Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 ContextTransferId,
5 EventId,
6 MessageId,
7 NodeId,
8 type OrchestrationV2AppThread,
9 type OrchestrationV2Run,
10 ProjectId,
11 ProviderDriverKind,
12 ProviderInstanceId,
13 ProviderSessionId,
14 ProviderThreadId,
15 ProviderTurnId,
16 RunId,
17 RuntimeRequestId,
18 ThreadId,
19 TurnItemId,
20} from "@t3tools/contracts";
21import * as DateTime from "effect/DateTime";
22import * as Effect from "effect/Effect";
23import * as Layer from "effect/Layer";
24import * as SqlClient from "effect/sql/SqlClient";
25
26import * as SqlitePersistence from "../persistence/Sqlite.ts";
27import * as ServerSettings from "../serverSettings.ts";
28import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
29import * as EffectOutbox from "./EffectOutbox.ts";
30import * as ProjectionStore from "./ProjectionStore.ts";
31import * as EventSink from "./EventSink.ts";
32import * as EventStore from "./EventStore.ts";
33import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
34import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
35import { restartContinuationRun } from "./RestartContinuation.ts";
36
37const layerTest = Layer.mergeAll(ProjectionStore.layer, EffectOutbox.layer).pipe(
38 Layer.provideMerge(SqlitePersistence.layerMemory),
39);
40const layerRecoveryTest = ProviderRuntimeRecovery.layer.pipe(
41 Layer.provideMerge(
42 EventSink.layer.pipe(
43 Layer.provideMerge(
44 Layer.mergeAll(
45 EventStore.layer,
46 ProjectionStore.layer,
47 EffectOutbox.layer,
48 IdAllocator.layer,
49 ).pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
50 ),
51 ),
52 ),
53 Layer.provide(ServerSettings.layerTest()),
54);
55const providerInstanceId = ProviderInstanceId.make("codex");
56const modelSelection = { instanceId: providerInstanceId, model: "gpt-5.4" };
57const driver = ProviderDriverKind.make("codex");
58
59const createThread = Effect.fn(function* (
60 name: string,
61 overrides: Partial<OrchestrationV2AppThread> = {},
62) {
63 const projections = yield* ProjectionStore.ProjectionStoreV2;
64 const now = yield* DateTime.now;
65 const threadId = ThreadId.make(`thread:recovery:${name}`);
66 const thread: OrchestrationV2AppThread = {
67 createdBy: "user",
68 creationSource: "web",
69 id: threadId,
70 projectId: ProjectId.make("project:recovery"),
71 title: name,
72 providerInstanceId,
73 modelSelection,
74 runtimeMode: "full-access",
75 interactionMode: "default",
76 branch: null,
77 worktreePath: null,
78 activeProviderThreadId: null,
79 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
80 forkedFrom: null,
81 createdAt: now,
82 updatedAt: now,
83 archivedAt: null,
84 settledOverride: null,
85 settledAt: null,
86 lastVisitedAt: null,
87 deletedAt: null,
88 ...overrides,
89 };
90 yield* projections.apply({
91 id: EventId.make(`event:${threadId}:created`),
92 type: "thread.created",
93 threadId,
94 occurredAt: now,
95 payload: thread,
96 });
97 return threadId;
98});
99
100const createRun = Effect.fn(function* (
101 threadId: ThreadId,
102 status: OrchestrationV2Run["status"],
103 overrides: Partial<OrchestrationV2Run> = {},
104) {
105 const projections = yield* ProjectionStore.ProjectionStoreV2;
106 const now = yield* DateTime.now;
107 const ordinal = overrides.ordinal ?? 1;
108 const runId = RunId.make(`run:${threadId}:${ordinal}`);
109 yield* projections.apply({
110 id: EventId.make(`event:${runId}:created`),
111 type: "run.created",
112 threadId,
113 runId,
114 occurredAt: now,
115 payload: {
116 id: runId,
117 threadId,
118 ordinal,
119 providerInstanceId,
120 modelSelection,
121 providerThreadId: null,
122 userMessageId: MessageId.make(`message:${runId}`),
123 rootNodeId: null,
124 activeAttemptId: null,
125 status,
126 requestedAt: now,
127 startedAt: now,
128 completedAt: status === "completed" ? now : null,
129 checkpointId: null,
130 contextHandoffId: null,
131 ...overrides,
132 },
133 });
134 return runId;
135});
136
137it.effect.each(["startup", "shutdown"] as const)(
138 "%s cancels queued buffered wakes and holds durable messages",
139 (trigger) =>
140 Effect.gen(function* () {
141 const projections = yield* ProjectionStore.ProjectionStoreV2;
142 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
143 const now = yield* DateTime.now;
144 const bufferedThreads = [] as ThreadId[];
145 const durableThreads = [] as ThreadId[];
146 for (const kind of ["buffered", "user", "notification", "delegated"] as const) {
147 const threadId = yield* createThread(`wake:${trigger}:${kind}`);
148 const buffered = kind === "buffered";
149 (buffered ? bufferedThreads : durableThreads).push(threadId);
150 const messageId = MessageId.make(`message:${threadId}`);
151 const runId = yield* createRun(threadId, "queued", {
152 userMessageId: messageId,
153 startedAt: null,
154 queuePosition: 1,
155 });
156 yield* createRun(threadId, "completed", { ordinal: 2 });
157 yield* projections.apply({
158 id: EventId.make(`message:${threadId}`),
159 type: "message.updated",
160 threadId,
161 runId,
162 occurredAt: now,
163 payload: {
164 id: messageId,
165 threadId,
166 runId,
167 nodeId: null,
168 role: "user",
169 text: "Queued work",
170 attachments: [],
171 streaming: false,
172 createdAt: now,
173 updatedAt: now,
174 createdBy: kind === "user" ? "user" : "agent",
175 creationSource: buffered ? "provider" : "server",
176 ...(kind === "user" || kind === "delegated"
177 ? {}
178 : {
179 notification: {
180 source: { kind: "background_task" as const },
181 outcome: "updated" as const,
182 summary: "Background activity updated",
183 },
184 }),
185 ...(kind === "delegated"
186 ? { delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [] } }
187 : {}),
188 },
189 });
190 }
191 assert.deepEqual(
192 new Set(yield* projections.getRecoveryThreadIds("runtime")),
193 new Set([...bufferedThreads, ...durableThreads]),
194 );
195 const summary = yield* recovery.reconcile(trigger);
196 assert.equal(summary.terminalizedRuns, 1);
197 for (const threadId of bufferedThreads) {
198 const projection = yield* projections.getThreadProjection(threadId);
199 assert.equal(projection.runs[0]?.status, "cancelled");
200 assert.isNotNull(projection.runs[0]?.completedAt);
201 assert.isNull(projection.runs[0]?.queuePosition);
202 assert.equal(projection.runs[1]?.status, "completed");
203 }
204 for (const threadId of durableThreads) {
205 const projection = yield* projections.getThreadProjection(threadId);
206 assert.equal(projection.runs[0]?.status, "queued");
207 assert.isTrue(projection.runs[0]?.queueHeld);
208 }
209 assert.deepEqual(yield* projections.getRecoveryThreadIds("runtime"), []);
210 }).pipe(Effect.provide(layerRecoveryTest)),
211);
212
213it.effect("stops a session its thread detached, which kept its live status", () =>
214 Effect.gen(function* () {
215 const projections = yield* ProjectionStore.ProjectionStoreV2;
216 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
217 const now = yield* DateTime.now;
218 const threadId = yield* createThread("detached-session");
219 const providerSessionId = ProviderSessionId.make("session:recovery:detached");
220 yield* projections.apply({
221 id: EventId.make("event:recovery:detached-session:attached"),
222 type: "provider-session.attached",
223 threadId,
224 driver,
225 providerInstanceId,
226 occurredAt: now,
227 payload: {
228 id: providerSessionId,
229 driver,
230 providerInstanceId,
231 status: "ready",
232 cwd: "/workspace",
233 model: modelSelection.model,
234 capabilities: CodexProviderCapabilitiesV2,
235 createdAt: now,
236 updatedAt: now,
237 lastError: null,
238 },
239 });
240 yield* projections.apply({
241 id: EventId.make("event:recovery:detached-session:detached"),
242 type: "provider-session.detached",
243 threadId,
244 driver,
245 providerInstanceId,
246 occurredAt: now,
247 payload: { providerSessionId, detachedAt: now, reason: "Thread settled." },
248 });
249 assert.deepEqual(yield* projections.getRecoveryThreadIds("runtime"), [threadId]);
250
251 const summary = yield* recovery.reconcile("startup");
252
253 assert.equal(summary.stoppedSessions, 1);
254 const sql = yield* SqlClient.SqlClient;
255 const rows = yield* sql<{ readonly status: string }>`
256 SELECT status FROM orchestration_v2_projection_provider_sessions
257 WHERE provider_session_id = ${providerSessionId}
258 `;
259 assert.deepEqual(rows, [{ status: "stopped" }]);
260 assert.deepEqual(yield* projections.getRecoveryThreadIds("runtime"), []);
261 }).pipe(Effect.provide(layerRecoveryTest)),
262);
263
264it.effect("selects unfinished recovery work without reading settled thread histories", () =>
265 Effect.gen(function* () {
266 const projections = yield* ProjectionStore.ProjectionStoreV2;
267 const outbox = yield* EffectOutbox.EffectOutboxV2;
268 const sql = yield* SqlClient.SqlClient;
269 const now = yield* DateTime.now;
270 for (let index = 0; index < 600; index += 1) {
271 yield* createRun(yield* createThread(`settled-${index}`), "completed");
272 }
273 const queued = yield* createThread("queued");
274 const archived = yield* createThread("archived", { archivedAt: now });
275 const deleted = yield* createThread("deleted", { deletedAt: now });
276 const blocked = yield* createThread("blocked");
277 yield* createRun(queued, "completed");
278 for (const threadId of [queued, archived, deleted, blocked]) {
279 yield* createRun(threadId, "queued", threadId === queued ? { ordinal: 2 } : {});
280 }
281 yield* createRun(blocked, "waiting", { ordinal: 2 });
282 const background = yield* createThread("background");
283 yield* createRun(background, "completed");
284 yield* projections.apply({
285 id: EventId.make("event:recovery:background"),
286 type: "turn-item.updated",
287 threadId: background,
288 occurredAt: now,
289 payload: {
290 id: TurnItemId.make("item:recovery:background"),
291 threadId: background,
292 runId: null,
293 nodeId: null,
294 providerThreadId: null,
295 providerTurnId: null,
296 nativeItemRef: null,
297 parentItemId: null,
298 ordinal: 1,
299 type: "dynamic_tool",
300 status: "waiting",
301 title: null,
302 startedAt: now,
303 completedAt: null,
304 updatedAt: now,
305 toolName: "background",
306 input: null,
307 output: null,
308 },
309 });
310 const outboxOnly = yield* createThread("outbox-only");
311 yield* outbox.enqueue([
312 {
313 id: "effect:recovery:outbox-only",
314 commandId: CommandId.make("command:recovery:outbox-only"),
315 threadId: outboxOnly,
316 request: { type: "provider-turn.start", runId: RunId.make("run:outbox-only") },
317 },
318 ]);
319 const requestOnly = yield* createThread("request-only");
320 yield* projections.apply({
321 id: EventId.make("event:recovery:request-only"),
322 type: "runtime-request.updated",
323 threadId: requestOnly,
324 occurredAt: now,
325 payload: {
326 id: RuntimeRequestId.make("request:recovery:pending"),
327 nodeId: NodeId.make("node:recovery:request"),
328 providerTurnId: null,
329 nativeRequestRef: null,
330 kind: "user_input",
331 status: "pending",
332 responseCapability: { type: "not_resumable", reason: "Process stopped" },
333 createdAt: now,
334 resolvedAt: null,
335 },
336 });
337 const delivery = yield* createThread("delivery", { archivedAt: now });
338 yield* createRun(delivery, "completed", {
339 delegatedCompletion: {
340 disposition: "open",
341 nextGeneration: 2,
342 delivery: { generation: 1, messageId: MessageId.make("message:delivery"), taskIds: [] },
343 },
344 });
345
346 yield* sql`
347 UPDATE orchestration_v2_projection_runs SET payload_json = '{broken'
348 WHERE thread_id = ${ThreadId.make("thread:recovery:settled-599")}
349 `;
350 yield* sql`
351 UPDATE orchestration_v2_projection_runs SET payload_json = '{broken'
352 WHERE thread_id = ${queued} AND ordinal = 1
353 `;
354 assert.deepEqual(yield* projections.getRecoveryThreadIds("queued-runs"), [queued]);
355 assert.deepEqual(
356 new Set(yield* projections.getRecoveryThreadIds("runtime")),
357 new Set([queued, archived, blocked, background, outboxOnly, requestOnly]),
358 );
359 assert.deepEqual(yield* projections.getRecoveryThreadIds("delegated-completions"), [delivery]);
360 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
361 const recoveryState = yield* projections.getRuntimeRecoveryProjection(queued);
362 assert.deepEqual(
363 recoveryState.runs.map((run) => run.id),
364 [RunId.make(`run:${queued}:2`)],
365 );
366 assert.deepEqual(yield* projections.getUnreadableThreadIds(), [
367 queued,
368 ThreadId.make("thread:recovery:settled-599"),
369 ]);
370 }).pipe(Effect.provide(layerTest)),
371);
372
373it.effect("recovers terminal subagent results until their cross-thread transfer exists", () =>
374 Effect.gen(function* () {
375 const projections = yield* ProjectionStore.ProjectionStoreV2;
376 const sql = yield* SqlClient.SqlClient;
377 const now = yield* DateTime.now;
378 const parent = yield* createThread("subagent-parent");
379 const children: Array<ThreadId> = [];
380 for (const name of ["terminal", "archived", "deleted", "running", "held", "queued"]) {
381 const child = yield* createThread(`subagent-${name}`, {
382 lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent },
383 forkedFrom: { type: "node", nodeId: NodeId.make(`node:${name}`) },
384 archivedAt: name === "archived" ? now : null,
385 deletedAt: name === "deleted" ? now : null,
386 });
387 yield* createRun(child, name === "running" ? "running" : "completed");
388 if (name === "held" || name === "queued") {
389 yield* createRun(child, "queued", {
390 ordinal: 2,
391 startedAt: null,
392 ...(name === "held" ? { queueHeld: true } : {}),
393 });
394 }
395 children.push(child);
396 }
397 const terminalChildren = new Set([children[0]!, children[1]!, children[4]!]);
398 assert.deepEqual(
399 new Set(yield* projections.getRecoveryThreadIds("subagent-results")),
400 terminalChildren,
401 );
402
403 const completed = children[0]!;
404 const transferId = ContextTransferId.make("transfer:recovery:subagent-result");
405 yield* projections.apply({
406 id: EventId.make("event:recovery:subagent-result"),
407 type: "context-transfer.created",
408 threadId: parent,
409 occurredAt: now,
410 payload: {
411 id: transferId,
412 type: "subagent_result",
413 sourceThreadId: completed,
414 targetThreadId: parent,
415 sourcePoint: { threadId: completed },
416 basePoint: null,
417 sourceProviderInstanceId: providerInstanceId,
418 targetProviderInstanceId: providerInstanceId,
419 targetRunId: null,
420 status: "pending",
421 resolution: null,
422 createdBy: "system",
423 error: null,
424 createdAt: now,
425 updatedAt: now,
426 consumedAt: null,
427 },
428 });
429 const archivedChild = children[1];
430 assert.isDefined(archivedChild);
431 assert.deepEqual(
432 new Set(yield* projections.getRecoveryThreadIds("subagent-results")),
433 new Set([archivedChild, children[4]!]),
434 );
435 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
436 yield* sql`
437 UPDATE orchestration_v2_projection_context_transfers SET payload_json = '{}'
438 WHERE context_transfer_id = ${transferId}
439 `;
440 assert.deepEqual(
441 new Set(yield* projections.getUnreadableThreadIds()),
442 new Set([parent, completed]),
443 );
444 }).pipe(Effect.provide(layerTest)),
445);
446
447it.effect.each([
448 { name: "SQLite", layer: layerTest },
449 { name: "memory", layer: ProjectionStore.layerMemory },
450])("recovers only recorded follow-up results with $name projections", ({ layer }) =>
451 Effect.gen(function* () {
452 const projections = yield* ProjectionStore.ProjectionStoreV2;
453 const now = yield* DateTime.now;
454 const parent = yield* createThread("followup-parent");
455 const child = yield* createThread("followup-child", {
456 lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent },
457 forkedFrom: { type: "node", nodeId: NodeId.make("node:original") },
458 });
459 const originalRunId = yield* createRun(child, "completed");
460 yield* projections.apply({
461 id: EventId.make("event:original-result"),
462 type: "context-transfer.created",
463 threadId: parent,
464 occurredAt: now,
465 payload: {
466 id: ContextTransferId.make("transfer:original-result"),
467 type: "subagent_result",
468 sourceThreadId: child,
469 targetThreadId: parent,
470 sourcePoint: { threadId: child, runId: originalRunId },
471 basePoint: null,
472 sourceProviderInstanceId: providerInstanceId,
473 targetProviderInstanceId: providerInstanceId,
474 targetRunId: null,
475 status: "pending",
476 resolution: null,
477 createdBy: "system",
478 error: null,
479 createdAt: now,
480 updatedAt: now,
481 consumedAt: null,
482 },
483 });
484 yield* createRun(child, "completed", { ordinal: 2 });
485 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
486 const taskId = NodeId.make("node:followup");
487 yield* createRun(child, "completed", { ordinal: 3, delegatedTaskId: taskId });
488 yield* createRun(child, "running", { ordinal: 4 });
489 const task = {
490 id: taskId,
491 threadId: parent,
492 runId: null,
493 parentNodeId: NodeId.make("node:parent"),
494 origin: "app_owned" as const,
495 createdBy: "agent" as const,
496 driver,
497 providerInstanceId,
498 providerThreadId: null,
499 childThreadId: child,
500 nativeTaskRef: null,
501 prompt: "Check the follow-up.",
502 title: null,
503 model: null,
504 status: "running" as const,
505 result: null,
506 startedAt: now,
507 completedAt: null,
508 updatedAt: now,
509 };
510 yield* projections.apply({
511 id: EventId.make("event:followup-task"),
512 type: "subagent.updated",
513 threadId: parent,
514 occurredAt: now,
515 payload: task,
516 });
517 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), [child]);
518 yield* projections.apply({
519 id: EventId.make("event:followup-settled"),
520 type: "subagent.updated",
521 threadId: parent,
522 occurredAt: now,
523 payload: { ...task, status: "completed", result: "Follow-up result.", completedAt: now },
524 });
525 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
526 }).pipe(Effect.provide(layer)),
527);
528
529it.effect("includes shared sessions and provider-owned background rosters in recovery", () =>
530 Effect.gen(function* () {
531 const projections = yield* ProjectionStore.ProjectionStoreV2;
532 const now = yield* DateTime.now;
533 const first = yield* createThread("shared-first");
534 const second = yield* createThread("shared-second", { archivedAt: now });
535 const providerSessionId = ProviderSessionId.make("session:recovery:shared");
536 for (const threadId of [first, second]) {
537 yield* projections.apply({
538 id: EventId.make(`event:${threadId}:session`),
539 type: "provider-session.attached",
540 threadId,
541 driver,
542 providerInstanceId,
543 occurredAt: now,
544 payload: {
545 id: providerSessionId,
546 driver,
547 providerInstanceId,
548 status: "ready",
549 cwd: "/workspace",
550 model: modelSelection.model,
551 capabilities: CodexProviderCapabilitiesV2,
552 createdAt: now,
553 updatedAt: now,
554 lastError: null,
555 },
556 });
557 }
558 const roster = yield* createThread("roster");
559 yield* projections.apply({
560 id: EventId.make("event:recovery:roster"),
561 type: "provider-thread.updated",
562 threadId: roster,
563 driver,
564 providerInstanceId,
565 occurredAt: now,
566 payload: {
567 id: ProviderThreadId.make("provider-thread:recovery:roster"),
568 appThreadId: roster,
569 ownerNodeId: null,
570 driver,
571 providerInstanceId,
572 providerSessionId: null,
573 nativeThreadRef: null,
574 nativeConversationHeadRef: null,
575 status: "idle",
576 firstRunOrdinal: null,
577 lastRunOrdinal: null,
578 handoffIds: [],
579 forkedFrom: null,
580 createdAt: now,
581 updatedAt: now,
582 pendingBackgroundTasks: [
583 { taskId: "background", description: "Still running", kind: "command" },
584 ],
585 },
586 });
587 const prepared = yield* createThread("prepared-continuation");
588 const preparedSessionId = ProviderSessionId.make("session:recovery:prepared");
589 const preparedProviderThreadId = ProviderThreadId.make("provider-thread:recovery:prepared");
590 yield* projections.apply({
591 id: EventId.make("event:recovery:prepared-session"),
592 type: "provider-session.attached",
593 threadId: prepared,
594 driver,
595 providerInstanceId,
596 occurredAt: now,
597 payload: {
598 id: preparedSessionId,
599 driver,
600 providerInstanceId,
601 status: "stopped",
602 cwd: "/workspace",
603 model: modelSelection.model,
604 capabilities: CodexProviderCapabilitiesV2,
605 createdAt: now,
606 updatedAt: now,
607 lastError: null,
608 },
609 });
610 yield* projections.apply({
611 id: EventId.make("event:recovery:prepared-thread"),
612 type: "provider-thread.updated",
613 threadId: prepared,
614 driver,
615 providerInstanceId,
616 occurredAt: now,
617 payload: {
618 id: preparedProviderThreadId,
619 appThreadId: prepared,
620 ownerNodeId: null,
621 driver,
622 providerInstanceId,
623 providerSessionId: preparedSessionId,
624 nativeThreadRef: { driver, nativeId: "native:prepared", strength: "strong" },
625 nativeConversationHeadRef: null,
626 status: "idle",
627 firstRunOrdinal: 1,
628 lastRunOrdinal: 1,
629 handoffIds: [],
630 forkedFrom: null,
631 createdAt: now,
632 updatedAt: now,
633 pendingBackgroundTasks: [],
634 },
635 });
636 const preparedRunId = yield* createRun(prepared, "starting", {
637 providerThreadId: preparedProviderThreadId,
638 restartContinuationOfRunId: RunId.make("run:recovery:source"),
639 });
640 assert.deepEqual(
641 new Set(yield* projections.getRecoveryThreadIds("runtime")),
642 new Set([first, second, roster, prepared]),
643 );
644 const preparedState = yield* projections.getRuntimeRecoveryProjection(prepared);
645 assert.deepEqual(
646 preparedState.providerSessions.map((session) => session.id),
647 [preparedSessionId],
648 );
649 assert.equal(restartContinuationRun(preparedState, yield* DateTime.now)?.id, preparedRunId);
650 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
651 const sql = yield* SqlClient.SqlClient;
652 yield* sql`
653 UPDATE orchestration_v2_projection_provider_sessions SET payload_json = '{}'
654 WHERE provider_session_id = ${providerSessionId}
655 `;
656 assert.deepEqual(
657 new Set(yield* projections.getUnreadableThreadIds()),
658 new Set([first, second]),
659 );
660 }).pipe(Effect.provide(layerTest)),
661);
662
663it.effect("reads the run that owns a background roster, not a queued or resumed one", () =>
664 Effect.gen(function* () {
665 const projections = yield* ProjectionStore.ProjectionStoreV2;
666 const now = yield* DateTime.now;
667 const withRoster = Effect.fn(function* (threadId: ThreadId) {
668 yield* projections.apply({
669 id: EventId.make(`event:${threadId}:roster`),
670 type: "provider-thread.updated",
671 threadId,
672 driver,
673 providerInstanceId,
674 occurredAt: now,
675 payload: {
676 id: ProviderThreadId.make(`provider-thread:${threadId}`),
677 appThreadId: threadId,
678 ownerNodeId: null,
679 driver,
680 providerInstanceId,
681 providerSessionId: null,
682 nativeThreadRef: null,
683 nativeConversationHeadRef: null,
684 status: "idle",
685 firstRunOrdinal: null,
686 lastRunOrdinal: null,
687 handoffIds: [],
688 forkedFrom: null,
689 createdAt: now,
690 updatedAt: now,
691 pendingBackgroundTasks: [
692 { taskId: "background", description: "Still running", kind: "command" },
693 ],
694 },
695 });
696 });
697 const runIds = (threadId: ThreadId) =>
698 projections
699 .getRuntimeRecoveryProjection(threadId)
700 .pipe(Effect.map((state) => state.runs.map((run) => run.id)));
701 const settled = yield* createThread("roster-before-queue");
702 const settledRun = yield* createRun(settled, "completed", {
703 providerThreadId: ProviderThreadId.make(`provider-thread:${settled}`),
704 });
705 const queuedRun = yield* createRun(settled, "queued", { ordinal: 2, completedAt: null });
706 yield* withRoster(settled);
707 assert.deepEqual(yield* runIds(settled), [settledRun, queuedRun]);
708 const resumed = yield* createThread("roster-after-resume");
709 const resumedRun = yield* createRun(resumed, "completed", {
710 providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`),
711 completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z"),
712 });
713 const continuationRun = yield* createRun(resumed, "completed", {
714 providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`),
715 ordinal: 2,
716 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
717 });
718 yield* withRoster(resumed);
719 assert.deepEqual(yield* runIds(resumed), [resumedRun, continuationRun]);
720 const quiet = yield* createThread("no-roster-before-queue");
721 yield* createRun(quiet, "completed");
722 const quietQueued = yield* createRun(quiet, "queued", { ordinal: 2, completedAt: null });
723 assert.deepEqual(yield* runIds(quiet), [quietQueued]);
724 }).pipe(Effect.provide(layerTest)),
725);
726
727it.effect("wakes the run whose subagent lost its shell, past a wake cut before it started", () =>
728 Effect.gen(function* () {
729 const projections = yield* ProjectionStore.ProjectionStoreV2;
730 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
731 const sql = yield* SqlClient.SqlClient;
732 const now = yield* DateTime.now;
733 const threadId = yield* createThread("subagent-shell");
734 const providerThreadId = ProviderThreadId.make(`provider-thread:${threadId}`);
735 const providerSessionId = ProviderSessionId.make(`session:${threadId}`);
736 yield* projections.apply({
737 id: EventId.make(`event:${threadId}:session`),
738 type: "provider-session.attached",
739 threadId,
740 driver,
741 providerInstanceId,
742 occurredAt: now,
743 payload: {
744 id: providerSessionId,
745 driver,
746 providerInstanceId,
747 status: "ready",
748 cwd: "/workspace",
749 model: modelSelection.model,
750 capabilities: CodexProviderCapabilitiesV2,
751 createdAt: now,
752 updatedAt: now,
753 lastError: null,
754 },
755 });
756 const settledRun = yield* createRun(threadId, "completed", { providerThreadId });
757 yield* createRun(threadId, "starting", {
758 ordinal: 2,
759 providerThreadId,
760 startedAt: null,
761 completedAt: null,
762 });
763 yield* projections.apply({
764 id: EventId.make(`event:${threadId}:roster`),
765 type: "provider-thread.updated",
766 threadId,
767 driver,
768 providerInstanceId,
769 occurredAt: now,
770 payload: {
771 id: providerThreadId,
772 appThreadId: threadId,
773 ownerNodeId: null,
774 driver,
775 providerInstanceId,
776 providerSessionId,
777 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
778 nativeConversationHeadRef: null,
779 status: "idle",
780 firstRunOrdinal: 1,
781 lastRunOrdinal: 2,
782 handoffIds: [],
783 forkedFrom: null,
784 createdAt: now,
785 updatedAt: now,
786 pendingBackgroundTasks: [
787 { taskId: "shell", description: "sleep 150", kind: "command", parentTaskId: "agent" },
788 ],
789 },
790 });
791
792 yield* recovery.reconcile("startup");
793
794 const effects = yield* sql<{ readonly effect_id: string }>`
795 SELECT effect_id FROM orchestration_v2_effect_outbox WHERE thread_id = ${threadId}
796 `;
797 assert.deepEqual(effects, [{ effect_id: `effect:restart-continuation:${settledRun}` }]);
798 const projection = yield* projections.getThreadProjection(threadId);
799 assert.deepEqual(projection.runs[0]?.restartCancelledBackgroundWork, [
800 { kind: "subagent", label: "sleep 150 (subagent agent)", id: "agent" },
801 ]);
802 }).pipe(Effect.provide(layerRecoveryTest)),
803);
804
805it.effect("wakes a settled run whose native subagent ran on its own provider thread", () =>
806 Effect.gen(function* () {
807 const projections = yield* ProjectionStore.ProjectionStoreV2;
808 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
809 const sql = yield* SqlClient.SqlClient;
810 const now = yield* DateTime.now;
811 const threadId = yield* createThread("native-subagent");
812 const parentProviderThreadId = ProviderThreadId.make(`provider-thread:${threadId}`);
813 const childProviderThreadId = ProviderThreadId.make(`provider-thread:${threadId}:child`);
814 const providerSessionId = ProviderSessionId.make(`session:${threadId}`);
815 const subagentId = NodeId.make(`node:${threadId}:subagent`);
816 // An older thread on the same Codex session is recovered first and stops it.
817 const sibling = yield* createThread("a-shared-session");
818 yield* createRun(sibling, "completed");
819 for (const boundThreadId of [sibling, threadId]) {
820 yield* projections.apply({
821 id: EventId.make(`event:${boundThreadId}:session`),
822 type: "provider-session.attached",
823 threadId: boundThreadId,
824 driver,
825 providerInstanceId,
826 occurredAt: now,
827 payload: {
828 id: providerSessionId,
829 driver,
830 providerInstanceId,
831 status: "ready",
832 cwd: "/workspace",
833 model: modelSelection.model,
834 capabilities: CodexProviderCapabilitiesV2,
835 createdAt: now,
836 updatedAt: now,
837 lastError: null,
838 },
839 });
840 }
841 const settledRun = yield* createRun(threadId, "completed", {
842 providerThreadId: parentProviderThreadId,
843 });
844 for (const [id, nativeId] of [
845 [parentProviderThreadId, "native-thread"],
846 [childProviderThreadId, "agent-thread"],
847 ] as const) {
848 yield* projections.apply({
849 id: EventId.make(`event:${id}`),
850 type: "provider-thread.updated",
851 threadId,
852 driver,
853 providerInstanceId,
854 occurredAt: now,
855 payload: {
856 id,
857 appThreadId:
858 id === parentProviderThreadId ? threadId : ThreadId.make(`${threadId}:child`),
859 ownerNodeId: null,
860 driver,
861 providerInstanceId,
862 providerSessionId,
863 nativeThreadRef: { driver, nativeId, strength: "strong" },
864 nativeConversationHeadRef: null,
865 status: "idle",
866 firstRunOrdinal: id === parentProviderThreadId ? 1 : null,
867 lastRunOrdinal: id === parentProviderThreadId ? 1 : null,
868 handoffIds: [],
869 forkedFrom: null,
870 createdAt: now,
871 updatedAt: now,
872 },
873 });
874 }
875 const subagent = {
876 threadId,
877 runId: settledRun,
878 origin: "provider_native",
879 driver,
880 providerInstanceId,
881 childThreadId: null,
882 prompt: "audit src",
883 status: "running",
884 result: null,
885 startedAt: now,
886 completedAt: null,
887 updatedAt: now,
888 } as const;
889 yield* projections.apply({
890 id: EventId.make(`event:${threadId}:subagent`),
891 type: "subagent.updated",
892 threadId,
893 occurredAt: now,
894 payload: {
895 ...subagent,
896 id: subagentId,
897 parentNodeId: NodeId.make(`node:${threadId}:root`),
898 createdBy: "agent",
899 providerThreadId: childProviderThreadId,
900 nativeTaskRef: { driver, nativeId: "call_1:agent-thread", strength: "strong" },
901 title: null,
902 model: null,
903 },
904 });
905 yield* projections.apply({
906 id: EventId.make(`event:${threadId}:subagent-item`),
907 type: "turn-item.updated",
908 threadId,
909 occurredAt: now,
910 payload: {
911 ...subagent,
912 id: TurnItemId.make(`item:${threadId}:subagent`),
913 nodeId: subagentId,
914 providerThreadId: childProviderThreadId,
915 providerTurnId: null,
916 nativeItemRef: { driver, nativeId: "call_1:agent-thread", strength: "strong" },
917 parentItemId: null,
918 ordinal: 1,
919 type: "subagent",
920 title: "audit",
921 subagentId,
922 },
923 });
924
925 yield* recovery.reconcile("startup");
926
927 const effects = yield* sql<{ readonly effect_id: string }>`
928 SELECT effect_id FROM orchestration_v2_effect_outbox WHERE thread_id = ${threadId}
929 `;
930 assert.deepEqual(effects, [{ effect_id: `effect:restart-continuation:${settledRun}` }]);
931 const projection = yield* projections.getThreadProjection(threadId);
932 assert.deepEqual(projection.runs[0]?.restartCancelledBackgroundWork, [
933 {
934 kind: "subagent",
935 label: "audit (id agent-thread)",
936 id: TurnItemId.make(`item:${threadId}:subagent`),
937 },
938 ]);
939 }).pipe(Effect.provide(layerRecoveryTest)),
940);
941
942it.effect("marks fork descendants unreadable when their source is missing or corrupt", () =>
943 Effect.gen(function* () {
944 const projections = yield* ProjectionStore.ProjectionStoreV2;
945 const sql = yield* SqlClient.SqlClient;
946 const source = yield* createThread("source");
947 const sourceRun = yield* createRun(source, "completed");
948 const fork = yield* createThread("fork", {
949 forkedFrom: { type: "run", threadId: source, runId: sourceRun },
950 });
951 const descendant = yield* createThread("descendant", {
952 forkedFrom: { type: "run", threadId: fork, runId: RunId.make("run:fork") },
953 });
954 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
955 yield* sql`
956 UPDATE orchestration_v2_projection_runs SET payload_json = '{}'
957 WHERE run_id = ${sourceRun}
958 `;
959 assert.deepEqual(
960 new Set(yield* projections.getUnreadableThreadIds()),
961 new Set([source, fork, descendant]),
962 );
963 yield* sql`DELETE FROM orchestration_v2_projection_threads WHERE thread_id = ${source}`;
964 assert.deepEqual(
965 new Set(yield* projections.getUnreadableThreadIds()),
966 new Set([fork, descendant]),
967 );
968 }).pipe(Effect.provide(layerTest)),
969);
970
971it.effect("startup ends the provider turn of a native child root it cancels", () =>
972 Effect.gen(function* () {
973 const projections = yield* ProjectionStore.ProjectionStoreV2;
974 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
975 const now = yield* DateTime.now;
976 const parentThreadId = yield* createThread("native-child-root-turn-parent");
977 const threadId = yield* createThread("native-child-root-turn");
978 const rootNodeId = NodeId.make(`node:${threadId}:thread-root`);
979 const providerThreadId = ProviderThreadId.make(`provider-thread:${threadId}`);
980 const providerTurnId = ProviderTurnId.make(`provider-turn:${threadId}`);
981 yield* projections.apply({
982 id: EventId.make(`event:${threadId}:root`),
983 type: "node.updated",
984 threadId,
985 nodeId: rootNodeId,
986 driver,
987 occurredAt: now,
988 payload: {
989 id: rootNodeId,
990 threadId,
991 runId: null,
992 parentNodeId: null,
993 rootNodeId,
994 kind: "root_turn",
995 status: "running",
996 countsForRun: false,
997 providerThreadId,
998 providerTurnId,
999 nativeItemRef: null,
1000 runtimeRequestId: null,
1001 checkpointScopeId: null,
1002 startedAt: now,
1003 completedAt: null,
1004 },
1005 });
1006 // A native subagent's turn belongs to no run attempt.
1007 yield* projections.apply({
1008 id: EventId.make(`event:${threadId}:provider-turn`),
1009 type: "provider-turn.updated",
1010 threadId,
1011 nodeId: rootNodeId,
1012 driver,
1013 occurredAt: now,
1014 payload: {
1015 id: providerTurnId,
1016 providerThreadId,
1017 nodeId: rootNodeId,
1018 runAttemptId: null,
1019 nativeTurnRef: null,
1020 ordinal: 1,
1021 status: "running",
1022 startedAt: now,
1023 completedAt: null,
1024 },
1025 });
1026
1027 const subagentId = NodeId.make(`node:${parentThreadId}:subagent`);
1028 yield* projections.apply({
1029 id: EventId.make(`event:${parentThreadId}:subagent`),
1030 type: "subagent.updated",
1031 threadId: parentThreadId,
1032 occurredAt: now,
1033 payload: {
1034 id: subagentId,
1035 threadId: parentThreadId,
1036 runId: null,
1037 parentNodeId: NodeId.make(`node:${parentThreadId}:root`),
1038 origin: "provider_native",
1039 createdBy: "agent",
1040 driver,
1041 providerInstanceId,
1042 providerThreadId,
1043 childThreadId: threadId,
1044 nativeTaskRef: null,
1045 title: null,
1046 model: null,
1047 prompt: "sleep 300",
1048 status: "running",
1049 result: null,
1050 startedAt: now,
1051 completedAt: null,
1052 updatedAt: now,
1053 },
1054 });
1055
1056 yield* recovery.reconcile("startup");
1057
1058 const projection = yield* projections.getThreadProjection(threadId);
1059 assert.deepEqual(
1060 {
1061 root: projection.nodes.find((node) => node.id === rootNodeId)?.status,
1062 providerTurn: projection.providerTurns.find((turn) => turn.id === providerTurnId)?.status,
1063 },
1064 { root: "cancelled", providerTurn: "cancelled" },
1065 "a root startup recovery cancelled left its provider turn running",
1066 );
1067 }).pipe(Effect.provide(layerRecoveryTest)),
1068);