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

ProviderRuntimeRecoveryService.test.ts

1,151 lines42.0 KB

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("holds accepted queued work without cancelling its execution state 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, 0);
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, "queued");
534 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queuePosition : null, 1);
535 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queueHeld : false, true);
536 assert.isUndefined(attemptEvent);
537 assert.isUndefined(nodeEvent);
538 }).pipe(Effect.provide(layer));
539});
540​
541it.effect(
542 "cancels the complete in-flight subtree and stops its persisted session without reopening it",
543 () => {
544 const threadId = ThreadId.make("thread_recovery_cancel");
545 const runId = RunId.make("run_recovery_cancel");
546 const attemptId = RunAttemptId.make("attempt_recovery_cancel");
547 const rootNodeId = NodeId.make("node_recovery_cancel");
548 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_cancel");
549 const providerTurnId = ProviderTurnId.make("provider_turn_recovery_cancel");
550 const providerSessionId = ProviderSessionId.make("provider_session_recovery_cancel");
551 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
552 null;
553 const projection = {
554 thread: { id: threadId },
555 runtimeRequests: [],
556 providerSessions: [
557 {
558 id: providerSessionId,
559 driver: ProviderDriverKind.make("codex"),
560 providerInstanceId: ProviderInstanceId.make("codex"),
561 status: "ready",
562 },
563 ],
564 providerThreads: [
565 {
566 id: providerThreadId,
567 driver: ProviderDriverKind.make("codex"),
568 providerInstanceId: ProviderInstanceId.make("codex"),
569 status: "active",
570 },
571 ],
572 providerTurns: [
573 {
574 id: providerTurnId,
575 runAttemptId: attemptId,
576 nodeId: rootNodeId,
577 status: "running",
578 },
579 ],
580 runs: [
581 {
582 id: runId,
583 status: "starting",
584 providerThreadId,
585 providerInstanceId: ProviderInstanceId.make("codex"),
586 },
587 ],
588 attempts: [
589 {
590 id: attemptId,
591 runId,
592 rootNodeId,
593 status: "running",
594 },
595 ],
596 nodes: [{ id: rootNodeId, runId, status: "running" }],
597 subagents: [],
598 messages: [{ id: MessageId.make("message_recovery_cancel"), runId, streaming: true }],
599 turnItems: [
600 {
601 id: TurnItemId.make("turn_item_recovery_cancel"),
602 runId,
603 nodeId: rootNodeId,
604 status: "running",
605 },
606 ],
607 } as unknown as OrchestrationV2ThreadProjection;
608 const layer = ProviderRuntimeRecovery.layer.pipe(
609 Layer.provide(ServerSettings.layerTest()),
610 Layer.provide(
611 Layer.mergeAll(
612 Layer.mock(ProjectionStore.ProjectionStoreV2)({
613 getRecoveryThreadIds: () => Effect.succeed([threadId]),
614 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
615 }),
616 Layer.mock(EventSink.EventSinkV2)({
617 commitCommand: (input) => {
618 committedInput = input;
619 return Effect.succeed({ committed: true, cancelledEffectCount: 2 } as never);
620 },
621 }),
622 IdAllocator.layer,
623 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
624 runRecoveryOnce: Effect.succeed(false),
625 }),
626 Layer.mock(EffectOutbox.EffectOutboxV2)({
627 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
628 }),
629 ),
630 ),
631 );
632​
633 return Effect.gen(function* () {
634 const summary = yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)
635 .recover;
636 assert.equal(summary.terminalizedRuns, 1);
637 assert.equal(summary.stoppedSessions, 1);
638 assert.equal(summary.retiredEffects, 2);
639 assert.deepEqual(committedInput?.cancelUnsettledEffects?.effectTypes, [
640 "provider-turn.start",
641 "provider-turn.interrupt",
642 "provider-turn.steer",
643 "provider-turn.restart",
644 "runtime-request.respond",
645 ]);
646 const events = committedInput?.events ?? [];
647 assert.deepEqual(
648 events.map((event) => [
649 event.type,
650 "status" in event.payload ? event.payload.status : null,
651 ]),
652 [
653 ["run.updated", "cancelled"],
654 ["run-attempt.updated", "cancelled"],
655 ["node.updated", "cancelled"],
656 ["provider-turn.updated", "cancelled"],
657 ["message.updated", null],
658 ["turn-item.updated", "cancelled"],
659 ["provider-thread.updated", "idle"],
660 ["provider-session.updated", "stopped"],
661 ],
662 );
663 const messageEvent = events.find((event) => event.type === "message.updated");
664 assert.isFalse(messageEvent?.type === "message.updated" && messageEvent.payload.streaming);
665 }).pipe(Effect.provide(layer));
666 },
667);
668​
669it.effect(
670 "clears persisted pendingBackgroundTasks and terminalizes stale background items on settled runs",
671 () => {
672 const threadId = ThreadId.make("thread_recovery_background");
673 const settledRunId = RunId.make("run_recovery_background_settled");
674 const activeRunId = RunId.make("run_recovery_background_active");
675 const activeAttemptId = RunAttemptId.make("attempt_recovery_background_active");
676 const activeRootNodeId = NodeId.make("node_recovery_background_active");
677 const idleProviderThreadId = ProviderThreadId.make("provider_thread_recovery_background_idle");
678 const activeProviderThreadId = ProviderThreadId.make(
679 "provider_thread_recovery_background_active",
680 );
681 const secondaryProviderThreadId = ProviderThreadId.make(
682 "provider_thread_recovery_background_secondary",
683 );
684 const providerSessionId = ProviderSessionId.make("provider_session_recovery_background");
685 const settledStaleItemId = TurnItemId.make("turn_item_recovery_background_stale");
686 const activeRunItemId = TurnItemId.make("turn_item_recovery_background_active");
687 const nullRunCommandItemId = TurnItemId.make("turn_item_recovery_background_null_run");
688 const nullRunSubagentItemId = TurnItemId.make("turn_item_recovery_background_null_subagent");
689 const claudeInstanceId = ProviderInstanceId.make("claude");
690 const secondaryInstanceId = ProviderInstanceId.make("claude-secondary");
691 const subagentInstanceId = ProviderInstanceId.make("claude-subagent");
692 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
693 null;
694 const projection = {
695 thread: { id: threadId },
696 runtimeRequests: [],
697 providerSessions: [
698 {
699 id: providerSessionId,
700 driver: ProviderDriverKind.make("claude"),
701 providerInstanceId: claudeInstanceId,
702 status: "ready",
703 },
704 ],
705 providerThreads: [
706 {
707 id: idleProviderThreadId,
708 driver: ProviderDriverKind.make("claude"),
709 // Index-0 is intentionally a different instance so misattribution
710 // to providerThreads[0] fails the assertions below.
711 providerInstanceId: claudeInstanceId,
712 status: "idle",
713 pendingBackgroundTasks: [{ taskId: "bg-settled", description: "sleep 30" }],
714 },
715 {
716 id: activeProviderThreadId,
717 driver: ProviderDriverKind.make("claude"),
718 providerInstanceId: claudeInstanceId,
719 status: "active",
720 pendingBackgroundTasks: [{ taskId: "bg-active", description: "npm test" }],
721 },
722 {
723 id: secondaryProviderThreadId,
724 driver: ProviderDriverKind.make("claude"),
725 providerInstanceId: secondaryInstanceId,
726 status: "idle",
727 pendingBackgroundTasks: [],
728 },
729 ],
730 providerTurns: [],
731 runs: [
732 {
733 id: settledRunId,
734 status: "completed",
735 providerInstanceId: claudeInstanceId,
736 },
737 {
738 id: activeRunId,
739 status: "running",
740 providerInstanceId: claudeInstanceId,
741 },
742 ],
743 attempts: [
744 {
745 id: activeAttemptId,
746 runId: activeRunId,
747 rootNodeId: activeRootNodeId,
748 status: "running",
749 },
750 ],
751 nodes: [{ id: activeRootNodeId, runId: activeRunId, status: "running" }],
752 subagents: [],
753 messages: [],
754 turnItems: [
755 {
756 id: settledStaleItemId,
757 runId: settledRunId,
758 nodeId: null,
759 providerThreadId: idleProviderThreadId,
760 type: "command_execution",
761 status: "running",
762 },
763 {
764 id: activeRunItemId,
765 runId: activeRunId,
766 nodeId: activeRootNodeId,
767 providerThreadId: activeProviderThreadId,
768 type: "dynamic_tool",
769 status: "running",
770 },
771 {
772 // Missing run: must attribute via providerThreadId, not index 0.
773 id: nullRunCommandItemId,
774 runId: null,
775 nodeId: null,
776 providerThreadId: secondaryProviderThreadId,
777 type: "command_execution",
778 status: "running",
779 },
780 {
781 // Missing run with a real matching provider thread whose instance
782 // differs from the subagent's own: own providerInstanceId must win.
783 id: nullRunSubagentItemId,
784 runId: null,
785 nodeId: null,
786 providerThreadId: secondaryProviderThreadId,
787 type: "subagent",
788 status: "running",
789 providerInstanceId: subagentInstanceId,
790 },
791 ],
792 } as unknown as OrchestrationV2ThreadProjection;
793 const layer = ProviderRuntimeRecovery.layer.pipe(
794 Layer.provide(ServerSettings.layerTest()),
795 Layer.provide(
796 Layer.mergeAll(
797 Layer.mock(ProjectionStore.ProjectionStoreV2)({
798 getRecoveryThreadIds: () => Effect.succeed([threadId]),
799 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
800 }),
801 Layer.mock(EventSink.EventSinkV2)({
802 commitCommand: (input) => {
803 committedInput = input;
804 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
805 },
806 }),
807 IdAllocator.layer,
808 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
809 runRecoveryOnce: Effect.succeed(false),
810 }),
811 Layer.mock(EffectOutbox.EffectOutboxV2)({
812 listByCommandId: () => Effect.succeed([]),
813 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
814 }),
815 ),
816 ),
817 );
818​
819 return Effect.gen(function* () {
820 const summary =
821 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
822 assert.equal(summary.terminalizedRuns, 1);
823 const events = committedInput?.events ?? [];
824​
825 const turnItemCancels = events.filter(
826 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
827 );
828 // Active-run item + settled-run stale + null-run command + null-run subagent.
829 assert.equal(turnItemCancels.length, 4);
830 assert.deepEqual(
831 turnItemCancels
832 .map((event) => event.type === "turn-item.updated" && event.payload.id)
833 .sort(),
834 [activeRunItemId, nullRunCommandItemId, nullRunSubagentItemId, settledStaleItemId].sort(),
835 );
836​
837 const cancelById = (id: TurnItemId) =>
838 turnItemCancels.find(
839 (event) => event.type === "turn-item.updated" && event.payload.id === id,
840 );
841 assert.equal(cancelById(nullRunCommandItemId)?.providerInstanceId, secondaryInstanceId);
842 // Subagent own instance wins over the matching thread's secondary instance.
843 assert.notEqual(subagentInstanceId, secondaryInstanceId);
844 assert.equal(cancelById(nullRunSubagentItemId)?.providerInstanceId, subagentInstanceId);
845 // Settled-run item still prefers the run's provider instance when present.
846 assert.equal(cancelById(settledStaleItemId)?.providerInstanceId, claudeInstanceId);
847​
848 const providerThreadEvents = events.filter(
849 (event) => event.type === "provider-thread.updated",
850 );
851 // Only threads with active status or nonempty rosters are rewritten.
852 assert.equal(providerThreadEvents.length, 2);
853 for (const event of providerThreadEvents) {
854 if (event.type !== "provider-thread.updated") continue;
855 assert.deepEqual(event.payload.pendingBackgroundTasks ?? [], []);
856 }
857 const idleThreadEvent = providerThreadEvents.find(
858 (event) =>
859 event.type === "provider-thread.updated" && event.payload.id === idleProviderThreadId,
860 );
861 assert.equal(
862 idleThreadEvent?.type === "provider-thread.updated" ? idleThreadEvent.payload.status : null,
863 "idle",
864 );
865 const activeThreadEvent = providerThreadEvents.find(
866 (event) =>
867 event.type === "provider-thread.updated" && event.payload.id === activeProviderThreadId,
868 );
869 assert.equal(
870 activeThreadEvent?.type === "provider-thread.updated"
871 ? activeThreadEvent.payload.status
872 : null,
873 "idle",
874 );
875 }).pipe(Effect.provide(layer));
876 },
877);
878​
879it.effect(
880 "terminalizes a leftover nonpersistent dynamic_tool on a settled run after process loss",
881 () => {
882 const threadId = ThreadId.make("thread_recovery_orphan_wait");
883 const settledRunId = RunId.make("run_recovery_orphan_wait_settled");
884 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_orphan_wait");
885 const orphanWaitItemId = TurnItemId.make(
886 "turn-item:provider:codex:native-item:exec-4669f3bb-78c9-4af1-b44e-daa340d2c538",
887 );
888 const persistentMonitorItemId = TurnItemId.make(
889 "turn-item:provider:codex:native-item:exec-persistent-monitor",
890 );
891 const orphanWaitNodeId = NodeId.make("node_recovery_orphan_wait");
892 const persistentMonitorNodeId = NodeId.make("node_recovery_persistent_monitor");
893 const codexInstanceId = ProviderInstanceId.make("codex");
894 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
895 null;
896 const projection = {
897 thread: { id: threadId, providerInstanceId: codexInstanceId },
898 runtimeRequests: [],
899 providerSessions: [],
900 providerThreads: [
901 {
902 id: providerThreadId,
903 driver: ProviderDriverKind.make("codex"),
904 providerInstanceId: codexInstanceId,
905 status: "idle",
906 pendingBackgroundTasks: [],
907 },
908 ],
909 providerTurns: [],
910 runs: [{ id: settledRunId, status: "completed", providerInstanceId: codexInstanceId }],
911 attempts: [],
912 nodes: [
913 { id: orphanWaitNodeId, runId: settledRunId, status: "running", kind: "tool_call" },
914 {
915 id: persistentMonitorNodeId,
916 runId: settledRunId,
917 status: "running",
918 kind: "tool_call",
919 },
920 ],
921 subagents: [],
922 messages: [],
923 turnItems: [
924 {
925 id: orphanWaitItemId,
926 runId: settledRunId,
927 nodeId: orphanWaitNodeId,
928 providerThreadId,
929 type: "dynamic_tool",
930 status: "running",
931 toolName: "t3-code.t3_thread_wait",
932 input: {
933 threadId:
934 "thread:delegated-task:command%3Amcp%3Aaafffab1-e811-458a-ae83-558e542c61ff%3Adelegate-task%3Areview-mobile-reconnect-opus-20260815",
935 timeoutMs: 30000,
936 },
937 },
938 {
939 id: persistentMonitorItemId,
940 runId: settledRunId,
941 nodeId: persistentMonitorNodeId,
942 providerThreadId,
943 type: "dynamic_tool",
944 status: "running",
945 toolName: "grok.monitor",
946 input: { persistent: true, command: "tail -f" },
947 },
948 ],
949 } as unknown as OrchestrationV2ThreadProjection;
950 const layer = ProviderRuntimeRecovery.layer.pipe(
951 Layer.provide(ServerSettings.layerTest()),
952 Layer.provide(
953 Layer.mergeAll(
954 Layer.mock(ProjectionStore.ProjectionStoreV2)({
955 getRecoveryThreadIds: () => Effect.succeed([threadId]),
956 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
957 }),
958 Layer.mock(EventSink.EventSinkV2)({
959 commitCommand: (input) => {
960 committedInput = input;
961 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
962 },
963 }),
964 IdAllocator.layer,
965 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
966 runRecoveryOnce: Effect.succeed(false),
967 }),
968 Layer.mock(EffectOutbox.EffectOutboxV2)({
969 listByCommandId: () => Effect.succeed([]),
970 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
971 }),
972 ),
973 ),
974 );
975​
976 return Effect.gen(function* () {
977 const summary =
978 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
979 assert.equal(summary.terminalizedRuns, 0);
980 const turnItemCancels = (committedInput?.events ?? []).filter(
981 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
982 );
983 // Process loss means the provider is gone, so even a persistent monitor
984 // cannot still be alive. The leftover wait and the monitor both close.
985 assert.equal(turnItemCancels.length, 2);
986 assert.deepEqual(
987 turnItemCancels
988 .map((event) => event.type === "turn-item.updated" && event.payload.id)
989 .sort(),
990 [orphanWaitItemId, persistentMonitorItemId].sort(),
991 );
992 const nodeCancels = (committedInput?.events ?? []).filter(
993 (event) => event.type === "node.updated" && event.payload.status === "cancelled",
994 );
995 assert.equal(nodeCancels.length, 2);
996 assert.deepEqual(
997 nodeCancels.map((event) => event.type === "node.updated" && event.payload.id).sort(),
998 [orphanWaitNodeId, persistentMonitorNodeId].sort(),
999 );
1000 }).pipe(Effect.provide(layer));
1001 },
1003​
1004it.effect(
1005 "terminalizes the linked subagent and node for a stale subagent item on a settled run",
1006 () => {
1007 const threadId = ThreadId.make("thread_recovery_subagent");
1008 const settledRunId = RunId.make("run_recovery_subagent_settled");
1009 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_subagent");
1010 const staleSubagentNodeId = NodeId.make("node_recovery_subagent_stale");
1011 const doneSubagentNodeId = NodeId.make("node_recovery_subagent_done");
1012 const staleItemId = TurnItemId.make("turn_item_recovery_subagent_stale");
1013 const doneItemId = TurnItemId.make("turn_item_recovery_subagent_done");
1014 const claudeInstanceId = ProviderInstanceId.make("claude");
1015 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
1016 null;
1017 const projection = {
1018 thread: { id: threadId },
1019 runtimeRequests: [],
1020 providerSessions: [],
1021 providerThreads: [
1023 id: providerThreadId,
1024 driver: ProviderDriverKind.make("claude"),
1025 providerInstanceId: claudeInstanceId,
1026 status: "idle",
1027 pendingBackgroundTasks: [],
1028 },
1029 ],
1030 providerTurns: [],
1031 // Settled run: the stale-item loop owns it, not the nonterminal loop.
1032 runs: [{ id: settledRunId, status: "completed", providerInstanceId: claudeInstanceId }],
1033 attempts: [],
1034 nodes: [
1035 { id: staleSubagentNodeId, runId: settledRunId, status: "running" },
1036 { id: doneSubagentNodeId, runId: settledRunId, status: "completed" },
1037 ],
1038 subagents: [
1040 id: staleSubagentNodeId,
1041 runId: settledRunId,
1042 driver: ProviderDriverKind.make("claude"),
1043 providerInstanceId: claudeInstanceId,
1044 status: "running",
1045 },
1047 // Already finished with a real result: must never be overwritten.
1048 id: doneSubagentNodeId,
1049 runId: settledRunId,
1050 driver: ProviderDriverKind.make("claude"),
1051 providerInstanceId: claudeInstanceId,
1052 status: "completed",
1053 result: "done",
1054 },
1055 ],
1056 messages: [],
1057 turnItems: [
1059 id: staleItemId,
1060 runId: settledRunId,
1061 nodeId: staleSubagentNodeId,
1062 providerThreadId,
1063 type: "subagent",
1064 status: "running",
1065 subagentId: staleSubagentNodeId,
1066 providerInstanceId: claudeInstanceId,
1067 },
1069 id: doneItemId,
1070 runId: settledRunId,
1071 nodeId: doneSubagentNodeId,
1072 providerThreadId,
1073 type: "subagent",
1074 status: "completed",
1075 subagentId: doneSubagentNodeId,
1076 providerInstanceId: claudeInstanceId,
1077 },
1078 ],
1079 } as unknown as OrchestrationV2ThreadProjection;
1080 const layer = ProviderRuntimeRecovery.layer.pipe(
1081 Layer.provide(ServerSettings.layerTest()),
1082 Layer.provide(
1083 Layer.mergeAll(
1084 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1085 getRecoveryThreadIds: () => Effect.succeed([threadId]),
1086 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
1087 }),
1088 Layer.mock(EventSink.EventSinkV2)({
1089 commitCommand: (input) => {
1090 committedInput = input;
1091 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
1092 },
1093 }),
1094 IdAllocator.layer,
1095 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
1096 runRecoveryOnce: Effect.succeed(false),
1097 }),
1098 Layer.mock(EffectOutbox.EffectOutboxV2)({
1099 listByCommandId: () => Effect.succeed([]),
1100 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
1101 }),
1102 ),
1103 ),
1104 );
1105​
1106 return Effect.gen(function* () {
1107 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
1108 const events = committedInput?.events ?? [];
1109​
1110 // Only the nonterminal subagent item is cancelled.
1111 const turnItemCancels = events.filter(
1112 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
1113 );
1114 assert.equal(turnItemCancels.length, 1);
1115​
1116 // The linked subagent entity is terminalized alongside its turn item.
1117 const subagentCancels = events.filter((event) => event.type === "subagent.updated");
1118 assert.equal(subagentCancels.length, 1);
1119 const subagentCancel = subagentCancels[0];
1120 assert.equal(
1121 subagentCancel?.type === "subagent.updated" ? subagentCancel.payload.id : null,
1122 staleSubagentNodeId,
1123 );
1124 assert.equal(
1125 subagentCancel?.type === "subagent.updated" ? subagentCancel.payload.status : null,
1126 "cancelled",
1127 );
1128​
1129 // So is its execution node, which no live process can terminalize.
1130 const nodeCancels = events.filter((event) => event.type === "node.updated");
1131 assert.equal(nodeCancels.length, 1);
1132 const nodeCancel = nodeCancels[0];
1133 assert.equal(
1134 nodeCancel?.type === "node.updated" ? nodeCancel.payload.id : null,
1135 staleSubagentNodeId,
1136 );
1137​
1138 // The already-completed subagent and node are left untouched.
1139 assert.isFalse(
1140 events.some(
1141 (event) => event.type === "subagent.updated" && event.payload.id === doneSubagentNodeId,
1142 ),
1143 );
1144 assert.isFalse(
1145 events.some(
1146 (event) => event.type === "node.updated" && event.payload.id === doneSubagentNodeId,
1147 ),
1148 );
1149 }).pipe(Effect.provide(layer));
1150 },