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

ProviderRuntimeRecoveryService.test.ts

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