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

ProviderEventIngestor.test.ts

1,237 lines45.5 KB

1import { assert, it } from "@effect/vitest";
2import {
3 MessageId,
4 type ModelSelection,
5 NodeId,
6 type OrchestrationV2AppThread,
7 type OrchestrationV2DomainEvent,
8 type OrchestrationV2ExecutionNode,
9 type OrchestrationV2PlanArtifact,
10 type OrchestrationV2RuntimeRequest,
11 type OrchestrationV2ProviderThread,
12 type OrchestrationV2Run,
13 type OrchestrationV2TurnItem,
14 ProviderDriverKind,
15 ProviderInstanceId,
16 PlanId,
17 RunAttemptId,
18 RunId,
19 RuntimeRequestId,
20 TurnItemId,
21} from "@t3tools/contracts";
22import * as DateTime from "effect/DateTime";
23import * as Deferred from "effect/Deferred";
24import * as Fiber from "effect/Fiber";
25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";
27import * as Stream from "effect/Stream";
28import * as TestClock from "effect/testing/TestClock";
29​
30import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
31import * as EventSink from "./EventSink.ts";
32import * as EventStore from "./EventStore.ts";
33import * as IdAllocator from "./IdAllocator.ts";
34import * as ProjectionStore from "./ProjectionStore.ts";
35import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
36import { makeProviderFailure } from "./ProviderFailure.ts";
37import {
38 makeProviderEventRoutingState,
39 type ProviderEventRouteIdentity,
40 routeProviderEvent,
41 selectInheritedBackgroundTurnItems,
42} from "./RunExecutionService.ts";
43​
44const TestDatabaseLayer = SqlitePersistenceMemory;
45const TestStoresLayer = Layer.merge(EventStore.layer, ProjectionStore.layer).pipe(
46 Layer.provide(TestDatabaseLayer),
47);
48​
49const TestEventSinkLayer = EventSink.layer.pipe(
50 Layer.provide(Layer.mergeAll(TestStoresLayer, TestDatabaseLayer)),
51);
52​
53const TestLayer = Layer.mergeAll(
54 TestStoresLayer,
55 TestEventSinkLayer,
56 IdAllocator.layer,
57 ProviderEventIngestor.layer.pipe(
58 Layer.provide(Layer.mergeAll(TestStoresLayer, TestEventSinkLayer, IdAllocator.layer)),
59 ),
60);
61const modelSelection = {
62 instanceId: ProviderInstanceId.make("codex"),
63 model: "gpt-5.4",
64} satisfies ModelSelection;
65const CODEX_DRIVER = ProviderDriverKind.make("codex");
66​
67function threadCreatedEvent(
68 now: DateTime.Utc,
69): Effect.Effect<
70 OrchestrationV2DomainEvent,
71 IdAllocator.IdAllocatorV2Error,
72 IdAllocator.IdAllocatorV2
73> {
74 return Effect.gen(function* () {
75 const idAllocator = yield* IdAllocator.IdAllocatorV2;
76 const projectId = yield* idAllocator.allocate.project({
77 fixtureName: "provider-event-ingestor",
78 });
79 const threadId = yield* idAllocator.allocate.thread({
80 fixtureName: "provider-event-ingestor",
81 projectId,
82 });
83 const providerThreadId = idAllocator.derive.providerThread({
84 driver: CODEX_DRIVER,
85 nativeThreadId: "native-thread",
86 });
87 const thread: OrchestrationV2AppThread = {
88 createdBy: "user",
89 creationSource: "web",
90 id: threadId,
91 projectId,
92 title: "Provider event ingestor",
93 providerInstanceId: modelSelection.instanceId,
94 modelSelection: modelSelection,
95 runtimeMode: "full-access",
96 interactionMode: "default",
97 branch: null,
98 worktreePath: null,
99 branchPullRequest: null,
100 activeOrderKey: null,
101 activeProviderThreadId: providerThreadId,
102 lineage: {
103 parentThreadId: null,
104 relationshipToParent: null,
105 rootThreadId: threadId,
106 },
107 forkedFrom: null,
108 createdAt: now,
109 updatedAt: now,
110 archivedAt: null,
111 settledOverride: null,
112 settledAt: null,
113 lastVisitedAt: null,
114 deletedAt: null,
115 };
116​
117 return {
118 id: yield* idAllocator.allocate.event({ threadId }),
119 type: "thread.created",
120 threadId,
121 occurredAt: now,
122 payload: thread,
123 };
124 });
126​
127const layer = it.layer(TestLayer);
128​
129it.effect("records accepted billed turn usage once without billing the context window", () => {
130 const recorded: Array<Readonly<Record<string, unknown>>> = [];
131 const analytics = Layer.succeed(ProviderEventIngestor.ProviderTurnAnalytics, {
132 record: (properties: Readonly<Record<string, unknown>>) =>
133 Effect.sync(() => {
134 recorded.push(properties);
135 }),
136 });
137 return Effect.gen(function* () {
138 const now = yield* DateTime.now;
139 const eventSink = yield* EventSink.EventSinkV2;
140 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
141 const idAllocator = yield* IdAllocator.IdAllocatorV2;
142 const threadEvent = yield* threadCreatedEvent(now);
143 yield* eventSink.write({ events: [threadEvent] });
144 const providerSessionId = yield* idAllocator.allocate.providerSession({
145 providerInstanceId: modelSelection.instanceId,
146 threadId: threadEvent.threadId,
147 });
148 const providerThreadId = idAllocator.derive.providerThread({
149 driver: CODEX_DRIVER,
150 nativeThreadId: "billing-thread",
151 });
152 const providerTurn = {
153 id: idAllocator.derive.providerTurn({ driver: CODEX_DRIVER, nativeTurnId: "billing-turn" }),
154 providerThreadId,
155 nodeId: NodeId.make("node:billing-turn"),
156 runAttemptId: null,
157 nativeTurnRef: null,
158 ordinal: 1,
159 status: "completed" as const,
160 startedAt: now,
161 completedAt: DateTime.makeUnsafe(DateTime.toEpochMillis(now) + 120),
162 tokenUsage: {
163 inputTokens: 4000,
164 cachedInputTokens: 3000,
165 outputTokens: 100,
166 usedTokens: 4100,
167 updatedAt: DateTime.formatIso(now),
168 },
169 turnTokenUsage: {
170 usageStatus: "complete" as const,
171 usageScope: "main_agent" as const,
172 hasSubagents: false,
173 inputTokens: 40,
174 cachedInputTokens: 30,
175 outputTokens: 10,
176 },
177 };
178 const input = {
179 providerSessionId,
180 providerInstanceId: modelSelection.instanceId,
181 threadId: threadEvent.threadId,
182 analyticsContext: {
183 modelSelection,
184 runtimeMode: "full-access" as const,
185 interactionMode: "default" as const,
186 },
187 event: { type: "provider_turn.updated" as const, driver: CODEX_DRIVER, providerTurn },
188 };
189 yield* ingestor.ingestNormalized(input);
190 yield* ingestor.ingestNormalized(input);
191 const ignored = yield* ingestor.ingestNormalized({
192 ...input,
193 event: {
194 ...input.event,
195 providerTurn: {
196 ...providerTurn,
197 id: idAllocator.derive.providerTurn({
198 driver: CODEX_DRIVER,
199 nativeTurnId: "stale-billing-turn",
200 }),
201 },
202 },
203 writeIfRunCurrent: {
204 runId: RunId.make("missing-run"),
205 activeAttemptId: RunAttemptId.make("stale-attempt"),
206 expectedStatus: "running",
207 },
208 });
209 assert.isEmpty(ignored);
210 assert.lengthOf(recorded, 1);
211 assert.deepEqual(recorded[0], {
212 provider: CODEX_DRIVER,
213 terminalStatus: "completed",
214 usageStatus: "complete",
215 usageScope: "main_agent",
216 hasSubagents: false,
217 inputTokens: 40,
218 cachedInputTokens: 30,
219 outputTokens: 10,
220 model: modelSelection.model,
221 mixedModels: false,
222 runtimeMode: "full-access",
223 interactionMode: "default",
224 durationMs: 120,
225 });
226 }).pipe(Effect.provide(TestLayer.pipe(Layer.provide(analytics))));
227});
228​
229layer("ProviderEventIngestorV2", (it) => {
230 it.effect("normalizes provider events through the real event log and projection store", () =>
231 Effect.gen(function* () {
232 const now = yield* DateTime.now;
233 const eventSink = yield* EventSink.EventSinkV2;
234 const eventStore = yield* EventStore.EventStoreV2;
235 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
236 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
237 const idAllocator = yield* IdAllocator.IdAllocatorV2;
238 const threadEvent = yield* threadCreatedEvent(now);
239 const providerSessionId = yield* idAllocator.allocate.providerSession({
240 providerInstanceId: modelSelection.instanceId,
241 threadId: threadEvent.threadId,
242 });
243 const providerThread: OrchestrationV2ProviderThread = {
244 id: idAllocator.derive.providerThread({
245 driver: CODEX_DRIVER,
246 nativeThreadId: "native-thread",
247 }),
248 driver: CODEX_DRIVER,
249 providerInstanceId: modelSelection.instanceId,
250 providerSessionId,
251 appThreadId: threadEvent.threadId,
252 ownerNodeId: null,
253 nativeThreadRef: {
254 driver: CODEX_DRIVER,
255 nativeId: "native-thread",
256 strength: "strong",
257 },
258 nativeConversationHeadRef: null,
259 status: "idle",
260 firstRunOrdinal: null,
261 lastRunOrdinal: null,
262 handoffIds: [],
263 forkedFrom: null,
264 createdAt: now,
265 updatedAt: now,
266 };
267​
268 yield* eventSink.write({ events: [threadEvent] });
269 const storedEvents = yield* ingestor.ingestNormalized({
270 providerSessionId,
271 providerInstanceId: modelSelection.instanceId,
272 threadId: threadEvent.threadId,
273 event: {
274 type: "provider_thread.updated",
275 driver: CODEX_DRIVER,
276 providerThread,
277 },
278 });
279​
280 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
281 const storedDomainEvents = yield* eventStore.read({}).pipe(Stream.runCollect);
282 const afterFirstEvent = yield* eventStore
283 .read({ afterSequence: 1, threadId: threadEvent.threadId })
284 .pipe(Stream.runCollect);
285 const latestThreadSequence = yield* eventStore.latestSequence({
286 threadId: threadEvent.threadId,
287 });
288​
289 assert.equal(storedEvents.length, 1);
290 assert.equal(storedEvents[0]?.event.type, "provider-thread.updated");
291 assert.deepEqual(
292 projection.providerThreads.map((thread) => thread.id),
293 [providerThread.id],
294 );
295 assert.deepEqual(
296 Array.from(storedDomainEvents).map((stored) => stored.event.type),
297 ["thread.created", "provider-thread.updated"],
298 );
299 assert.deepEqual(
300 Array.from(storedDomainEvents).map((stored) => stored.sequence),
301 [1, 2],
302 );
303 assert.deepEqual(
304 Array.from(afterFirstEvent).map((stored) => stored.event.type),
305 ["provider-thread.updated"],
306 );
307 assert.equal(latestThreadSequence, 2);
308 }),
309 );
310​
311 it.effect("carries plan-step durations through consecutive and restarted ingestion", () =>
312 Effect.gen(function* () {
313 yield* TestClock.setTime(Date.parse("2026-09-07T00:00:00.000Z"));
314 const now = yield* DateTime.now;
315 const eventSink = yield* EventSink.EventSinkV2;
316 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
317 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
318 const idAllocator = yield* IdAllocator.IdAllocatorV2;
319 const threadEvent = yield* threadCreatedEvent(now);
320 const providerSessionId = yield* idAllocator.allocate.providerSession({
321 providerInstanceId: modelSelection.instanceId,
322 threadId: threadEvent.threadId,
323 });
324 const planId = PlanId.make("plan:provider-event-duration");
325 const nodeId = NodeId.make("node:provider-event-duration");
326 type TodoListPlan = Extract<OrchestrationV2PlanArtifact, { readonly kind: "todo_list" }>;
327 const plan = (steps: TodoListPlan["steps"]): TodoListPlan => ({
328 id: planId,
329 threadId: threadEvent.threadId,
330 runId: null,
331 nodeId,
332 kind: "todo_list",
333 status: "active",
334 steps,
335 });
336 const ingest = (
337 service: ProviderEventIngestor.ProviderEventIngestorV2["Service"],
338 steps: TodoListPlan["steps"],
339 ) =>
340 service.ingestNormalized({
341 providerSessionId,
342 providerInstanceId: modelSelection.instanceId,
343 threadId: threadEvent.threadId,
344 event: { type: "plan.updated", driver: CODEX_DRIVER, plan: plan(steps) },
345 });
346​
347 yield* eventSink.write({ events: [threadEvent] });
348 yield* ingest(ingestor, [
349 { id: "duplicate-a", text: "Verify", status: "running" },
350 { id: "duplicate-b", text: "Verify", status: "pending" },
351 { id: "fallback", text: "Report", status: "pending" },
352 ]);
353 yield* TestClock.adjust("3 seconds");
354 yield* ingest(ingestor, [
355 { id: "duplicate-a", text: "Verify", status: "completed" },
356 { id: "duplicate-b", text: "Verify", status: "pending" },
357 { id: "fallback", text: "Report", status: "pending" },
358 ]);
359​
360 const restartedIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(
361 Effect.provide(
362 Layer.fresh(ProviderEventIngestor.layer).pipe(
363 Layer.provide(
364 Layer.succeed(ProjectionStore.ProjectionStoreV2, {
365 ...projectionStore,
366 getThreadProjection: () => Effect.die("Plan timing must not load thread history"),
367 }),
368 ),
369 ),
370 ),
371 );
372 yield* TestClock.adjust("4 seconds");
373 yield* ingest(restartedIngestor, [
374 { id: "duplicate-a", text: "Verify", status: "completed" },
375 { id: "duplicate-b", text: "Verify", status: "completed" },
376 { id: "fallback", text: "Report", status: "pending" },
377 ]);
378 yield* TestClock.adjust("5 seconds");
379 yield* ingest(restartedIngestor, [
380 { id: "duplicate-a", text: "Verify", status: "completed" },
381 { id: "duplicate-b", text: "Verify", status: "completed" },
382 { id: "fallback", text: "Report", status: "completed" },
383 ]);
384​
385 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
386 const persisted = projection.plans.find(
387 (candidate): candidate is TodoListPlan =>
388 candidate.kind === "todo_list" && candidate.id === planId,
389 );
390 assert.deepEqual(
391 persisted?.steps.map(({ id, text, status, durationMs }) => ({
392 id,
393 text,
394 status,
395 durationMs,
396 })),
397 [
398 { id: "duplicate-a", text: "Verify", status: "completed", durationMs: 3_000 },
399 { id: "duplicate-b", text: "Verify", status: "completed", durationMs: 4_000 },
400 { id: "fallback", text: "Report", status: "completed", durationMs: 5_000 },
401 ],
402 );
403​
404 yield* ingest(restartedIngestor, [
405 { id: "duplicate-a", text: "Inserted task", status: "running" },
406 { id: "duplicate-b", text: "Verify", status: "completed" },
407 { id: "fallback", text: "Different completed task", status: "completed" },
408 ]);
409 yield* TestClock.adjust("2 seconds");
410 yield* ingest(restartedIngestor, [
411 { id: "duplicate-a", text: "Inserted task", status: "completed" },
412 { id: "duplicate-b", text: "Verify", status: "completed" },
413 { id: "fallback", text: "Different completed task", status: "completed" },
414 ]);
415 const updated = yield* projectionStore.getThreadProjection(threadEvent.threadId);
416 const changedPlan = updated.plans.find(
417 (candidate): candidate is TodoListPlan =>
418 candidate.kind === "todo_list" && candidate.id === planId,
419 );
420 assert.deepEqual(
421 changedPlan?.steps.map((step) => step.durationMs),
422 [2_000, 4_000, undefined],
423 );
424 }),
425 );
426​
427 it.effect(
428 "treats successful provider terminal markers as non-persisted orchestration control signals",
429 () =>
430 Effect.gen(function* () {
431 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
432 const idAllocator = yield* IdAllocator.IdAllocatorV2;
433 const projectId = yield* idAllocator.allocate.project({
434 fixtureName: "provider-event-terminal",
435 });
436 const threadId = yield* idAllocator.allocate.thread({
437 fixtureName: "provider-event-terminal",
438 projectId,
439 });
440 const providerSessionId = yield* idAllocator.allocate.providerSession({
441 providerInstanceId: modelSelection.instanceId,
442 threadId,
443 });
444 const normalized = yield* ingestor.normalize({
445 providerSessionId,
446 providerInstanceId: modelSelection.instanceId,
447 threadId,
448 event: {
449 type: "turn.terminal",
450 driver: CODEX_DRIVER,
451 providerThreadId: idAllocator.derive.providerThread({
452 driver: CODEX_DRIVER,
453 nativeThreadId: "native-thread",
454 }),
455 providerTurnId: idAllocator.derive.providerTurn({
456 driver: CODEX_DRIVER,
457 nativeTurnId: "native-turn",
458 }),
459 runOrdinal: 1,
460 status: "completed",
461 failure: null,
462 threadDisposition: "reusable",
463 },
464 });
465​
466 assert.deepEqual(normalized, []);
467 }),
468 );
469​
470 it.effect("persists an interrupted run's inherited terminal through the live run router", () =>
471 Effect.gen(function* () {
472 const now = yield* DateTime.now;
473 const eventSink = yield* EventSink.EventSinkV2;
474 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
475 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
476 const idAllocator = yield* IdAllocator.IdAllocatorV2;
477 const threadEvent = yield* threadCreatedEvent(now);
478 const priorRunId = RunId.make("run:provider-event-inherited:prior");
479 const currentRunId = RunId.make("run:provider-event-inherited:current");
480 const itemId = TurnItemId.make("turn-item:provider-event-inherited");
481 const providerSessionId = yield* idAllocator.allocate.providerSession({
482 providerInstanceId: modelSelection.instanceId,
483 threadId: threadEvent.threadId,
484 });
485 const providerThreadId = idAllocator.derive.providerThread({
486 driver: CODEX_DRIVER,
487 nativeThreadId: "native-thread-inherited",
488 });
489 const providerTurnId = idAllocator.derive.providerTurn({
490 driver: CODEX_DRIVER,
491 nativeTurnId: "native-turn-inherited",
492 });
493 const runningItem = {
494 id: itemId,
495 threadId: threadEvent.threadId,
496 runId: priorRunId,
497 nodeId: NodeId.make("node:provider-event-inherited"),
498 providerThreadId,
499 providerTurnId,
500 nativeItemRef: null,
501 parentItemId: null,
502 ordinal: 101,
503 status: "running",
504 title: "Inherited background command",
505 startedAt: now,
506 completedAt: null,
507 updatedAt: now,
508 type: "command_execution",
509 input: "sleep 60",
510 } satisfies OrchestrationV2TurnItem;
511 const terminalItem = {
512 ...runningItem,
513 status: "completed" as const,
514 completedAt: now,
515 updatedAt: now,
516 };
517​
518 yield* eventSink.write({ events: [threadEvent] });
519 yield* ingestor.ingestNormalized({
520 providerSessionId,
521 providerInstanceId: modelSelection.instanceId,
522 threadId: threadEvent.threadId,
523 runId: priorRunId,
524 event: { type: "turn_item.updated", driver: CODEX_DRIVER, turnItem: runningItem },
525 });
526​
527 const identity: ProviderEventRouteIdentity = {
528 threadId: threadEvent.threadId,
529 runId: currentRunId,
530 attemptId: RunAttemptId.make("attempt:provider-event-inherited:current"),
531 providerThreadId,
532 };
533 const inheritedBackgroundTurnItems = selectInheritedBackgroundTurnItems({
534 threadId: threadEvent.threadId,
535 currentProviderThreadId: providerThreadId,
536 currentRunOrdinal: 2,
537 runs: [
538 {
539 id: priorRunId,
540 threadId: threadEvent.threadId,
541 ordinal: 1,
542 status: "interrupted",
543 } as OrchestrationV2Run,
544 {
545 id: currentRunId,
546 threadId: threadEvent.threadId,
547 ordinal: 2,
548 status: "running",
549 } as OrchestrationV2Run,
550 ],
551 turnItems: [runningItem],
552 });
553 const routeState = makeProviderEventRoutingState({
554 identity,
555 inheritedBackgroundTurnItems,
556 providerTurnId: null,
557 });
558 const terminalEvent = {
559 type: "turn_item.updated",
560 driver: CODEX_DRIVER,
561 turnItem: terminalItem,
562 } as const;
563 const [accepted] = routeProviderEvent(terminalEvent, identity, routeState);
564 assert.isTrue(accepted);
565​
566 const stored = yield* ingestor.ingestNormalized({
567 providerSessionId,
568 providerInstanceId: modelSelection.instanceId,
569 threadId: threadEvent.threadId,
570 runId: currentRunId,
571 event: terminalEvent,
572 });
573 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
574 const persisted = projection.turnItems.find((item) => item.id === itemId);
575​
576 assert.equal(stored.length, 1);
577 assert.equal(stored[0]?.event.type, "turn-item.updated");
578 assert.equal(persisted?.runId, priorRunId);
579 assert.equal(persisted?.threadId, threadEvent.threadId);
580 assert.equal(persisted?.status, "completed");
581 }),
582 );
583​
584 it.effect("persists a completed run's late background terminal exactly once", () =>
585 Effect.gen(function* () {
586 const now = yield* DateTime.now;
587 const eventSink = yield* EventSink.EventSinkV2;
588 const eventStore = yield* EventStore.EventStoreV2;
589 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
590 const idAllocator = yield* IdAllocator.IdAllocatorV2;
591 const threadEvent = yield* threadCreatedEvent(now);
592 const priorRunId = RunId.make("run:provider-event-completed:prior");
593 const currentRunId = RunId.make("run:provider-event-completed:current");
594 const itemId = TurnItemId.make("turn-item:provider-event-completed");
595 const providerSessionId = yield* idAllocator.allocate.providerSession({
596 providerInstanceId: modelSelection.instanceId,
597 threadId: threadEvent.threadId,
598 });
599 const providerThreadId = idAllocator.derive.providerThread({
600 driver: CODEX_DRIVER,
601 nativeThreadId: "native-thread-completed",
602 });
603 const providerTurnId = idAllocator.derive.providerTurn({
604 driver: CODEX_DRIVER,
605 nativeTurnId: "native-turn-completed",
606 });
607 const runningItem = {
608 id: itemId,
609 threadId: threadEvent.threadId,
610 runId: priorRunId,
611 nodeId: NodeId.make("node:provider-event-completed"),
612 providerThreadId,
613 providerTurnId,
614 nativeItemRef: null,
615 parentItemId: null,
616 ordinal: 101,
617 status: "running",
618 title: "Completed run background command",
619 startedAt: now,
620 completedAt: null,
621 updatedAt: now,
622 type: "command_execution",
623 input: "sleep 60",
624 } satisfies OrchestrationV2TurnItem;
625 const terminalEvent = {
626 type: "turn_item.updated",
627 driver: CODEX_DRIVER,
628 turnItem: {
629 ...runningItem,
630 status: "completed" as const,
631 completedAt: now,
632 updatedAt: now,
633 },
634 } as const;
635​
636 yield* eventSink.write({ events: [threadEvent] });
637 yield* ingestor.ingestNormalized({
638 providerSessionId,
639 providerInstanceId: modelSelection.instanceId,
640 threadId: threadEvent.threadId,
641 runId: priorRunId,
642 event: { type: "turn_item.updated", driver: CODEX_DRIVER, turnItem: runningItem },
643 });
644​
645 const priorIdentity: ProviderEventRouteIdentity = {
646 threadId: threadEvent.threadId,
647 runId: priorRunId,
648 attemptId: RunAttemptId.make("attempt:provider-event-completed:prior"),
649 providerThreadId,
650 };
651 const currentIdentity: ProviderEventRouteIdentity = {
652 threadId: threadEvent.threadId,
653 runId: currentRunId,
654 attemptId: RunAttemptId.make("attempt:provider-event-completed:current"),
655 providerThreadId,
656 };
657 const inheritedBackgroundTurnItems = selectInheritedBackgroundTurnItems({
658 threadId: threadEvent.threadId,
659 currentProviderThreadId: providerThreadId,
660 currentRunOrdinal: 2,
661 runs: [
662 {
663 id: priorRunId,
664 threadId: threadEvent.threadId,
665 ordinal: 1,
666 status: "completed",
667 } as OrchestrationV2Run,
668 {
669 id: currentRunId,
670 threadId: threadEvent.threadId,
671 ordinal: 2,
672 status: "running",
673 } as OrchestrationV2Run,
674 ],
675 turnItems: [runningItem],
676 });
677 const routers = [
678 {
679 identity: priorIdentity,
680 state: makeProviderEventRoutingState({
681 identity: priorIdentity,
682 providerTurnId: providerTurnId,
683 }),
684 },
685 {
686 identity: currentIdentity,
687 state: makeProviderEventRoutingState({
688 identity: currentIdentity,
689 inheritedBackgroundTurnItems,
690 providerTurnId: null,
691 }),
692 },
693 ];
694 const acceptedRouters = routers.filter(
695 ({ identity, state }) => routeProviderEvent(terminalEvent, identity, state)[0],
696 );
697​
698 yield* Effect.forEach(
699 acceptedRouters,
700 ({ identity }) =>
701 ingestor.ingestNormalized({
702 providerSessionId,
703 providerInstanceId: modelSelection.instanceId,
704 threadId: threadEvent.threadId,
705 runId: identity.runId,
706 event: terminalEvent,
707 }),
708 { concurrency: 1 },
709 );
710​
711 const storedEvents = yield* eventStore
712 .read({ threadId: threadEvent.threadId })
713 .pipe(Stream.runCollect);
714 const storedTerminals = Array.from(storedEvents).filter(
715 (stored) =>
716 stored.event.type === "turn-item.updated" &&
717 stored.event.payload.id === itemId &&
718 stored.event.payload.status === "completed",
719 );
720​
721 assert.equal(storedTerminals.length, 1);
722 assert.equal(acceptedRouters.length, 1);
723 assert.equal(acceptedRouters[0]?.identity.runId, priorRunId);
724 }),
725 );
726​
727 for (const terminal of ["completed", "interrupted", "failed", "cancelled", "control"] as const) {
728 it.effect(`dismisses only native questions when a provider turn ends with ${terminal}`, () =>
729 Effect.gen(function* () {
730 const now = yield* DateTime.now;
731 const eventSink = yield* EventSink.EventSinkV2;
732 const eventStore = yield* EventStore.EventStoreV2;
733 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
734 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
735 const idAllocator = yield* IdAllocator.IdAllocatorV2;
736 const threadEvent = yield* threadCreatedEvent(now);
737 const threadId = threadEvent.threadId;
738 const providerSessionId = yield* idAllocator.allocate.providerSession({
739 providerInstanceId: modelSelection.instanceId,
740 threadId,
741 });
742 const providerThreadId = idAllocator.derive.providerThread({
743 driver: CODEX_DRIVER,
744 nativeThreadId: `${threadId}:questions`,
745 });
746 const providerTurnId = idAllocator.derive.providerTurn({
747 driver: CODEX_DRIVER,
748 nativeTurnId: `${threadId}:questions`,
749 });
750 const otherTurnId = idAllocator.derive.providerTurn({
751 driver: CODEX_DRIVER,
752 nativeTurnId: `${threadId}:other-turn`,
753 });
754 const specs = [
755 { key: "native", responseCapability: { type: "live", providerSessionId } },
756 {
757 key: "unavailable",
758 responseCapability: { type: "not_resumable", reason: "Turn ended" },
759 },
760 { key: "message", responseCapability: { type: "message" } },
761 { key: "answered", responseCapability: { type: "live", providerSessionId } },
762 { key: "other-turn", responseCapability: { type: "live", providerSessionId } },
763 { key: "approval", responseCapability: { type: "live", providerSessionId } },
764 ] as const;
765 const fixtures = specs.map((spec, ordinal) => {
766 const nodeId = NodeId.make(`${threadId}:${spec.key}`);
767 const resolved = spec.key === "answered";
768 const request: OrchestrationV2RuntimeRequest = {
769 id: RuntimeRequestId.make(`${threadId}:${spec.key}`),
770 nodeId,
771 providerTurnId: spec.key === "other-turn" ? otherTurnId : providerTurnId,
772 nativeRequestRef: null,
773 kind: spec.key === "approval" ? "command" : "user_input",
774 status: resolved ? "resolved" : "pending",
775 responseCapability: spec.responseCapability,
776 createdAt: now,
777 resolvedAt: resolved ? now : null,
778 };
779 const node: OrchestrationV2ExecutionNode = {
780 id: nodeId,
781 threadId,
782 runId: null,
783 parentNodeId: null,
784 rootNodeId: nodeId,
785 kind: spec.key === "approval" ? "approval_request" : "user_input_request",
786 status: resolved ? "completed" : "waiting",
787 countsForRun: false,
788 providerThreadId,
789 providerTurnId: request.providerTurnId,
790 nativeItemRef: null,
791 runtimeRequestId: request.id,
792 checkpointScopeId: null,
793 startedAt: now,
794 completedAt: resolved ? now : null,
795 };
796 const item: OrchestrationV2TurnItem = {
797 id: TurnItemId.make(`${threadId}:${spec.key}`),
798 threadId,
799 runId: null,
800 nodeId,
801 providerThreadId,
802 providerTurnId: request.providerTurnId,
803 nativeItemRef: null,
804 parentItemId: null,
805 ordinal,
806 status: resolved ? "completed" : "waiting",
807 title: "Which option?",
808 startedAt: now,
809 completedAt: resolved ? now : null,
810 updatedAt: now,
811 ...(spec.key === "approval"
812 ? { type: "approval_request", requestId: request.id, requestKind: "command" }
813 : {
814 type: "user_input_request",
815 requestId: request.id,
816 questions: [],
817 ...(spec.key === "message" ? { responseMode: "message" as const } : {}),
818 }),
819 };
820 return { key: spec.key, request, node, item };
821 });
822 const seedEvents: Array<OrchestrationV2DomainEvent> = [threadEvent];
823 for (const fixture of fixtures) {
824 for (const payload of [
825 { type: "runtime-request.updated" as const, payload: fixture.request },
826 { type: "node.updated" as const, payload: fixture.node },
827 { type: "turn-item.updated" as const, payload: fixture.item },
828 ]) {
829 seedEvents.push({
830 id: yield* idAllocator.allocate.event({ threadId }),
831 threadId,
832 occurredAt: now,
833 ...payload,
834 });
835 }
836 }
837 yield* eventSink.write({ events: seedEvents });
838 const input = {
839 providerSessionId,
840 providerInstanceId: modelSelection.instanceId,
841 threadId,
842 event:
843 terminal === "control"
844 ? {
845 type: "turn.terminal" as const,
846 driver: CODEX_DRIVER,
847 providerThreadId,
848 providerTurnId,
849 runOrdinal: 1,
850 status: "completed" as const,
851 failure: null,
852 threadDisposition: "reusable" as const,
853 }
854 : {
855 type: "provider_turn.updated" as const,
856 driver: CODEX_DRIVER,
857 providerTurn: {
858 id: providerTurnId,
859 providerThreadId,
860 nodeId: NodeId.make(`${threadId}:root`),
861 runAttemptId: null,
862 nativeTurnRef: null,
863 ordinal: 1,
864 status: terminal,
865 startedAt: now,
866 completedAt: now,
867 },
868 },
869 };
870 const stored = yield* ingestor.ingestNormalized(input);
871 const projection = yield* projectionStore.getThreadProjection(threadId);
872 for (const fixture of fixtures) {
873 const closed = fixture.key === "native" || fixture.key === "unavailable";
874 const request = projection.runtimeRequests.find(
875 (item) => item.id === fixture.request.id,
876 )!;
877 const node = projection.nodes.find((item) => item.id === fixture.node.id)!;
878 const item = projection.turnItems.find((item) => item.id === fixture.item.id)!;
879 if (closed) {
880 assert.equal(request.status, "cancelled");
881 assert.isNotNull(request.resolvedAt);
882 assert.equal(node.status, "cancelled");
883 assert.isNotNull(node.completedAt);
884 assert.equal(item.status, "cancelled");
885 assert.isNotNull(item.completedAt);
886 } else {
887 assert.equal(request.status, fixture.request.status);
888 assert.equal(node.status, fixture.node.status);
889 assert.equal(item.status, fixture.item.status);
890 }
891 }
892 assert.equal(
893 stored.filter((entry) => entry.event.type === "runtime-request.updated").length,
894 2,
895 );
896 assert.isEmpty(
897 (yield* projectionStore.getPendingNativeUserInputs(threadId, providerTurnId))
898 .runtimeRequests,
899 );
900 const replayed = yield* eventStore.read({ threadId }).pipe(Stream.runCollect);
901 assert.equal(
902 replayed.filter(
903 (entry) =>
904 entry.event.type === "runtime-request.updated" &&
905 entry.event.payload.status === "cancelled",
906 ).length,
907 2,
908 );
909 const repeated = yield* ingestor.ingestNormalized(input);
910 assert.isFalse(repeated.some((entry) => entry.event.type === "runtime-request.updated"));
911 }),
912 );
913 }
914​
915 it.effect(
916 "preserves an answer committed after terminal normalization reads a pending question",
917 () =>
918 Effect.scoped(
919 Effect.gen(function* () {
920 const eventSink = yield* EventSink.EventSinkV2;
921 const eventStore = yield* EventStore.EventStoreV2;
922 const projections = yield* ProjectionStore.ProjectionStoreV2;
923 const idAllocator = yield* IdAllocator.IdAllocatorV2;
924 const now = yield* DateTime.now;
925 const threadEvent = yield* threadCreatedEvent(now);
926 const threadId = threadEvent.threadId;
927 const providerSessionId = yield* idAllocator.allocate.providerSession({
928 providerInstanceId: modelSelection.instanceId,
929 threadId,
930 });
931 const providerThreadId = idAllocator.derive.providerThread({
932 driver: CODEX_DRIVER,
933 nativeThreadId: `${threadId}:race`,
934 });
935 const providerTurnId = idAllocator.derive.providerTurn({
936 driver: CODEX_DRIVER,
937 nativeTurnId: `${threadId}:race`,
938 });
939 const nodeId = NodeId.make(`${threadId}:question`);
940 const request: OrchestrationV2RuntimeRequest = {
941 id: RuntimeRequestId.make(`${threadId}:question`),
942 nodeId,
943 providerTurnId,
944 nativeRequestRef: null,
945 kind: "user_input",
946 status: "pending",
947 responseCapability: { type: "live", providerSessionId },
948 createdAt: now,
949 resolvedAt: null,
950 };
951 const node: OrchestrationV2ExecutionNode = {
952 id: nodeId,
953 threadId,
954 runId: null,
955 parentNodeId: null,
956 rootNodeId: nodeId,
957 kind: "user_input_request",
958 status: "waiting",
959 countsForRun: false,
960 providerThreadId,
961 providerTurnId,
962 nativeItemRef: null,
963 runtimeRequestId: request.id,
964 checkpointScopeId: null,
965 startedAt: now,
966 completedAt: null,
967 };
968 const item: OrchestrationV2TurnItem = {
969 id: TurnItemId.make(`${threadId}:question`),
970 threadId,
971 runId: null,
972 nodeId,
973 providerThreadId,
974 providerTurnId,
975 nativeItemRef: null,
976 parentItemId: null,
977 ordinal: 1,
978 status: "waiting",
979 title: "Which option?",
980 startedAt: now,
981 completedAt: null,
982 updatedAt: now,
983 type: "user_input_request",
984 requestId: request.id,
985 questions: [],
986 };
987 const seedEvents: Array<OrchestrationV2DomainEvent> = [threadEvent];
988 for (const payload of [
989 { type: "runtime-request.updated" as const, payload: request },
990 { type: "node.updated" as const, payload: node },
991 { type: "turn-item.updated" as const, payload: item },
992 ])
993 seedEvents.push({
994 id: yield* idAllocator.allocate.event({ threadId }),
995 threadId,
996 occurredAt: now,
997 ...payload,
998 });
999 yield* eventSink.write({ events: seedEvents });
1000 const normalized = yield* Deferred.make<void>();
1001 const releaseTerminalWrite = yield* Deferred.make<void>();
1002 const gatedSink = EventSink.EventSinkV2.of({
1003 ...eventSink,
1004 write: (input) =>
1005 Deferred.succeed(normalized, undefined).pipe(
1006 Effect.andThen(Deferred.await(releaseTerminalWrite)),
1007 Effect.andThen(eventSink.write(input)),
1008 ),
1009 });
1010 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(
1011 Effect.provide(Layer.fresh(ProviderEventIngestor.layer)),
1012 Effect.provideService(EventSink.EventSinkV2, gatedSink),
1013 );
1014 const terminal = yield* ingestor
1015 .ingestNormalized({
1016 providerSessionId,
1017 providerInstanceId: modelSelection.instanceId,
1018 threadId,
1019 event: {
1020 type: "provider_turn.updated",
1021 driver: CODEX_DRIVER,
1022 providerTurn: {
1023 id: providerTurnId,
1024 providerThreadId,
1025 nodeId,
1026 runAttemptId: null,
1027 nativeTurnRef: null,
1028 ordinal: 1,
1029 status: "completed",
1030 startedAt: now,
1031 completedAt: now,
1032 },
1033 },
1034 })
1035 .pipe(Effect.forkScoped);
1036 yield* Deferred.await(normalized);
1037 const answers = { decision: "Use the existing workspace" };
1038 const responseEvents: Array<OrchestrationV2DomainEvent> = [];
1039 for (const payload of [
1041 type: "runtime-request.updated" as const,
1042 payload: { ...request, status: "resolved" as const, answers, resolvedAt: now },
1043 },
1045 type: "node.updated" as const,
1046 payload: { ...node, status: "completed" as const, completedAt: now },
1047 },
1049 type: "turn-item.updated" as const,
1050 payload: { ...item, status: "completed" as const, completedAt: now },
1051 },
1052 ])
1053 responseEvents.push({
1054 id: yield* idAllocator.allocate.event({ threadId }),
1055 threadId,
1056 occurredAt: now,
1057 ...payload,
1058 });
1059 yield* eventSink.write({ events: responseEvents });
1060 yield* Deferred.succeed(releaseTerminalWrite, undefined);
1061 const committedTerminal = yield* Fiber.join(terminal);
1062 assert.deepEqual(
1063 committedTerminal.map((stored) => stored.event.type),
1064 ["provider-turn.updated"],
1065 );
1066 const projection = yield* projections.getThreadProjection(threadId);
1067 const answered = projection.runtimeRequests.find((entry) => entry.id === request.id)!;
1068 assert.equal(answered.status, "resolved");
1069 assert.deepEqual(answered.answers, answers);
1070 assert.equal(projection.nodes.find((entry) => entry.id === nodeId)!.status, "completed");
1071 assert.equal(
1072 projection.turnItems.find((entry) => entry.id === item.id)!.status,
1073 "completed",
1074 );
1075 const history = yield* eventStore.read({ threadId }).pipe(Stream.runCollect);
1076 assert.isFalse(
1077 history.some(
1078 (stored) =>
1079 stored.event.type === "runtime-request.updated" &&
1080 stored.event.payload.status === "cancelled",
1081 ),
1082 );
1083 }),
1084 ),
1085 );
1086​
1087 it.effect("persists a failed provider terminal as one expected error item", () =>
1088 Effect.gen(function* () {
1089 const now = yield* DateTime.now;
1090 const retryStartedAt = DateTime.makeUnsafe(DateTime.toEpochMillis(now) - 5_000);
1091 const eventSink = yield* EventSink.EventSinkV2;
1092 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
1093 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
1094 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1095 const threadEvent = yield* threadCreatedEvent(now);
1096 const providerSessionId = yield* idAllocator.allocate.providerSession({
1097 providerInstanceId: modelSelection.instanceId,
1098 threadId: threadEvent.threadId,
1099 });
1100 const providerThreadId = idAllocator.derive.providerThread({
1101 driver: CODEX_DRIVER,
1102 nativeThreadId: "native-thread-failed",
1103 });
1104 const providerTurnId = idAllocator.derive.providerTurn({
1105 driver: CODEX_DRIVER,
1106 nativeTurnId: "native-turn-failed",
1107 });
1108​
1109 yield* eventSink.write({ events: [threadEvent] });
1110 const stored = yield* ingestor.ingestNormalized({
1111 providerSessionId,
1112 providerInstanceId: modelSelection.instanceId,
1113 threadId: threadEvent.threadId,
1114 event: {
1115 type: "turn.terminal",
1116 driver: CODEX_DRIVER,
1117 providerThreadId,
1118 providerTurnId,
1119 runOrdinal: 1,
1120 failureItemOrdinal: 102,
1121 status: "failed",
1122 failure: makeProviderFailure({
1123 message: "Invalid reasoning effort.",
1124 code: "invalid_request",
1125 class: "validation_error",
1126 }),
1127 retry: {
1128 attempt: 3,
1129 maxAttempts: 3,
1130 retryDelayMs: 2_000,
1131 },
1132 retryStartedAt,
1133 threadDisposition: "reusable",
1134 },
1135 });
1136​
1137 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
1138 const errorItems = projection.visibleTurnItems.filter(
1139 (candidate) => candidate.item.type === "error",
1140 );
1141​
1142 assert.equal(stored.length, 1);
1143 assert.equal(stored[0]?.event.type, "turn-item.updated");
1144 assert.equal(errorItems.length, 1);
1145 const errorItem = errorItems[0]?.item;
1146 assert.equal(errorItem?.type, "error");
1147 if (errorItem?.type !== "error") return;
1148 assert.equal(errorItem.failure.message, "Invalid reasoning effort.");
1149 assert.equal(errorItem.failure.code, "invalid_request");
1150 assert.deepEqual(errorItem.retry, {
1151 attempt: 3,
1152 maxAttempts: 3,
1153 retryDelayMs: 2_000,
1154 });
1155 const errorStartedAt = errorItem.startedAt;
1156 assert.ok(errorStartedAt);
1157 assert.equal(DateTime.toEpochMillis(errorStartedAt), DateTime.toEpochMillis(retryStartedAt));
1158 assert.equal(errorItem.providerThreadId, providerThreadId);
1159 assert.equal(errorItem.providerTurnId, providerTurnId);
1160 }),
1161 );
1162​
1163 it.effect("routes provider-owned child artifacts to their child app thread", () =>
1164 Effect.gen(function* () {
1165 const now = yield* DateTime.now;
1166 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
1167 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1168 const rootEvent = yield* threadCreatedEvent(now);
1169 if (rootEvent.type !== "thread.created") {
1170 throw new Error("Expected a thread.created fixture event");
1172 const childThreadId = idAllocator.derive.threadFromProviderThread({
1173 driver: CODEX_DRIVER,
1174 nativeThreadId: "native-subagent-thread",
1175 });
1176 const childRootNodeId = NodeId.make("node:subagent-root");
1177 const childThread: OrchestrationV2AppThread = {
1178 ...rootEvent.payload,
1179 id: childThreadId,
1180 title: "inspect package",
1181 activeProviderThreadId: null,
1182 lineage: {
1183 parentThreadId: rootEvent.threadId,
1184 relationshipToParent: "subagent",
1185 rootThreadId: rootEvent.threadId,
1186 },
1187 forkedFrom: {
1188 type: "node",
1189 nodeId: NodeId.make("node:parent-subagent"),
1190 },
1191 };
1192 const providerSessionId = yield* idAllocator.allocate.providerSession({
1193 providerInstanceId: modelSelection.instanceId,
1194 threadId: rootEvent.threadId,
1195 });
1196​
1197 const threadEvents = yield* ingestor.normalize({
1198 providerSessionId,
1199 providerInstanceId: modelSelection.instanceId,
1200 threadId: rootEvent.threadId,
1201 event: {
1202 type: "app_thread.created",
1203 driver: CODEX_DRIVER,
1204 appThread: childThread,
1205 },
1206 });
1207 const messageEvents = yield* ingestor.normalize({
1208 providerSessionId,
1209 providerInstanceId: modelSelection.instanceId,
1210 threadId: rootEvent.threadId,
1211 event: {
1212 type: "message.updated",
1213 driver: CODEX_DRIVER,
1214 message: {
1215 createdBy: "agent",
1216 creationSource: "provider",
1217 id: MessageId.make("message:subagent-response"),
1218 threadId: childThreadId,
1219 runId: null,
1220 nodeId: childRootNodeId,
1221 role: "assistant",
1222 text: "Subagent result",
1223 attachments: [],
1224 streaming: false,
1225 createdAt: now,
1226 updatedAt: now,
1227 },
1228 },
1229 });
1230​
1231 assert.equal(threadEvents[0]?.type, "thread.created");
1232 assert.equal(threadEvents[0]?.threadId, childThreadId);
1233 assert.equal(messageEvents[0]?.type, "message.updated");
1234 assert.equal(messageEvents[0]?.threadId, childThreadId);
1235 }),
1236 );
1237});