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";
27import * as ServerSettings from "../serverSettings.ts";
28
29it.effect("leaves durable effects for the worker after runtime reconciliation", () =>
30 Effect.gen(function* () {
31 const runs = yield* Ref.make(0);
32 const layer = ProviderRuntimeRecovery.layer.pipe(
33 Layer.provide(ServerSettings.layerTest()),
34 Layer.provide(
35 Layer.mergeAll(
36 Layer.mock(ProjectionStore.ProjectionStoreV2)({
37 getRecoveryThreadIds: () => Effect.succeed([]),
38 }),
39 Layer.mock(EventSink.EventSinkV2)({}),
40 IdAllocator.layer,
41 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
42 runRecoveryOnce: Ref.getAndUpdate(runs, (count) => count + 1).pipe(
43 Effect.map((count) => count < 2),
44 ),
45 }),
46 Layer.mock(EffectOutbox.EffectOutboxV2)({
47 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
48 }),
49 ),
50 ),
51 );
52 const summary = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService.pipe(
53 Effect.flatMap((recovery) => recovery.recover),
54 Effect.provide(layer),
55 );
56 assert.deepEqual(summary, {
57 terminalizedRuns: 0,
58 stoppedSessions: 0,
59 closedRequests: 0,
60 retiredEffects: 0,
61 requeuedEffects: 0,
62 });
63 assert.equal(yield* Ref.get(runs), 0);
64 }),
65);
66
67it.effect("reads recovery projections only for threads that need runtime recovery", () => {
68 const settledThreadIds = Array.from({ length: 1_000 }, (_, index) =>
69 ThreadId.make(`thread_recovery_settled_${index}`),
70 );
71 const recoveryThreadId = ThreadId.make("thread_recovery_candidate");
72 const projectionReads = vi.fn<(threadId: ThreadId) => void>();
73 const layer = ProviderRuntimeRecovery.layer.pipe(
74 Layer.provide(ServerSettings.layerTest()),
75 Layer.provide(
76 Layer.mergeAll(
77 Layer.mock(ProjectionStore.ProjectionStoreV2)({
78 getShellSnapshot: () =>
79 Effect.succeed({
80 schemaVersion: 2,
81 snapshotSequence: 0,
82 threads: [...settledThreadIds, recoveryThreadId].map((id) => ({ id })),
83 archivedThreads: [],
84 } as never),
85 getRecoveryThreadIds: () => Effect.succeed([recoveryThreadId]),
86 getRuntimeRecoveryProjection: (threadId) => {
87 projectionReads(threadId);
88 return Effect.succeed({
89 thread: { id: threadId },
90 runtimeRequests: [],
91 providerSessions: [],
92 providerThreads: [],
93 providerTurns: [],
94 runs: [],
95 attempts: [],
96 nodes: [],
97 subagents: [],
98 messages: [],
99 turnItems: [],
100 } as unknown as OrchestrationV2ThreadProjection);
101 },
102 }),
103 Layer.mock(EventSink.EventSinkV2)({}),
104 IdAllocator.layer,
105 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
106 runRecoveryOnce: Effect.succeed(false),
107 }),
108 Layer.mock(EffectOutbox.EffectOutboxV2)({
109 cancelUnsettled: () => Effect.succeed([]),
110 signalCancellations: () => Effect.void,
111 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
112 }),
113 ),
114 ),
115 );
116
117 return Effect.gen(function* () {
118 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).recover;
119 assert.deepEqual(
120 projectionReads.mock.calls.map(([threadId]) => threadId),
121 [recoveryThreadId],
122 );
123 }).pipe(Effect.provide(layer));
124});
125
126it.effect("expires orphaned runtime requests before command readiness", () => {
127 const threadId = ThreadId.make("thread_recovery_requests");
128 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
129 null;
130 const committed = vi.fn(
131 (input: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0]) => {
132 committedInput = input;
133 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
134 },
135 );
136 const projection = {
137 thread: { id: threadId },
138 runtimeRequests: [
139 {
140 id: RuntimeRequestId.make("request_orphaned"),
141 nodeId: NodeId.make("node_orphaned"),
142 status: "pending",
143 responseCapability: { type: "not_resumable", reason: "old process" },
144 },
145 ],
146 providerSessions: [],
147 providerThreads: [],
148 runs: [],
149 nodes: [],
150 } as unknown as OrchestrationV2ThreadProjection;
151 const layer = ProviderRuntimeRecovery.layer.pipe(
152 Layer.provide(ServerSettings.layerTest()),
153 Layer.provide(
154 Layer.mergeAll(
155 Layer.mock(ProjectionStore.ProjectionStoreV2)({
156 getRecoveryThreadIds: () => Effect.succeed([threadId]),
157 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
158 }),
159 Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }),
160 IdAllocator.layer,
161 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
162 runRecoveryOnce: Effect.succeed(false),
163 }),
164 Layer.mock(EffectOutbox.EffectOutboxV2)({
165 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
166 }),
167 ),
168 ),
169 );
170 return Effect.gen(function* () {
171 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).recover;
172 const command = committedInput;
173 assert.isNotNull(command);
174 if (command === null) return;
175 assert.equal(command?.events[0]?.type, "runtime-request.updated");
176 if (command?.events[0]?.type === "runtime-request.updated") {
177 assert.equal(command.events[0].payload.status, "expired");
178 assert.equal(command.events[0].payload.responseCapability.type, "not_resumable");
179 }
180 }).pipe(Effect.provide(layer));
181});
182
183it.effect("preserves async questions across startup and shutdown", () => {
184 const threadId = ThreadId.make("async-recovery-thread");
185 const nodeId = NodeId.make("async-recovery-node");
186 const projection = {
187 thread: { id: threadId },
188 runtimeRequests: [
189 {
190 id: RuntimeRequestId.make("async-recovery-request"),
191 nodeId,
192 status: "pending",
193 responseCapability: { type: "message" },
194 },
195 ],
196 providerSessions: [],
197 providerThreads: [],
198 runs: [],
199 nodes: [],
200 turnItems: [],
201 } as unknown as OrchestrationV2ThreadProjection;
202 const commitCommand = vi.fn(() => Effect.die("an async question needs no process-loss write"));
203 const layer = ProviderRuntimeRecovery.layer.pipe(
204 Layer.provide(ServerSettings.layerTest()),
205 Layer.provide(
206 Layer.mergeAll(
207 Layer.mock(ProjectionStore.ProjectionStoreV2)({
208 getRecoveryThreadIds: () => Effect.succeed([threadId]),
209 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
210 }),
211 Layer.mock(EventSink.EventSinkV2)({ commitCommand }),
212 IdAllocator.layer,
213 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
214 runRecoveryOnce: Effect.succeed(false),
215 }),
216 Layer.mock(EffectOutbox.EffectOutboxV2)({
217 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
218 cancelUnsettled: () => Effect.succeed([]),
219 signalCancellations: () => Effect.void,
220 }),
221 ),
222 ),
223 );
224 return Effect.gen(function* () {
225 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
226 assert.equal((yield* recovery.reconcile("startup")).closedRequests, 0);
227 assert.equal((yield* recovery.reconcile("startup")).closedRequests, 0);
228 assert.isFalse(commitCommand.mock.calls.length > 0);
229 }).pipe(Effect.provide(layer));
230});
231
232it.effect("uses the same reconciliation path to cancel runtime requests during shutdown", () => {
233 const threadId = ThreadId.make("thread_shutdown_requests");
234 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
235 null;
236 const projection = {
237 thread: { id: threadId },
238 runtimeRequests: [
239 {
240 id: RuntimeRequestId.make("request_shutdown"),
241 nodeId: NodeId.make("node_shutdown"),
242 status: "pending",
243 responseCapability: { type: "live" },
244 },
245 ],
246 providerSessions: [],
247 providerThreads: [],
248 runs: [],
249 nodes: [],
250 } as unknown as OrchestrationV2ThreadProjection;
251 const layer = ProviderRuntimeRecovery.layer.pipe(
252 Layer.provide(ServerSettings.layerTest()),
253 Layer.provide(
254 Layer.mergeAll(
255 Layer.mock(ProjectionStore.ProjectionStoreV2)({
256 getRecoveryThreadIds: () => Effect.succeed([threadId]),
257 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
258 }),
259 Layer.mock(EventSink.EventSinkV2)({
260 commitCommand: (input) => {
261 committedInput = input;
262 return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
263 },
264 }),
265 IdAllocator.layer,
266 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
267 runRecoveryOnce: Effect.succeed(false),
268 }),
269 Layer.mock(EffectOutbox.EffectOutboxV2)({
270 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
271 }),
272 ),
273 ),
274 );
275
276 return Effect.gen(function* () {
277 const summary =
278 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("shutdown");
279 assert.equal(summary.closedRequests, 1);
280 assert.equal(summary.retiredEffects, 1);
281 const requestEvent = committedInput?.events[0];
282 assert.equal(requestEvent?.type, "runtime-request.updated");
283 if (requestEvent?.type === "runtime-request.updated") {
284 assert.equal(requestEvent.payload.status, "cancelled");
285 assert.equal(requestEvent.payload.responseCapability.type, "not_resumable");
286 if (requestEvent.payload.responseCapability.type === "not_resumable") {
287 assert.match(requestEvent.payload.responseCapability.reason, /shut down/);
288 }
289 }
290 }).pipe(Effect.provide(layer));
291});
292
293it.effect(
294 "preserves a replayable waiting run while cancelling its process-bound background work",
295 () => {
296 const threadId = ThreadId.make("thread_waiting_checkpoint");
297 const runId = RunId.make("run_waiting_checkpoint");
298 const providerThreadId = ProviderThreadId.make("provider_thread_waiting_checkpoint");
299 const providerInstanceId = ProviderInstanceId.make("claude");
300 const backgroundItemId = TurnItemId.make("turn_item_waiting_checkpoint");
301 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
302 null;
303 const projection = {
304 thread: { id: threadId },
305 runtimeRequests: [],
306 providerSessions: [],
307 providerThreads: [
308 {
309 id: providerThreadId,
310 driver: ProviderDriverKind.make("claude"),
311 providerInstanceId,
312 status: "idle",
313 pendingBackgroundTasks: [
314 { taskId: String(backgroundItemId), description: "Finish background task" },
315 ],
316 },
317 ],
318 runs: [{ id: runId, status: "waiting", providerInstanceId }],
319 attempts: [],
320 nodes: [],
321 subagents: [],
322 messages: [],
323 turnItems: [
324 {
325 id: backgroundItemId,
326 runId,
327 nodeId: null,
328 providerThreadId,
329 type: "command_execution",
330 status: "running",
331 },
332 ],
333 } as unknown as OrchestrationV2ThreadProjection;
334 const layer = ProviderRuntimeRecovery.layer.pipe(
335 Layer.provide(ServerSettings.layerTest()),
336 Layer.provide(
337 Layer.mergeAll(
338 Layer.mock(ProjectionStore.ProjectionStoreV2)({
339 getRecoveryThreadIds: () => Effect.succeed([threadId]),
340 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
341 }),
342 Layer.mock(EventSink.EventSinkV2)({
343 commitCommand: (input) => {
344 committedInput = input;
345 return Effect.succeed({
346 committed: true,
347 cancelledEffectCount: 0,
348 } as never);
349 },
350 }),
351 IdAllocator.layer,
352 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
353 runRecoveryOnce: Effect.succeed(false),
354 }),
355 Layer.mock(EffectOutbox.EffectOutboxV2)({
356 listByCommandId: () =>
357 Effect.succeed([
358 {
359 request: { type: "checkpoint.capture", runId },
360 status: "running",
361 },
362 ] as never),
363 reconcileAfterProcessLoss: Effect.succeed({ requeued: 1, cancelled: 0 }),
364 }),
365 ),
366 ),
367 );
368
369 return Effect.gen(function* () {
370 const summary =
371 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
372 assert.equal(summary.terminalizedRuns, 0);
373 assert.equal(summary.requeuedEffects, 1);
374
375 const command = committedInput;
376 assert.isNotNull(command);
377 if (command === null) return;
378 assert.isFalse(command.events.some((event) => event.type === "run.updated"));
379 assert.isTrue(
380 command.events.some(
381 (event) =>
382 event.type === "turn-item.updated" &&
383 event.payload.id === backgroundItemId &&
384 event.payload.status === "cancelled",
385 ),
386 );
387 assert.isTrue(
388 command.events.some(
389 (event) =>
390 event.type === "provider-thread.updated" &&
391 event.payload.id === providerThreadId &&
392 event.payload.pendingBackgroundTasks?.length === 0,
393 ),
394 );
395 }).pipe(Effect.provide(layer));
396 },
397);
398
399it.effect("cancels a stale waiting run when no checkpoint capture can finish it", () => {
400 const threadId = ThreadId.make("thread_stale_waiting");
401 const runId = RunId.make("run_stale_waiting");
402 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
403 null;
404 const projection = {
405 thread: { id: threadId },
406 runtimeRequests: [],
407 providerSessions: [],
408 providerThreads: [],
409 providerTurns: [],
410 runs: [
411 {
412 id: runId,
413 status: "waiting",
414 providerInstanceId: ProviderInstanceId.make("codex"),
415 },
416 ],
417 attempts: [],
418 nodes: [],
419 subagents: [],
420 messages: [],
421 turnItems: [],
422 } as unknown as OrchestrationV2ThreadProjection;
423 const layer = ProviderRuntimeRecovery.layer.pipe(
424 Layer.provide(ServerSettings.layerTest()),
425 Layer.provide(
426 Layer.mergeAll(
427 Layer.mock(ProjectionStore.ProjectionStoreV2)({
428 getRecoveryThreadIds: () => Effect.succeed([threadId]),
429 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
430 }),
431 Layer.mock(EventSink.EventSinkV2)({
432 commitCommand: (input) => {
433 committedInput = input;
434 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
435 },
436 }),
437 IdAllocator.layer,
438 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
439 runRecoveryOnce: Effect.succeed(false),
440 }),
441 Layer.mock(EffectOutbox.EffectOutboxV2)({
442 listByCommandId: () => Effect.succeed([]),
443 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
444 }),
445 ),
446 ),
447 );
448
449 return Effect.gen(function* () {
450 const summary =
451 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
452 assert.equal(summary.terminalizedRuns, 1);
453 const runEvent = committedInput?.events.find((event) => event.type === "run.updated");
454 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled");
455 }).pipe(Effect.provide(layer));
456});
457
458it.effect("cancels accepted queued work instead of replaying it after restart", () => {
459 const threadId = ThreadId.make("thread_queued_restart");
460 const runId = RunId.make("run_queued_restart");
461 const attemptId = RunAttemptId.make("attempt_queued_restart");
462 const rootNodeId = NodeId.make("node_queued_restart");
463 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
464 null;
465 const projection = {
466 thread: { id: threadId },
467 runtimeRequests: [],
468 providerSessions: [],
469 providerThreads: [],
470 providerTurns: [],
471 runs: [
472 {
473 id: runId,
474 status: "queued",
475 queuePosition: 1,
476 providerInstanceId: ProviderInstanceId.make("codex"),
477 },
478 ],
479 attempts: [
480 {
481 id: attemptId,
482 runId,
483 rootNodeId,
484 status: "pending",
485 },
486 ],
487 nodes: [
488 {
489 id: rootNodeId,
490 runId,
491 status: "pending",
492 },
493 ],
494 subagents: [],
495 messages: [],
496 turnItems: [],
497 } as unknown as OrchestrationV2ThreadProjection;
498 const layer = ProviderRuntimeRecovery.layer.pipe(
499 Layer.provide(ServerSettings.layerTest()),
500 Layer.provide(
501 Layer.mergeAll(
502 Layer.mock(ProjectionStore.ProjectionStoreV2)({
503 getRecoveryThreadIds: () => Effect.succeed([threadId]),
504 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
505 }),
506 Layer.mock(EventSink.EventSinkV2)({
507 commitCommand: (input) => {
508 committedInput = input;
509 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
510 },
511 }),
512 IdAllocator.layer,
513 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
514 runRecoveryOnce: Effect.succeed(false),
515 }),
516 Layer.mock(EffectOutbox.EffectOutboxV2)({
517 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
518 }),
519 ),
520 ),
521 );
522
523 return Effect.gen(function* () {
524 const summary =
525 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
526 assert.equal(summary.terminalizedRuns, 1);
527 const command = committedInput;
528 assert.isNotNull(command);
529 if (command === null) return;
530 const runEvent = command.events.find((event) => event.type === "run.updated");
531 const attemptEvent = command.events.find((event) => event.type === "run-attempt.updated");
532 const nodeEvent = command.events.find((event) => event.type === "node.updated");
533 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled");
534 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queuePosition : 1, null);
535 assert.equal(
536 attemptEvent?.type === "run-attempt.updated" ? attemptEvent.payload.status : null,
537 "cancelled",
538 );
539 assert.equal(nodeEvent?.type === "node.updated" ? nodeEvent.payload.status : null, "cancelled");
540 }).pipe(Effect.provide(layer));
541});
542
543it.effect(
544 "cancels the complete in-flight subtree and stops its persisted session without reopening it",
545 () => {
546 const threadId = ThreadId.make("thread_recovery_cancel");
547 const runId = RunId.make("run_recovery_cancel");
548 const attemptId = RunAttemptId.make("attempt_recovery_cancel");
549 const rootNodeId = NodeId.make("node_recovery_cancel");
550 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_cancel");
551 const providerTurnId = ProviderTurnId.make("provider_turn_recovery_cancel");
552 const providerSessionId = ProviderSessionId.make("provider_session_recovery_cancel");
553 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
554 null;
555 const projection = {
556 thread: { id: threadId },
557 runtimeRequests: [],
558 providerSessions: [
559 {
560 id: providerSessionId,
561 driver: ProviderDriverKind.make("codex"),
562 providerInstanceId: ProviderInstanceId.make("codex"),
563 status: "ready",
564 },
565 ],
566 providerThreads: [
567 {
568 id: providerThreadId,
569 driver: ProviderDriverKind.make("codex"),
570 providerInstanceId: ProviderInstanceId.make("codex"),
571 status: "active",
572 },
573 ],
574 providerTurns: [
575 {
576 id: providerTurnId,
577 runAttemptId: attemptId,
578 nodeId: rootNodeId,
579 status: "running",
580 },
581 ],
582 runs: [
583 {
584 id: runId,
585 status: "starting",
586 providerThreadId,
587 providerInstanceId: ProviderInstanceId.make("codex"),
588 },
589 ],
590 attempts: [
591 {
592 id: attemptId,
593 runId,
594 rootNodeId,
595 status: "running",
596 },
597 ],
598 nodes: [{ id: rootNodeId, runId, status: "running" }],
599 subagents: [],
600 messages: [{ id: MessageId.make("message_recovery_cancel"), runId, streaming: true }],
601 turnItems: [
602 {
603 id: TurnItemId.make("turn_item_recovery_cancel"),
604 runId,
605 nodeId: rootNodeId,
606 status: "running",
607 },
608 ],
609 } as unknown as OrchestrationV2ThreadProjection;
610 const layer = ProviderRuntimeRecovery.layer.pipe(
611 Layer.provide(ServerSettings.layerTest()),
612 Layer.provide(
613 Layer.mergeAll(
614 Layer.mock(ProjectionStore.ProjectionStoreV2)({
615 getRecoveryThreadIds: () => Effect.succeed([threadId]),
616 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
617 }),
618 Layer.mock(EventSink.EventSinkV2)({
619 commitCommand: (input) => {
620 committedInput = input;
621 return Effect.succeed({ committed: true, cancelledEffectCount: 2 } as never);
622 },
623 }),
624 IdAllocator.layer,
625 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
626 runRecoveryOnce: Effect.succeed(false),
627 }),
628 Layer.mock(EffectOutbox.EffectOutboxV2)({
629 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
630 }),
631 ),
632 ),
633 );
634
635 return Effect.gen(function* () {
636 const summary = yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)
637 .recover;
638 assert.equal(summary.terminalizedRuns, 1);
639 assert.equal(summary.stoppedSessions, 1);
640 assert.equal(summary.retiredEffects, 2);
641 assert.deepEqual(committedInput?.cancelUnsettledEffects?.effectTypes, [
642 "provider-turn.start",
643 "provider-turn.interrupt",
644 "provider-turn.steer",
645 "provider-turn.restart",
646 "runtime-request.respond",
647 ]);
648 const events = committedInput?.events ?? [];
649 assert.deepEqual(
650 events.map((event) => [
651 event.type,
652 "status" in event.payload ? event.payload.status : null,
653 ]),
654 [
655 ["run.updated", "cancelled"],
656 ["run-attempt.updated", "cancelled"],
657 ["node.updated", "cancelled"],
658 ["provider-turn.updated", "cancelled"],
659 ["message.updated", null],
660 ["turn-item.updated", "cancelled"],
661 ["provider-thread.updated", "idle"],
662 ["provider-session.updated", "stopped"],
663 ],
664 );
665 const messageEvent = events.find((event) => event.type === "message.updated");
666 assert.isFalse(messageEvent?.type === "message.updated" && messageEvent.payload.streaming);
667 }).pipe(Effect.provide(layer));
668 },
669);
670
671it.effect(
672 "clears persisted pendingBackgroundTasks and terminalizes stale background items on settled runs",
673 () => {
674 const threadId = ThreadId.make("thread_recovery_background");
675 const settledRunId = RunId.make("run_recovery_background_settled");
676 const activeRunId = RunId.make("run_recovery_background_active");
677 const activeAttemptId = RunAttemptId.make("attempt_recovery_background_active");
678 const activeRootNodeId = NodeId.make("node_recovery_background_active");
679 const idleProviderThreadId = ProviderThreadId.make("provider_thread_recovery_background_idle");
680 const activeProviderThreadId = ProviderThreadId.make(
681 "provider_thread_recovery_background_active",
682 );
683 const secondaryProviderThreadId = ProviderThreadId.make(
684 "provider_thread_recovery_background_secondary",
685 );
686 const providerSessionId = ProviderSessionId.make("provider_session_recovery_background");
687 const settledStaleItemId = TurnItemId.make("turn_item_recovery_background_stale");
688 const activeRunItemId = TurnItemId.make("turn_item_recovery_background_active");
689 const nullRunCommandItemId = TurnItemId.make("turn_item_recovery_background_null_run");
690 const nullRunSubagentItemId = TurnItemId.make("turn_item_recovery_background_null_subagent");
691 const claudeInstanceId = ProviderInstanceId.make("claude");
692 const secondaryInstanceId = ProviderInstanceId.make("claude-secondary");
693 const subagentInstanceId = ProviderInstanceId.make("claude-subagent");
694 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
695 null;
696 const projection = {
697 thread: { id: threadId },
698 runtimeRequests: [],
699 providerSessions: [
700 {
701 id: providerSessionId,
702 driver: ProviderDriverKind.make("claude"),
703 providerInstanceId: claudeInstanceId,
704 status: "ready",
705 },
706 ],
707 providerThreads: [
708 {
709 id: idleProviderThreadId,
710 driver: ProviderDriverKind.make("claude"),
711 // Index-0 is intentionally a different instance so misattribution
712 // to providerThreads[0] fails the assertions below.
713 providerInstanceId: claudeInstanceId,
714 status: "idle",
715 pendingBackgroundTasks: [{ taskId: "bg-settled", description: "sleep 30" }],
716 },
717 {
718 id: activeProviderThreadId,
719 driver: ProviderDriverKind.make("claude"),
720 providerInstanceId: claudeInstanceId,
721 status: "active",
722 pendingBackgroundTasks: [{ taskId: "bg-active", description: "npm test" }],
723 },
724 {
725 id: secondaryProviderThreadId,
726 driver: ProviderDriverKind.make("claude"),
727 providerInstanceId: secondaryInstanceId,
728 status: "idle",
729 pendingBackgroundTasks: [],
730 },
731 ],
732 providerTurns: [],
733 runs: [
734 {
735 id: settledRunId,
736 status: "completed",
737 providerInstanceId: claudeInstanceId,
738 },
739 {
740 id: activeRunId,
741 status: "running",
742 providerInstanceId: claudeInstanceId,
743 },
744 ],
745 attempts: [
746 {
747 id: activeAttemptId,
748 runId: activeRunId,
749 rootNodeId: activeRootNodeId,
750 status: "running",
751 },
752 ],
753 nodes: [{ id: activeRootNodeId, runId: activeRunId, status: "running" }],
754 subagents: [],
755 messages: [],
756 turnItems: [
757 {
758 id: settledStaleItemId,
759 runId: settledRunId,
760 nodeId: null,
761 providerThreadId: idleProviderThreadId,
762 type: "command_execution",
763 status: "running",
764 },
765 {
766 id: activeRunItemId,
767 runId: activeRunId,
768 nodeId: activeRootNodeId,
769 providerThreadId: activeProviderThreadId,
770 type: "dynamic_tool",
771 status: "running",
772 },
773 {
774 // Missing run: must attribute via providerThreadId, not index 0.
775 id: nullRunCommandItemId,
776 runId: null,
777 nodeId: null,
778 providerThreadId: secondaryProviderThreadId,
779 type: "command_execution",
780 status: "running",
781 },
782 {
783 // Missing run with a real matching provider thread whose instance
784 // differs from the subagent's own: own providerInstanceId must win.
785 id: nullRunSubagentItemId,
786 runId: null,
787 nodeId: null,
788 providerThreadId: secondaryProviderThreadId,
789 type: "subagent",
790 status: "running",
791 providerInstanceId: subagentInstanceId,
792 },
793 ],
794 } as unknown as OrchestrationV2ThreadProjection;
795 const layer = ProviderRuntimeRecovery.layer.pipe(
796 Layer.provide(ServerSettings.layerTest()),
797 Layer.provide(
798 Layer.mergeAll(
799 Layer.mock(ProjectionStore.ProjectionStoreV2)({
800 getRecoveryThreadIds: () => Effect.succeed([threadId]),
801 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
802 }),
803 Layer.mock(EventSink.EventSinkV2)({
804 commitCommand: (input) => {
805 committedInput = input;
806 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
807 },
808 }),
809 IdAllocator.layer,
810 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
811 runRecoveryOnce: Effect.succeed(false),
812 }),
813 Layer.mock(EffectOutbox.EffectOutboxV2)({
814 listByCommandId: () => Effect.succeed([]),
815 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
816 }),
817 ),
818 ),
819 );
820
821 return Effect.gen(function* () {
822 const summary =
823 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
824 assert.equal(summary.terminalizedRuns, 1);
825 const events = committedInput?.events ?? [];
826
827 const turnItemCancels = events.filter(
828 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
829 );
830 // Active-run item + settled-run stale + null-run command + null-run subagent.
831 assert.equal(turnItemCancels.length, 4);
832 assert.deepEqual(
833 turnItemCancels
834 .map((event) => event.type === "turn-item.updated" && event.payload.id)
835 .sort(),
836 [activeRunItemId, nullRunCommandItemId, nullRunSubagentItemId, settledStaleItemId].sort(),
837 );
838
839 const cancelById = (id: TurnItemId) =>
840 turnItemCancels.find(
841 (event) => event.type === "turn-item.updated" && event.payload.id === id,
842 );
843 assert.equal(cancelById(nullRunCommandItemId)?.providerInstanceId, secondaryInstanceId);
844 // Subagent own instance wins over the matching thread's secondary instance.
845 assert.notEqual(subagentInstanceId, secondaryInstanceId);
846 assert.equal(cancelById(nullRunSubagentItemId)?.providerInstanceId, subagentInstanceId);
847 // Settled-run item still prefers the run's provider instance when present.
848 assert.equal(cancelById(settledStaleItemId)?.providerInstanceId, claudeInstanceId);
849
850 const providerThreadEvents = events.filter(
851 (event) => event.type === "provider-thread.updated",
852 );
853 // Only threads with active status or nonempty rosters are rewritten.
854 assert.equal(providerThreadEvents.length, 2);
855 for (const event of providerThreadEvents) {
856 if (event.type !== "provider-thread.updated") continue;
857 assert.deepEqual(event.payload.pendingBackgroundTasks ?? [], []);
858 }
859 const idleThreadEvent = providerThreadEvents.find(
860 (event) =>
861 event.type === "provider-thread.updated" && event.payload.id === idleProviderThreadId,
862 );
863 assert.equal(
864 idleThreadEvent?.type === "provider-thread.updated" ? idleThreadEvent.payload.status : null,
865 "idle",
866 );
867 const activeThreadEvent = providerThreadEvents.find(
868 (event) =>
869 event.type === "provider-thread.updated" && event.payload.id === activeProviderThreadId,
870 );
871 assert.equal(
872 activeThreadEvent?.type === "provider-thread.updated"
873 ? activeThreadEvent.payload.status
874 : null,
875 "idle",
876 );
877 }).pipe(Effect.provide(layer));
878 },
879);
880
881it.effect(
882 "terminalizes a leftover nonpersistent dynamic_tool on a settled run after process loss",
883 () => {
884 const threadId = ThreadId.make("thread_recovery_orphan_wait");
885 const settledRunId = RunId.make("run_recovery_orphan_wait_settled");
886 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_orphan_wait");
887 const orphanWaitItemId = TurnItemId.make(
888 "turn-item:provider:codex:native-item:exec-4669f3bb-78c9-4af1-b44e-daa340d2c538",
889 );
890 const persistentMonitorItemId = TurnItemId.make(
891 "turn-item:provider:codex:native-item:exec-persistent-monitor",
892 );
893 const orphanWaitNodeId = NodeId.make("node_recovery_orphan_wait");
894 const persistentMonitorNodeId = NodeId.make("node_recovery_persistent_monitor");
895 const codexInstanceId = ProviderInstanceId.make("codex");
896 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
897 null;
898 const projection = {
899 thread: { id: threadId, providerInstanceId: codexInstanceId },
900 runtimeRequests: [],
901 providerSessions: [],
902 providerThreads: [
903 {
904 id: providerThreadId,
905 driver: ProviderDriverKind.make("codex"),
906 providerInstanceId: codexInstanceId,
907 status: "idle",
908 pendingBackgroundTasks: [],
909 },
910 ],
911 providerTurns: [],
912 runs: [{ id: settledRunId, status: "completed", providerInstanceId: codexInstanceId }],
913 attempts: [],
914 nodes: [
915 { id: orphanWaitNodeId, runId: settledRunId, status: "running", kind: "tool_call" },
916 {
917 id: persistentMonitorNodeId,
918 runId: settledRunId,
919 status: "running",
920 kind: "tool_call",
921 },
922 ],
923 subagents: [],
924 messages: [],
925 turnItems: [
926 {
927 id: orphanWaitItemId,
928 runId: settledRunId,
929 nodeId: orphanWaitNodeId,
930 providerThreadId,
931 type: "dynamic_tool",
932 status: "running",
933 toolName: "t3-code.t3_thread_wait",
934 input: {
935 threadId:
936 "thread:delegated-task:command%3Amcp%3Aaafffab1-e811-458a-ae83-558e542c61ff%3Adelegate-task%3Areview-mobile-reconnect-opus-20260815",
937 timeoutMs: 30000,
938 },
939 },
940 {
941 id: persistentMonitorItemId,
942 runId: settledRunId,
943 nodeId: persistentMonitorNodeId,
944 providerThreadId,
945 type: "dynamic_tool",
946 status: "running",
947 toolName: "grok.monitor",
948 input: { persistent: true, command: "tail -f" },
949 },
950 ],
951 } as unknown as OrchestrationV2ThreadProjection;
952 const layer = ProviderRuntimeRecovery.layer.pipe(
953 Layer.provide(ServerSettings.layerTest()),
954 Layer.provide(
955 Layer.mergeAll(
956 Layer.mock(ProjectionStore.ProjectionStoreV2)({
957 getRecoveryThreadIds: () => Effect.succeed([threadId]),
958 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
959 }),
960 Layer.mock(EventSink.EventSinkV2)({
961 commitCommand: (input) => {
962 committedInput = input;
963 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
964 },
965 }),
966 IdAllocator.layer,
967 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
968 runRecoveryOnce: Effect.succeed(false),
969 }),
970 Layer.mock(EffectOutbox.EffectOutboxV2)({
971 listByCommandId: () => Effect.succeed([]),
972 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
973 }),
974 ),
975 ),
976 );
977
978 return Effect.gen(function* () {
979 const summary =
980 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
981 assert.equal(summary.terminalizedRuns, 0);
982 const turnItemCancels = (committedInput?.events ?? []).filter(
983 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
984 );
985 // Process loss means the provider is gone, so even a persistent monitor
986 // cannot still be alive. The leftover wait and the monitor both close.
987 assert.equal(turnItemCancels.length, 2);
988 assert.deepEqual(
989 turnItemCancels
990 .map((event) => event.type === "turn-item.updated" && event.payload.id)
991 .sort(),
992 [orphanWaitItemId, persistentMonitorItemId].sort(),
993 );
994 const nodeCancels = (committedInput?.events ?? []).filter(
995 (event) => event.type === "node.updated" && event.payload.status === "cancelled",
996 );
997 assert.equal(nodeCancels.length, 2);
998 assert.deepEqual(
999 nodeCancels.map((event) => event.type === "node.updated" && event.payload.id).sort(),
1000 [orphanWaitNodeId, persistentMonitorNodeId].sort(),
1001 );
1002 }).pipe(Effect.provide(layer));
1003 },
1004);
1005
1006it.effect(
1007 "terminalizes the linked subagent and node for a stale subagent item on a settled run",
1008 () => {
1009 const threadId = ThreadId.make("thread_recovery_subagent");
1010 const settledRunId = RunId.make("run_recovery_subagent_settled");
1011 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_subagent");
1012 const staleSubagentNodeId = NodeId.make("node_recovery_subagent_stale");
1013 const doneSubagentNodeId = NodeId.make("node_recovery_subagent_done");
1014 const staleItemId = TurnItemId.make("turn_item_recovery_subagent_stale");
1015 const doneItemId = TurnItemId.make("turn_item_recovery_subagent_done");
1016 const claudeInstanceId = ProviderInstanceId.make("claude");
1017 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
1018 null;
1019 const projection = {
1020 thread: { id: threadId },
1021 runtimeRequests: [],
1022 providerSessions: [],
1023 providerThreads: [
1024 {
1025 id: providerThreadId,
1026 driver: ProviderDriverKind.make("claude"),
1027 providerInstanceId: claudeInstanceId,
1028 status: "idle",
1029 pendingBackgroundTasks: [],
1030 },
1031 ],
1032 providerTurns: [],
1033 // Settled run: the stale-item loop owns it, not the nonterminal loop.
1034 runs: [{ id: settledRunId, status: "completed", providerInstanceId: claudeInstanceId }],
1035 attempts: [],
1036 nodes: [
1037 { id: staleSubagentNodeId, runId: settledRunId, status: "running" },
1038 { id: doneSubagentNodeId, runId: settledRunId, status: "completed" },
1039 ],
1040 subagents: [
1041 {
1042 id: staleSubagentNodeId,
1043 runId: settledRunId,
1044 driver: ProviderDriverKind.make("claude"),
1045 providerInstanceId: claudeInstanceId,
1046 status: "running",
1047 },
1048 {
1049 // Already finished with a real result: must never be overwritten.
1050 id: doneSubagentNodeId,
1051 runId: settledRunId,
1052 driver: ProviderDriverKind.make("claude"),
1053 providerInstanceId: claudeInstanceId,
1054 status: "completed",
1055 result: "done",
1056 },
1057 ],
1058 messages: [],
1059 turnItems: [
1060 {
1061 id: staleItemId,
1062 runId: settledRunId,
1063 nodeId: staleSubagentNodeId,
1064 providerThreadId,
1065 type: "subagent",
1066 status: "running",
1067 subagentId: staleSubagentNodeId,
1068 providerInstanceId: claudeInstanceId,
1069 },
1070 {
1071 id: doneItemId,
1072 runId: settledRunId,
1073 nodeId: doneSubagentNodeId,
1074 providerThreadId,
1075 type: "subagent",
1076 status: "completed",
1077 subagentId: doneSubagentNodeId,
1078 providerInstanceId: claudeInstanceId,
1079 },
1080 ],
1081 } as unknown as OrchestrationV2ThreadProjection;
1082 const layer = ProviderRuntimeRecovery.layer.pipe(
1083 Layer.provide(ServerSettings.layerTest()),
1084 Layer.provide(
1085 Layer.mergeAll(
1086 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1087 getRecoveryThreadIds: () => Effect.succeed([threadId]),
1088 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
1089 }),
1090 Layer.mock(EventSink.EventSinkV2)({
1091 commitCommand: (input) => {
1092 committedInput = input;
1093 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
1094 },
1095 }),
1096 IdAllocator.layer,
1097 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
1098 runRecoveryOnce: Effect.succeed(false),
1099 }),
1100 Layer.mock(EffectOutbox.EffectOutboxV2)({
1101 listByCommandId: () => Effect.succeed([]),
1102 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
1103 }),
1104 ),
1105 ),
1106 );
1107
1108 return Effect.gen(function* () {
1109 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
1110 const events = committedInput?.events ?? [];
1111
1112 // Only the nonterminal subagent item is cancelled.
1113 const turnItemCancels = events.filter(
1114 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
1115 );
1116 assert.equal(turnItemCancels.length, 1);
1117
1118 // The linked subagent entity is terminalized alongside its turn item.
1119 const subagentCancels = events.filter((event) => event.type === "subagent.updated");
1120 assert.equal(subagentCancels.length, 1);
1121 const subagentCancel = subagentCancels[0];
1122 assert.equal(
1123 subagentCancel?.type === "subagent.updated" ? subagentCancel.payload.id : null,
1124 staleSubagentNodeId,
1125 );
1126 assert.equal(
1127 subagentCancel?.type === "subagent.updated" ? subagentCancel.payload.status : null,
1128 "cancelled",
1129 );
1130
1131 // So is its execution node, which no live process can terminalize.
1132 const nodeCancels = events.filter((event) => event.type === "node.updated");
1133 assert.equal(nodeCancels.length, 1);
1134 const nodeCancel = nodeCancels[0];
1135 assert.equal(
1136 nodeCancel?.type === "node.updated" ? nodeCancel.payload.id : null,
1137 staleSubagentNodeId,
1138 );
1139
1140 // The already-completed subagent and node are left untouched.
1141 assert.isFalse(
1142 events.some(
1143 (event) => event.type === "subagent.updated" && event.payload.id === doneSubagentNodeId,
1144 ),
1145 );
1146 assert.isFalse(
1147 events.some(
1148 (event) => event.type === "node.updated" && event.payload.id === doneSubagentNodeId,
1149 ),
1150 );
1151 }).pipe(Effect.provide(layer));
1152 },
1153);