Open History to see the last commit
1import { assert, it, vi } from "@effect/vitest";
2import {
3 MessageId,
4 NodeId,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 ProviderSessionId,
8 ProviderThreadId,
9 ProviderTurnId,
10 RunAttemptId,
11 RunId,
12 RuntimeRequestId,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationV2ThreadProjection,
16} from "@t3tools/contracts";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Ref from "effect/Ref";
20
21import * as EffectWorker from "./EffectWorker.ts";
22import * as EffectOutbox from "./EffectOutbox.ts";
23import * as EventSink from "./EventSink.ts";
24import * as IdAllocator from "./IdAllocator.ts";
25import * as ProjectionStore from "./ProjectionStore.ts";
26import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
27
28it.effect("drains durable effects before reporting recovery complete", () =>
29 Effect.gen(function* () {
30 const runs = yield* Ref.make(0);
31 const layer = ProviderRuntimeRecovery.layer.pipe(
32 Layer.provide(
33 Layer.mergeAll(
34 Layer.mock(ProjectionStore.ProjectionStoreV2)({
35 getShellSnapshot: () =>
36 Effect.succeed({
37 schemaVersion: 2,
38 snapshotSequence: 0,
39 threads: [],
40 archivedThreads: [],
41 }),
42 }),
43 Layer.mock(EventSink.EventSinkV2)({}),
44 IdAllocator.layer,
45 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
46 runOnce: Ref.getAndUpdate(runs, (count) => count + 1).pipe(
47 Effect.map((count) => count < 2),
48 ),
49 }),
50 Layer.mock(EffectOutbox.EffectOutboxV2)({
51 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
52 }),
53 ),
54 ),
55 );
56 const summary = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService.pipe(
57 Effect.flatMap((recovery) => recovery.recover),
58 Effect.provide(layer),
59 );
60 assert.deepEqual(summary, {
61 terminalizedRuns: 0,
62 stoppedSessions: 0,
63 closedRequests: 0,
64 retiredEffects: 0,
65 requeuedEffects: 0,
66 executedEffects: 2,
67 });
68 }),
69);
70
71it.effect("expires orphaned runtime requests before command readiness", () => {
72 const threadId = ThreadId.make("thread_recovery_requests");
73 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
74 null;
75 const committed = vi.fn(
76 (input: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0]) => {
77 committedInput = input;
78 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
79 },
80 );
81 const projection = {
82 thread: { id: threadId },
83 runtimeRequests: [
84 {
85 id: RuntimeRequestId.make("request_orphaned"),
86 nodeId: NodeId.make("node_orphaned"),
87 status: "pending",
88 responseCapability: { type: "not_resumable", reason: "old process" },
89 },
90 ],
91 providerSessions: [],
92 providerThreads: [],
93 runs: [],
94 nodes: [],
95 } as unknown as OrchestrationV2ThreadProjection;
96 const layer = ProviderRuntimeRecovery.layer.pipe(
97 Layer.provide(
98 Layer.mergeAll(
99 Layer.mock(ProjectionStore.ProjectionStoreV2)({
100 getShellSnapshot: () =>
101 Effect.succeed({
102 schemaVersion: 2,
103 snapshotSequence: 0,
104 threads: [{ id: threadId }],
105 archivedThreads: [],
106 } as never),
107 getThreadProjection: () => Effect.succeed(projection),
108 }),
109 Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }),
110 IdAllocator.layer,
111 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
112 Layer.mock(EffectOutbox.EffectOutboxV2)({
113 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
114 }),
115 ),
116 ),
117 );
118 return Effect.gen(function* () {
119 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).recover;
120 const command = committedInput;
121 assert.isNotNull(command);
122 if (command === null) return;
123 assert.equal(command?.events[0]?.type, "runtime-request.updated");
124 if (command?.events[0]?.type === "runtime-request.updated") {
125 assert.equal(command.events[0].payload.status, "expired");
126 assert.equal(command.events[0].payload.responseCapability.type, "not_resumable");
127 }
128 }).pipe(Effect.provide(layer));
129});
130
131it.effect("uses the same reconciliation path to cancel runtime requests during shutdown", () => {
132 const threadId = ThreadId.make("thread_shutdown_requests");
133 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
134 null;
135 const projection = {
136 thread: { id: threadId },
137 runtimeRequests: [
138 {
139 id: RuntimeRequestId.make("request_shutdown"),
140 nodeId: NodeId.make("node_shutdown"),
141 status: "pending",
142 responseCapability: { type: "live" },
143 },
144 ],
145 providerSessions: [],
146 providerThreads: [],
147 runs: [],
148 nodes: [],
149 } as unknown as OrchestrationV2ThreadProjection;
150 const layer = ProviderRuntimeRecovery.layer.pipe(
151 Layer.provide(
152 Layer.mergeAll(
153 Layer.mock(ProjectionStore.ProjectionStoreV2)({
154 getShellSnapshot: () =>
155 Effect.succeed({
156 schemaVersion: 2,
157 snapshotSequence: 0,
158 threads: [{ id: threadId }],
159 archivedThreads: [],
160 } as never),
161 getThreadProjection: () => Effect.succeed(projection),
162 }),
163 Layer.mock(EventSink.EventSinkV2)({
164 commitCommand: (input) => {
165 committedInput = input;
166 return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
167 },
168 }),
169 IdAllocator.layer,
170 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
171 Layer.mock(EffectOutbox.EffectOutboxV2)({
172 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
173 }),
174 ),
175 ),
176 );
177
178 return Effect.gen(function* () {
179 const summary =
180 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("shutdown");
181 assert.equal(summary.closedRequests, 1);
182 assert.equal(summary.retiredEffects, 1);
183 const requestEvent = committedInput?.events[0];
184 assert.equal(requestEvent?.type, "runtime-request.updated");
185 if (requestEvent?.type === "runtime-request.updated") {
186 assert.equal(requestEvent.payload.status, "cancelled");
187 assert.equal(requestEvent.payload.responseCapability.type, "not_resumable");
188 if (requestEvent.payload.responseCapability.type === "not_resumable") {
189 assert.match(requestEvent.payload.responseCapability.reason, /shut down/);
190 }
191 }
192 }).pipe(Effect.provide(layer));
193});
194
195it.effect(
196 "preserves a replayable waiting run while cancelling its process-bound background work",
197 () => {
198 const threadId = ThreadId.make("thread_waiting_checkpoint");
199 const runId = RunId.make("run_waiting_checkpoint");
200 const providerThreadId = ProviderThreadId.make("provider_thread_waiting_checkpoint");
201 const providerInstanceId = ProviderInstanceId.make("claude");
202 const backgroundItemId = TurnItemId.make("turn_item_waiting_checkpoint");
203 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
204 null;
205 const projection = {
206 thread: { id: threadId },
207 runtimeRequests: [],
208 providerSessions: [],
209 providerThreads: [
210 {
211 id: providerThreadId,
212 driver: ProviderDriverKind.make("claude"),
213 providerInstanceId,
214 status: "idle",
215 pendingBackgroundTasks: [
216 { taskId: String(backgroundItemId), description: "Finish background task" },
217 ],
218 },
219 ],
220 runs: [{ id: runId, status: "waiting", providerInstanceId }],
221 attempts: [],
222 nodes: [],
223 subagents: [],
224 messages: [],
225 turnItems: [
226 {
227 id: backgroundItemId,
228 runId,
229 nodeId: null,
230 providerThreadId,
231 type: "command_execution",
232 status: "running",
233 },
234 ],
235 } as unknown as OrchestrationV2ThreadProjection;
236 const layer = ProviderRuntimeRecovery.layer.pipe(
237 Layer.provide(
238 Layer.mergeAll(
239 Layer.mock(ProjectionStore.ProjectionStoreV2)({
240 getShellSnapshot: () =>
241 Effect.succeed({
242 schemaVersion: 2,
243 snapshotSequence: 0,
244 threads: [{ id: threadId }],
245 archivedThreads: [],
246 } as never),
247 getThreadProjection: () => Effect.succeed(projection),
248 }),
249 Layer.mock(EventSink.EventSinkV2)({
250 commitCommand: (input) => {
251 committedInput = input;
252 return Effect.succeed({
253 committed: true,
254 cancelledEffectCount: 0,
255 } as never);
256 },
257 }),
258 IdAllocator.layer,
259 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
260 Layer.mock(EffectOutbox.EffectOutboxV2)({
261 listByCommandId: () =>
262 Effect.succeed([
263 {
264 request: { type: "checkpoint.capture", runId },
265 status: "running",
266 },
267 ] as never),
268 reconcileAfterProcessLoss: Effect.succeed({ requeued: 1, cancelled: 0 }),
269 }),
270 ),
271 ),
272 );
273
274 return Effect.gen(function* () {
275 const summary =
276 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
277 assert.equal(summary.terminalizedRuns, 0);
278 assert.equal(summary.requeuedEffects, 1);
279
280 const command = committedInput;
281 assert.isNotNull(command);
282 if (command === null) return;
283 assert.isFalse(command.events.some((event) => event.type === "run.updated"));
284 assert.isTrue(
285 command.events.some(
286 (event) =>
287 event.type === "turn-item.updated" &&
288 event.payload.id === backgroundItemId &&
289 event.payload.status === "cancelled",
290 ),
291 );
292 assert.isTrue(
293 command.events.some(
294 (event) =>
295 event.type === "provider-thread.updated" &&
296 event.payload.id === providerThreadId &&
297 event.payload.pendingBackgroundTasks?.length === 0,
298 ),
299 );
300 }).pipe(Effect.provide(layer));
301 },
302);
303
304it.effect("cancels a stale waiting run when no checkpoint capture can finish it", () => {
305 const threadId = ThreadId.make("thread_stale_waiting");
306 const runId = RunId.make("run_stale_waiting");
307 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
308 null;
309 const projection = {
310 thread: { id: threadId },
311 runtimeRequests: [],
312 providerSessions: [],
313 providerThreads: [],
314 providerTurns: [],
315 runs: [
316 {
317 id: runId,
318 status: "waiting",
319 providerInstanceId: ProviderInstanceId.make("codex"),
320 },
321 ],
322 attempts: [],
323 nodes: [],
324 subagents: [],
325 messages: [],
326 turnItems: [],
327 } as unknown as OrchestrationV2ThreadProjection;
328 const layer = ProviderRuntimeRecovery.layer.pipe(
329 Layer.provide(
330 Layer.mergeAll(
331 Layer.mock(ProjectionStore.ProjectionStoreV2)({
332 getShellSnapshot: () =>
333 Effect.succeed({
334 schemaVersion: 2,
335 snapshotSequence: 0,
336 threads: [{ id: threadId }],
337 archivedThreads: [],
338 } as never),
339 getThreadProjection: () => Effect.succeed(projection),
340 }),
341 Layer.mock(EventSink.EventSinkV2)({
342 commitCommand: (input) => {
343 committedInput = input;
344 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
345 },
346 }),
347 IdAllocator.layer,
348 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
349 Layer.mock(EffectOutbox.EffectOutboxV2)({
350 listByCommandId: () => Effect.succeed([]),
351 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
352 }),
353 ),
354 ),
355 );
356
357 return Effect.gen(function* () {
358 const summary =
359 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
360 assert.equal(summary.terminalizedRuns, 1);
361 const runEvent = committedInput?.events.find((event) => event.type === "run.updated");
362 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled");
363 }).pipe(Effect.provide(layer));
364});
365
366it.effect("cancels accepted queued work instead of replaying it after restart", () => {
367 const threadId = ThreadId.make("thread_queued_restart");
368 const runId = RunId.make("run_queued_restart");
369 const attemptId = RunAttemptId.make("attempt_queued_restart");
370 const rootNodeId = NodeId.make("node_queued_restart");
371 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
372 null;
373 const projection = {
374 thread: { id: threadId },
375 runtimeRequests: [],
376 providerSessions: [],
377 providerThreads: [],
378 providerTurns: [],
379 runs: [
380 {
381 id: runId,
382 status: "queued",
383 queuePosition: 1,
384 providerInstanceId: ProviderInstanceId.make("codex"),
385 },
386 ],
387 attempts: [
388 {
389 id: attemptId,
390 runId,
391 rootNodeId,
392 status: "pending",
393 },
394 ],
395 nodes: [
396 {
397 id: rootNodeId,
398 runId,
399 status: "pending",
400 },
401 ],
402 subagents: [],
403 messages: [],
404 turnItems: [],
405 } as unknown as OrchestrationV2ThreadProjection;
406 const layer = ProviderRuntimeRecovery.layer.pipe(
407 Layer.provide(
408 Layer.mergeAll(
409 Layer.mock(ProjectionStore.ProjectionStoreV2)({
410 getShellSnapshot: () =>
411 Effect.succeed({
412 schemaVersion: 2,
413 snapshotSequence: 0,
414 threads: [{ id: threadId }],
415 archivedThreads: [],
416 } as never),
417 getThreadProjection: () => Effect.succeed(projection),
418 }),
419 Layer.mock(EventSink.EventSinkV2)({
420 commitCommand: (input) => {
421 committedInput = input;
422 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
423 },
424 }),
425 IdAllocator.layer,
426 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
427 Layer.mock(EffectOutbox.EffectOutboxV2)({
428 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
429 }),
430 ),
431 ),
432 );
433
434 return Effect.gen(function* () {
435 const summary =
436 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
437 assert.equal(summary.terminalizedRuns, 1);
438 const command = committedInput;
439 assert.isNotNull(command);
440 if (command === null) return;
441 const runEvent = command.events.find((event) => event.type === "run.updated");
442 const attemptEvent = command.events.find((event) => event.type === "run-attempt.updated");
443 const nodeEvent = command.events.find((event) => event.type === "node.updated");
444 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled");
445 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queuePosition : 1, null);
446 assert.equal(
447 attemptEvent?.type === "run-attempt.updated" ? attemptEvent.payload.status : null,
448 "cancelled",
449 );
450 assert.equal(nodeEvent?.type === "node.updated" ? nodeEvent.payload.status : null, "cancelled");
451 }).pipe(Effect.provide(layer));
452});
453
454it.effect(
455 "cancels the complete in-flight subtree and stops its persisted session without reopening it",
456 () => {
457 const threadId = ThreadId.make("thread_recovery_cancel");
458 const runId = RunId.make("run_recovery_cancel");
459 const attemptId = RunAttemptId.make("attempt_recovery_cancel");
460 const rootNodeId = NodeId.make("node_recovery_cancel");
461 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_cancel");
462 const providerTurnId = ProviderTurnId.make("provider_turn_recovery_cancel");
463 const providerSessionId = ProviderSessionId.make("provider_session_recovery_cancel");
464 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
465 null;
466 const projection = {
467 thread: { id: threadId },
468 runtimeRequests: [],
469 providerSessions: [
470 {
471 id: providerSessionId,
472 driver: ProviderDriverKind.make("codex"),
473 providerInstanceId: ProviderInstanceId.make("codex"),
474 status: "ready",
475 },
476 ],
477 providerThreads: [
478 {
479 id: providerThreadId,
480 driver: ProviderDriverKind.make("codex"),
481 providerInstanceId: ProviderInstanceId.make("codex"),
482 status: "active",
483 },
484 ],
485 providerTurns: [
486 {
487 id: providerTurnId,
488 runAttemptId: attemptId,
489 nodeId: rootNodeId,
490 status: "running",
491 },
492 ],
493 runs: [
494 {
495 id: runId,
496 status: "starting",
497 providerThreadId,
498 providerInstanceId: ProviderInstanceId.make("codex"),
499 },
500 ],
501 attempts: [
502 {
503 id: attemptId,
504 runId,
505 rootNodeId,
506 status: "running",
507 },
508 ],
509 nodes: [{ id: rootNodeId, runId, status: "running" }],
510 subagents: [],
511 messages: [{ id: MessageId.make("message_recovery_cancel"), runId, streaming: true }],
512 turnItems: [
513 {
514 id: TurnItemId.make("turn_item_recovery_cancel"),
515 runId,
516 nodeId: rootNodeId,
517 status: "running",
518 },
519 ],
520 } as unknown as OrchestrationV2ThreadProjection;
521 const layer = ProviderRuntimeRecovery.layer.pipe(
522 Layer.provide(
523 Layer.mergeAll(
524 Layer.mock(ProjectionStore.ProjectionStoreV2)({
525 getShellSnapshot: () =>
526 Effect.succeed({
527 schemaVersion: 2,
528 snapshotSequence: 0,
529 threads: [{ id: threadId }],
530 archivedThreads: [],
531 } as never),
532 getThreadProjection: () => Effect.succeed(projection),
533 }),
534 Layer.mock(EventSink.EventSinkV2)({
535 commitCommand: (input) => {
536 committedInput = input;
537 return Effect.succeed({ committed: true, cancelledEffectCount: 2 } as never);
538 },
539 }),
540 IdAllocator.layer,
541 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
542 Layer.mock(EffectOutbox.EffectOutboxV2)({
543 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
544 }),
545 ),
546 ),
547 );
548
549 return Effect.gen(function* () {
550 const summary = yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)
551 .recover;
552 assert.equal(summary.terminalizedRuns, 1);
553 assert.equal(summary.stoppedSessions, 1);
554 assert.equal(summary.retiredEffects, 2);
555 assert.deepEqual(committedInput?.cancelUnsettledEffects?.effectTypes, [
556 "provider-turn.start",
557 "provider-turn.interrupt",
558 "provider-turn.steer",
559 "provider-turn.restart",
560 "runtime-request.respond",
561 ]);
562 const events = committedInput?.events ?? [];
563 assert.deepEqual(
564 events.map((event) => [
565 event.type,
566 "status" in event.payload ? event.payload.status : null,
567 ]),
568 [
569 ["run.updated", "cancelled"],
570 ["run-attempt.updated", "cancelled"],
571 ["node.updated", "cancelled"],
572 ["provider-turn.updated", "cancelled"],
573 ["message.updated", null],
574 ["turn-item.updated", "cancelled"],
575 ["provider-thread.updated", "idle"],
576 ["provider-session.updated", "stopped"],
577 ],
578 );
579 const messageEvent = events.find((event) => event.type === "message.updated");
580 assert.isFalse(messageEvent?.type === "message.updated" && messageEvent.payload.streaming);
581 }).pipe(Effect.provide(layer));
582 },
583);
584
585it.effect(
586 "clears persisted pendingBackgroundTasks and terminalizes stale background items on settled runs",
587 () => {
588 const threadId = ThreadId.make("thread_recovery_background");
589 const settledRunId = RunId.make("run_recovery_background_settled");
590 const activeRunId = RunId.make("run_recovery_background_active");
591 const activeAttemptId = RunAttemptId.make("attempt_recovery_background_active");
592 const activeRootNodeId = NodeId.make("node_recovery_background_active");
593 const idleProviderThreadId = ProviderThreadId.make("provider_thread_recovery_background_idle");
594 const activeProviderThreadId = ProviderThreadId.make(
595 "provider_thread_recovery_background_active",
596 );
597 const secondaryProviderThreadId = ProviderThreadId.make(
598 "provider_thread_recovery_background_secondary",
599 );
600 const providerSessionId = ProviderSessionId.make("provider_session_recovery_background");
601 const settledStaleItemId = TurnItemId.make("turn_item_recovery_background_stale");
602 const activeRunItemId = TurnItemId.make("turn_item_recovery_background_active");
603 const nullRunCommandItemId = TurnItemId.make("turn_item_recovery_background_null_run");
604 const nullRunSubagentItemId = TurnItemId.make("turn_item_recovery_background_null_subagent");
605 const claudeInstanceId = ProviderInstanceId.make("claude");
606 const secondaryInstanceId = ProviderInstanceId.make("claude-secondary");
607 const subagentInstanceId = ProviderInstanceId.make("claude-subagent");
608 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
609 null;
610 const projection = {
611 thread: { id: threadId },
612 runtimeRequests: [],
613 providerSessions: [
614 {
615 id: providerSessionId,
616 driver: ProviderDriverKind.make("claude"),
617 providerInstanceId: claudeInstanceId,
618 status: "ready",
619 },
620 ],
621 providerThreads: [
622 {
623 id: idleProviderThreadId,
624 driver: ProviderDriverKind.make("claude"),
625 // Index-0 is intentionally a different instance so misattribution
626 // to providerThreads[0] fails the assertions below.
627 providerInstanceId: claudeInstanceId,
628 status: "idle",
629 pendingBackgroundTasks: [{ taskId: "bg-settled", description: "sleep 30" }],
630 },
631 {
632 id: activeProviderThreadId,
633 driver: ProviderDriverKind.make("claude"),
634 providerInstanceId: claudeInstanceId,
635 status: "active",
636 pendingBackgroundTasks: [{ taskId: "bg-active", description: "npm test" }],
637 },
638 {
639 id: secondaryProviderThreadId,
640 driver: ProviderDriverKind.make("claude"),
641 providerInstanceId: secondaryInstanceId,
642 status: "idle",
643 pendingBackgroundTasks: [],
644 },
645 ],
646 providerTurns: [],
647 runs: [
648 {
649 id: settledRunId,
650 status: "completed",
651 providerInstanceId: claudeInstanceId,
652 },
653 {
654 id: activeRunId,
655 status: "running",
656 providerInstanceId: claudeInstanceId,
657 },
658 ],
659 attempts: [
660 {
661 id: activeAttemptId,
662 runId: activeRunId,
663 rootNodeId: activeRootNodeId,
664 status: "running",
665 },
666 ],
667 nodes: [{ id: activeRootNodeId, runId: activeRunId, status: "running" }],
668 subagents: [],
669 messages: [],
670 turnItems: [
671 {
672 id: settledStaleItemId,
673 runId: settledRunId,
674 nodeId: null,
675 providerThreadId: idleProviderThreadId,
676 type: "command_execution",
677 status: "running",
678 },
679 {
680 id: activeRunItemId,
681 runId: activeRunId,
682 nodeId: activeRootNodeId,
683 providerThreadId: activeProviderThreadId,
684 type: "dynamic_tool",
685 status: "running",
686 },
687 {
688 // Missing run: must attribute via providerThreadId, not index 0.
689 id: nullRunCommandItemId,
690 runId: null,
691 nodeId: null,
692 providerThreadId: secondaryProviderThreadId,
693 type: "command_execution",
694 status: "running",
695 },
696 {
697 // Missing run with a real matching provider thread whose instance
698 // differs from the subagent's own: own providerInstanceId must win.
699 id: nullRunSubagentItemId,
700 runId: null,
701 nodeId: null,
702 providerThreadId: secondaryProviderThreadId,
703 type: "subagent",
704 status: "running",
705 providerInstanceId: subagentInstanceId,
706 },
707 ],
708 } as unknown as OrchestrationV2ThreadProjection;
709 const layer = ProviderRuntimeRecovery.layer.pipe(
710 Layer.provide(
711 Layer.mergeAll(
712 Layer.mock(ProjectionStore.ProjectionStoreV2)({
713 getShellSnapshot: () =>
714 Effect.succeed({
715 schemaVersion: 2,
716 snapshotSequence: 0,
717 threads: [{ id: threadId }],
718 archivedThreads: [],
719 } as never),
720 getThreadProjection: () => Effect.succeed(projection),
721 }),
722 Layer.mock(EventSink.EventSinkV2)({
723 commitCommand: (input) => {
724 committedInput = input;
725 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
726 },
727 }),
728 IdAllocator.layer,
729 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
730 Layer.mock(EffectOutbox.EffectOutboxV2)({
731 listByCommandId: () => Effect.succeed([]),
732 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
733 }),
734 ),
735 ),
736 );
737
738 return Effect.gen(function* () {
739 const summary =
740 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
741 assert.equal(summary.terminalizedRuns, 1);
742 const events = committedInput?.events ?? [];
743
744 const turnItemCancels = events.filter(
745 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
746 );
747 // Active-run item + settled-run stale + null-run command + null-run subagent.
748 assert.equal(turnItemCancels.length, 4);
749 assert.deepEqual(
750 turnItemCancels
751 .map((event) => event.type === "turn-item.updated" && event.payload.id)
752 .sort(),
753 [activeRunItemId, nullRunCommandItemId, nullRunSubagentItemId, settledStaleItemId].sort(),
754 );
755
756 const cancelById = (id: TurnItemId) =>
757 turnItemCancels.find(
758 (event) => event.type === "turn-item.updated" && event.payload.id === id,
759 );
760 assert.equal(cancelById(nullRunCommandItemId)?.providerInstanceId, secondaryInstanceId);
761 // Subagent own instance wins over the matching thread's secondary instance.
762 assert.notEqual(subagentInstanceId, secondaryInstanceId);
763 assert.equal(cancelById(nullRunSubagentItemId)?.providerInstanceId, subagentInstanceId);
764 // Settled-run item still prefers the run's provider instance when present.
765 assert.equal(cancelById(settledStaleItemId)?.providerInstanceId, claudeInstanceId);
766
767 const providerThreadEvents = events.filter(
768 (event) => event.type === "provider-thread.updated",
769 );
770 // Only threads with active status or nonempty rosters are rewritten.
771 assert.equal(providerThreadEvents.length, 2);
772 for (const event of providerThreadEvents) {
773 if (event.type !== "provider-thread.updated") continue;
774 assert.deepEqual(event.payload.pendingBackgroundTasks ?? [], []);
775 }
776 const idleThreadEvent = providerThreadEvents.find(
777 (event) =>
778 event.type === "provider-thread.updated" && event.payload.id === idleProviderThreadId,
779 );
780 assert.equal(
781 idleThreadEvent?.type === "provider-thread.updated" ? idleThreadEvent.payload.status : null,
782 "idle",
783 );
784 const activeThreadEvent = providerThreadEvents.find(
785 (event) =>
786 event.type === "provider-thread.updated" && event.payload.id === activeProviderThreadId,
787 );
788 assert.equal(
789 activeThreadEvent?.type === "provider-thread.updated"
790 ? activeThreadEvent.payload.status
791 : null,
792 "idle",
793 );
794 }).pipe(Effect.provide(layer));
795 },
796);
797
798it.effect(
799 "terminalizes the linked subagent and node for a stale subagent item on a settled run",
800 () => {
801 const threadId = ThreadId.make("thread_recovery_subagent");
802 const settledRunId = RunId.make("run_recovery_subagent_settled");
803 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_subagent");
804 const staleSubagentNodeId = NodeId.make("node_recovery_subagent_stale");
805 const doneSubagentNodeId = NodeId.make("node_recovery_subagent_done");
806 const staleItemId = TurnItemId.make("turn_item_recovery_subagent_stale");
807 const doneItemId = TurnItemId.make("turn_item_recovery_subagent_done");
808 const claudeInstanceId = ProviderInstanceId.make("claude");
809 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
810 null;
811 const projection = {
812 thread: { id: threadId },
813 runtimeRequests: [],
814 providerSessions: [],
815 providerThreads: [
816 {
817 id: providerThreadId,
818 driver: ProviderDriverKind.make("claude"),
819 providerInstanceId: claudeInstanceId,
820 status: "idle",
821 pendingBackgroundTasks: [],
822 },
823 ],
824 providerTurns: [],
825 // Settled run: the stale-item loop owns it, not the nonterminal loop.
826 runs: [{ id: settledRunId, status: "completed", providerInstanceId: claudeInstanceId }],
827 attempts: [],
828 nodes: [
829 { id: staleSubagentNodeId, runId: settledRunId, status: "running" },
830 { id: doneSubagentNodeId, runId: settledRunId, status: "completed" },
831 ],
832 subagents: [
833 {
834 id: staleSubagentNodeId,
835 runId: settledRunId,
836 driver: ProviderDriverKind.make("claude"),
837 providerInstanceId: claudeInstanceId,
838 status: "running",
839 },
840 {
841 // Already finished with a real result: must never be overwritten.
842 id: doneSubagentNodeId,
843 runId: settledRunId,
844 driver: ProviderDriverKind.make("claude"),
845 providerInstanceId: claudeInstanceId,
846 status: "completed",
847 result: "done",
848 },
849 ],
850 messages: [],
851 turnItems: [
852 {
853 id: staleItemId,
854 runId: settledRunId,
855 nodeId: staleSubagentNodeId,
856 providerThreadId,
857 type: "subagent",
858 status: "running",
859 subagentId: staleSubagentNodeId,
860 providerInstanceId: claudeInstanceId,
861 },
862 {
863 id: doneItemId,
864 runId: settledRunId,
865 nodeId: doneSubagentNodeId,
866 providerThreadId,
867 type: "subagent",
868 status: "completed",
869 subagentId: doneSubagentNodeId,
870 providerInstanceId: claudeInstanceId,
871 },
872 ],
873 } as unknown as OrchestrationV2ThreadProjection;
874 const layer = ProviderRuntimeRecovery.layer.pipe(
875 Layer.provide(
876 Layer.mergeAll(
877 Layer.mock(ProjectionStore.ProjectionStoreV2)({
878 getShellSnapshot: () =>
879 Effect.succeed({
880 schemaVersion: 2,
881 snapshotSequence: 0,
882 threads: [{ id: threadId }],
883 archivedThreads: [],
884 } as never),
885 getThreadProjection: () => Effect.succeed(projection),
886 }),
887 Layer.mock(EventSink.EventSinkV2)({
888 commitCommand: (input) => {
889 committedInput = input;
890 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
891 },
892 }),
893 IdAllocator.layer,
894 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
895 Layer.mock(EffectOutbox.EffectOutboxV2)({
896 listByCommandId: () => Effect.succeed([]),
897 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
898 }),
899 ),
900 ),
901 );
902
903 return Effect.gen(function* () {
904 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
905 const events = committedInput?.events ?? [];
906
907 // Only the nonterminal subagent item is cancelled.
908 const turnItemCancels = events.filter(
909 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
910 );
911 assert.equal(turnItemCancels.length, 1);
912
913 // The linked subagent entity is terminalized alongside its turn item.
914 const subagentCancels = events.filter((event) => event.type === "subagent.updated");
915 assert.equal(subagentCancels.length, 1);
916 const subagentCancel = subagentCancels[0];
917 assert.equal(
918 subagentCancel?.type === "subagent.updated" ? subagentCancel.payload.id : null,
919 staleSubagentNodeId,
920 );
921 assert.equal(
922 subagentCancel?.type === "subagent.updated" ? subagentCancel.payload.status : null,
923 "cancelled",
924 );
925
926 // So is its execution node, which no live process can terminalize.
927 const nodeCancels = events.filter((event) => event.type === "node.updated");
928 assert.equal(nodeCancels.length, 1);
929 const nodeCancel = nodeCancels[0];
930 assert.equal(
931 nodeCancel?.type === "node.updated" ? nodeCancel.payload.id : null,
932 staleSubagentNodeId,
933 );
934
935 // The already-completed subagent and node are left untouched.
936 assert.isFalse(
937 events.some(
938 (event) => event.type === "subagent.updated" && event.payload.id === doneSubagentNodeId,
939 ),
940 );
941 assert.isFalse(
942 events.some(
943 (event) => event.type === "node.updated" && event.payload.id === doneSubagentNodeId,
944 ),
945 );
946 }).pipe(Effect.provide(layer));
947 },
948);