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

ProjectionRecovery.test.ts

1,065 lines37.3 KB

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("recovers only recorded follow-up results with SQLite projections", () =>
448 Effect.gen(function* () {
449 const projections = yield* ProjectionStore.ProjectionStoreV2;
450 const now = yield* DateTime.now;
451 const parent = yield* createThread("followup-parent");
452 const child = yield* createThread("followup-child", {
453 lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent },
454 forkedFrom: { type: "node", nodeId: NodeId.make("node:original") },
455 });
456 const originalRunId = yield* createRun(child, "completed");
457 yield* projections.apply({
458 id: EventId.make("event:original-result"),
459 type: "context-transfer.created",
460 threadId: parent,
461 occurredAt: now,
462 payload: {
463 id: ContextTransferId.make("transfer:original-result"),
464 type: "subagent_result",
465 sourceThreadId: child,
466 targetThreadId: parent,
467 sourcePoint: { threadId: child, runId: originalRunId },
468 basePoint: null,
469 sourceProviderInstanceId: providerInstanceId,
470 targetProviderInstanceId: providerInstanceId,
471 targetRunId: null,
472 status: "pending",
473 resolution: null,
474 createdBy: "system",
475 error: null,
476 createdAt: now,
477 updatedAt: now,
478 consumedAt: null,
479 },
480 });
481 yield* createRun(child, "completed", { ordinal: 2 });
482 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
483 const taskId = NodeId.make("node:followup");
484 yield* createRun(child, "completed", { ordinal: 3, delegatedTaskId: taskId });
485 yield* createRun(child, "running", { ordinal: 4 });
486 const task = {
487 id: taskId,
488 threadId: parent,
489 runId: null,
490 parentNodeId: NodeId.make("node:parent"),
491 origin: "app_owned" as const,
492 createdBy: "agent" as const,
493 driver,
494 providerInstanceId,
495 providerThreadId: null,
496 childThreadId: child,
497 nativeTaskRef: null,
498 prompt: "Check the follow-up.",
499 title: null,
500 model: null,
501 status: "running" as const,
502 result: null,
503 startedAt: now,
504 completedAt: null,
505 updatedAt: now,
506 };
507 yield* projections.apply({
508 id: EventId.make("event:followup-task"),
509 type: "subagent.updated",
510 threadId: parent,
511 occurredAt: now,
512 payload: task,
513 });
514 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), [child]);
515 yield* projections.apply({
516 id: EventId.make("event:followup-settled"),
517 type: "subagent.updated",
518 threadId: parent,
519 occurredAt: now,
520 payload: { ...task, status: "completed", result: "Follow-up result.", completedAt: now },
521 });
522 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
523 }).pipe(Effect.provide(layerTest)),
524);
525​
526it.effect("includes shared sessions and provider-owned background rosters in recovery", () =>
527 Effect.gen(function* () {
528 const projections = yield* ProjectionStore.ProjectionStoreV2;
529 const now = yield* DateTime.now;
530 const first = yield* createThread("shared-first");
531 const second = yield* createThread("shared-second", { archivedAt: now });
532 const providerSessionId = ProviderSessionId.make("session:recovery:shared");
533 for (const threadId of [first, second]) {
534 yield* projections.apply({
535 id: EventId.make(`event:${threadId}:session`),
536 type: "provider-session.attached",
537 threadId,
538 driver,
539 providerInstanceId,
540 occurredAt: now,
541 payload: {
542 id: providerSessionId,
543 driver,
544 providerInstanceId,
545 status: "ready",
546 cwd: "/workspace",
547 model: modelSelection.model,
548 capabilities: CodexProviderCapabilitiesV2,
549 createdAt: now,
550 updatedAt: now,
551 lastError: null,
552 },
553 });
554 }
555 const roster = yield* createThread("roster");
556 yield* projections.apply({
557 id: EventId.make("event:recovery:roster"),
558 type: "provider-thread.updated",
559 threadId: roster,
560 driver,
561 providerInstanceId,
562 occurredAt: now,
563 payload: {
564 id: ProviderThreadId.make("provider-thread:recovery:roster"),
565 appThreadId: roster,
566 ownerNodeId: null,
567 driver,
568 providerInstanceId,
569 providerSessionId: null,
570 nativeThreadRef: null,
571 nativeConversationHeadRef: null,
572 status: "idle",
573 firstRunOrdinal: null,
574 lastRunOrdinal: null,
575 handoffIds: [],
576 forkedFrom: null,
577 createdAt: now,
578 updatedAt: now,
579 pendingBackgroundTasks: [
580 { taskId: "background", description: "Still running", kind: "command" },
581 ],
582 },
583 });
584 const prepared = yield* createThread("prepared-continuation");
585 const preparedSessionId = ProviderSessionId.make("session:recovery:prepared");
586 const preparedProviderThreadId = ProviderThreadId.make("provider-thread:recovery:prepared");
587 yield* projections.apply({
588 id: EventId.make("event:recovery:prepared-session"),
589 type: "provider-session.attached",
590 threadId: prepared,
591 driver,
592 providerInstanceId,
593 occurredAt: now,
594 payload: {
595 id: preparedSessionId,
596 driver,
597 providerInstanceId,
598 status: "stopped",
599 cwd: "/workspace",
600 model: modelSelection.model,
601 capabilities: CodexProviderCapabilitiesV2,
602 createdAt: now,
603 updatedAt: now,
604 lastError: null,
605 },
606 });
607 yield* projections.apply({
608 id: EventId.make("event:recovery:prepared-thread"),
609 type: "provider-thread.updated",
610 threadId: prepared,
611 driver,
612 providerInstanceId,
613 occurredAt: now,
614 payload: {
615 id: preparedProviderThreadId,
616 appThreadId: prepared,
617 ownerNodeId: null,
618 driver,
619 providerInstanceId,
620 providerSessionId: preparedSessionId,
621 nativeThreadRef: { driver, nativeId: "native:prepared", strength: "strong" },
622 nativeConversationHeadRef: null,
623 status: "idle",
624 firstRunOrdinal: 1,
625 lastRunOrdinal: 1,
626 handoffIds: [],
627 forkedFrom: null,
628 createdAt: now,
629 updatedAt: now,
630 pendingBackgroundTasks: [],
631 },
632 });
633 const preparedRunId = yield* createRun(prepared, "starting", {
634 providerThreadId: preparedProviderThreadId,
635 restartContinuationOfRunId: RunId.make("run:recovery:source"),
636 });
637 assert.deepEqual(
638 new Set(yield* projections.getRecoveryThreadIds("runtime")),
639 new Set([first, second, roster, prepared]),
640 );
641 const preparedState = yield* projections.getRuntimeRecoveryProjection(prepared);
642 assert.deepEqual(
643 preparedState.providerSessions.map((session) => session.id),
644 [preparedSessionId],
645 );
646 assert.equal(restartContinuationRun(preparedState, yield* DateTime.now)?.id, preparedRunId);
647 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
648 const sql = yield* SqlClient.SqlClient;
649 yield* sql`
650 UPDATE orchestration_v2_projection_provider_sessions SET payload_json = '{}'
651 WHERE provider_session_id = ${providerSessionId}
652 `;
653 assert.deepEqual(
654 new Set(yield* projections.getUnreadableThreadIds()),
655 new Set([first, second]),
656 );
657 }).pipe(Effect.provide(layerTest)),
658);
659​
660it.effect("reads the run that owns a background roster, not a queued or resumed one", () =>
661 Effect.gen(function* () {
662 const projections = yield* ProjectionStore.ProjectionStoreV2;
663 const now = yield* DateTime.now;
664 const withRoster = Effect.fn(function* (threadId: ThreadId) {
665 yield* projections.apply({
666 id: EventId.make(`event:${threadId}:roster`),
667 type: "provider-thread.updated",
668 threadId,
669 driver,
670 providerInstanceId,
671 occurredAt: now,
672 payload: {
673 id: ProviderThreadId.make(`provider-thread:${threadId}`),
674 appThreadId: threadId,
675 ownerNodeId: null,
676 driver,
677 providerInstanceId,
678 providerSessionId: null,
679 nativeThreadRef: null,
680 nativeConversationHeadRef: null,
681 status: "idle",
682 firstRunOrdinal: null,
683 lastRunOrdinal: null,
684 handoffIds: [],
685 forkedFrom: null,
686 createdAt: now,
687 updatedAt: now,
688 pendingBackgroundTasks: [
689 { taskId: "background", description: "Still running", kind: "command" },
690 ],
691 },
692 });
693 });
694 const runIds = (threadId: ThreadId) =>
695 projections
696 .getRuntimeRecoveryProjection(threadId)
697 .pipe(Effect.map((state) => state.runs.map((run) => run.id)));
698 const settled = yield* createThread("roster-before-queue");
699 const settledRun = yield* createRun(settled, "completed", {
700 providerThreadId: ProviderThreadId.make(`provider-thread:${settled}`),
701 });
702 const queuedRun = yield* createRun(settled, "queued", { ordinal: 2, completedAt: null });
703 yield* withRoster(settled);
704 assert.deepEqual(yield* runIds(settled), [settledRun, queuedRun]);
705 const resumed = yield* createThread("roster-after-resume");
706 const resumedRun = yield* createRun(resumed, "completed", {
707 providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`),
708 completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z"),
709 });
710 const continuationRun = yield* createRun(resumed, "completed", {
711 providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`),
712 ordinal: 2,
713 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
714 });
715 yield* withRoster(resumed);
716 assert.deepEqual(yield* runIds(resumed), [resumedRun, continuationRun]);
717 const quiet = yield* createThread("no-roster-before-queue");
718 yield* createRun(quiet, "completed");
719 const quietQueued = yield* createRun(quiet, "queued", { ordinal: 2, completedAt: null });
720 assert.deepEqual(yield* runIds(quiet), [quietQueued]);
721 }).pipe(Effect.provide(layerTest)),
722);
723​
724it.effect("wakes the run whose subagent lost its shell, past a wake cut before it started", () =>
725 Effect.gen(function* () {
726 const projections = yield* ProjectionStore.ProjectionStoreV2;
727 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
728 const sql = yield* SqlClient.SqlClient;
729 const now = yield* DateTime.now;
730 const threadId = yield* createThread("subagent-shell");
731 const providerThreadId = ProviderThreadId.make(`provider-thread:${threadId}`);
732 const providerSessionId = ProviderSessionId.make(`session:${threadId}`);
733 yield* projections.apply({
734 id: EventId.make(`event:${threadId}:session`),
735 type: "provider-session.attached",
736 threadId,
737 driver,
738 providerInstanceId,
739 occurredAt: now,
740 payload: {
741 id: providerSessionId,
742 driver,
743 providerInstanceId,
744 status: "ready",
745 cwd: "/workspace",
746 model: modelSelection.model,
747 capabilities: CodexProviderCapabilitiesV2,
748 createdAt: now,
749 updatedAt: now,
750 lastError: null,
751 },
752 });
753 const settledRun = yield* createRun(threadId, "completed", { providerThreadId });
754 yield* createRun(threadId, "starting", {
755 ordinal: 2,
756 providerThreadId,
757 startedAt: null,
758 completedAt: null,
759 });
760 yield* projections.apply({
761 id: EventId.make(`event:${threadId}:roster`),
762 type: "provider-thread.updated",
763 threadId,
764 driver,
765 providerInstanceId,
766 occurredAt: now,
767 payload: {
768 id: providerThreadId,
769 appThreadId: threadId,
770 ownerNodeId: null,
771 driver,
772 providerInstanceId,
773 providerSessionId,
774 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
775 nativeConversationHeadRef: null,
776 status: "idle",
777 firstRunOrdinal: 1,
778 lastRunOrdinal: 2,
779 handoffIds: [],
780 forkedFrom: null,
781 createdAt: now,
782 updatedAt: now,
783 pendingBackgroundTasks: [
784 { taskId: "shell", description: "sleep 150", kind: "command", parentTaskId: "agent" },
785 ],
786 },
787 });
788​
789 yield* recovery.reconcile("startup");
790​
791 const effects = yield* sql<{ readonly effect_id: string }>`
792 SELECT effect_id FROM orchestration_v2_effect_outbox WHERE thread_id = ${threadId}
793 `;
794 assert.deepEqual(effects, [{ effect_id: `effect:restart-continuation:${settledRun}` }]);
795 const projection = yield* projections.getThreadProjection(threadId);
796 assert.deepEqual(projection.runs[0]?.restartCancelledBackgroundWork, [
797 { kind: "subagent", label: "sleep 150 (subagent agent)", id: "agent" },
798 ]);
799 }).pipe(Effect.provide(layerRecoveryTest)),
800);
801​
802it.effect("wakes a settled run whose native subagent ran on its own provider thread", () =>
803 Effect.gen(function* () {
804 const projections = yield* ProjectionStore.ProjectionStoreV2;
805 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
806 const sql = yield* SqlClient.SqlClient;
807 const now = yield* DateTime.now;
808 const threadId = yield* createThread("native-subagent");
809 const parentProviderThreadId = ProviderThreadId.make(`provider-thread:${threadId}`);
810 const childProviderThreadId = ProviderThreadId.make(`provider-thread:${threadId}:child`);
811 const providerSessionId = ProviderSessionId.make(`session:${threadId}`);
812 const subagentId = NodeId.make(`node:${threadId}:subagent`);
813 // An older thread on the same Codex session is recovered first and stops it.
814 const sibling = yield* createThread("a-shared-session");
815 yield* createRun(sibling, "completed");
816 for (const boundThreadId of [sibling, threadId]) {
817 yield* projections.apply({
818 id: EventId.make(`event:${boundThreadId}:session`),
819 type: "provider-session.attached",
820 threadId: boundThreadId,
821 driver,
822 providerInstanceId,
823 occurredAt: now,
824 payload: {
825 id: providerSessionId,
826 driver,
827 providerInstanceId,
828 status: "ready",
829 cwd: "/workspace",
830 model: modelSelection.model,
831 capabilities: CodexProviderCapabilitiesV2,
832 createdAt: now,
833 updatedAt: now,
834 lastError: null,
835 },
836 });
837 }
838 const settledRun = yield* createRun(threadId, "completed", {
839 providerThreadId: parentProviderThreadId,
840 });
841 for (const [id, nativeId] of [
842 [parentProviderThreadId, "native-thread"],
843 [childProviderThreadId, "agent-thread"],
844 ] as const) {
845 yield* projections.apply({
846 id: EventId.make(`event:${id}`),
847 type: "provider-thread.updated",
848 threadId,
849 driver,
850 providerInstanceId,
851 occurredAt: now,
852 payload: {
853 id,
854 appThreadId:
855 id === parentProviderThreadId ? threadId : ThreadId.make(`${threadId}:child`),
856 ownerNodeId: null,
857 driver,
858 providerInstanceId,
859 providerSessionId,
860 nativeThreadRef: { driver, nativeId, strength: "strong" },
861 nativeConversationHeadRef: null,
862 status: "idle",
863 firstRunOrdinal: id === parentProviderThreadId ? 1 : null,
864 lastRunOrdinal: id === parentProviderThreadId ? 1 : null,
865 handoffIds: [],
866 forkedFrom: null,
867 createdAt: now,
868 updatedAt: now,
869 },
870 });
871 }
872 const subagent = {
873 threadId,
874 runId: settledRun,
875 origin: "provider_native",
876 driver,
877 providerInstanceId,
878 childThreadId: null,
879 prompt: "audit src",
880 status: "running",
881 result: null,
882 startedAt: now,
883 completedAt: null,
884 updatedAt: now,
885 } as const;
886 yield* projections.apply({
887 id: EventId.make(`event:${threadId}:subagent`),
888 type: "subagent.updated",
889 threadId,
890 occurredAt: now,
891 payload: {
892 ...subagent,
893 id: subagentId,
894 parentNodeId: NodeId.make(`node:${threadId}:root`),
895 createdBy: "agent",
896 providerThreadId: childProviderThreadId,
897 nativeTaskRef: { driver, nativeId: "call_1:agent-thread", strength: "strong" },
898 title: null,
899 model: null,
900 },
901 });
902 yield* projections.apply({
903 id: EventId.make(`event:${threadId}:subagent-item`),
904 type: "turn-item.updated",
905 threadId,
906 occurredAt: now,
907 payload: {
908 ...subagent,
909 id: TurnItemId.make(`item:${threadId}:subagent`),
910 nodeId: subagentId,
911 providerThreadId: childProviderThreadId,
912 providerTurnId: null,
913 nativeItemRef: { driver, nativeId: "call_1:agent-thread", strength: "strong" },
914 parentItemId: null,
915 ordinal: 1,
916 type: "subagent",
917 title: "audit",
918 subagentId,
919 },
920 });
921​
922 yield* recovery.reconcile("startup");
923​
924 const effects = yield* sql<{ readonly effect_id: string }>`
925 SELECT effect_id FROM orchestration_v2_effect_outbox WHERE thread_id = ${threadId}
926 `;
927 assert.deepEqual(effects, [{ effect_id: `effect:restart-continuation:${settledRun}` }]);
928 const projection = yield* projections.getThreadProjection(threadId);
929 assert.deepEqual(projection.runs[0]?.restartCancelledBackgroundWork, [
930 {
931 kind: "subagent",
932 label: "audit (id agent-thread)",
933 id: TurnItemId.make(`item:${threadId}:subagent`),
934 },
935 ]);
936 }).pipe(Effect.provide(layerRecoveryTest)),
937);
938​
939it.effect("marks fork descendants unreadable when their source is missing or corrupt", () =>
940 Effect.gen(function* () {
941 const projections = yield* ProjectionStore.ProjectionStoreV2;
942 const sql = yield* SqlClient.SqlClient;
943 const source = yield* createThread("source");
944 const sourceRun = yield* createRun(source, "completed");
945 const fork = yield* createThread("fork", {
946 forkedFrom: { type: "run", threadId: source, runId: sourceRun },
947 });
948 const descendant = yield* createThread("descendant", {
949 forkedFrom: { type: "run", threadId: fork, runId: RunId.make("run:fork") },
950 });
951 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
952 yield* sql`
953 UPDATE orchestration_v2_projection_runs SET payload_json = '{}'
954 WHERE run_id = ${sourceRun}
955 `;
956 assert.deepEqual(
957 new Set(yield* projections.getUnreadableThreadIds()),
958 new Set([source, fork, descendant]),
959 );
960 yield* sql`DELETE FROM orchestration_v2_projection_threads WHERE thread_id = ${source}`;
961 assert.deepEqual(
962 new Set(yield* projections.getUnreadableThreadIds()),
963 new Set([fork, descendant]),
964 );
965 }).pipe(Effect.provide(layerTest)),
966);
967​
968it.effect("startup ends the provider turn of a native child root it cancels", () =>
969 Effect.gen(function* () {
970 const projections = yield* ProjectionStore.ProjectionStoreV2;
971 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
972 const now = yield* DateTime.now;
973 const parentThreadId = yield* createThread("native-child-root-turn-parent");
974 const threadId = yield* createThread("native-child-root-turn");
975 const rootNodeId = NodeId.make(`node:${threadId}:thread-root`);
976 const providerThreadId = ProviderThreadId.make(`provider-thread:${threadId}`);
977 const providerTurnId = ProviderTurnId.make(`provider-turn:${threadId}`);
978 yield* projections.apply({
979 id: EventId.make(`event:${threadId}:root`),
980 type: "node.updated",
981 threadId,
982 nodeId: rootNodeId,
983 driver,
984 occurredAt: now,
985 payload: {
986 id: rootNodeId,
987 threadId,
988 runId: null,
989 parentNodeId: null,
990 rootNodeId,
991 kind: "root_turn",
992 status: "running",
993 countsForRun: false,
994 providerThreadId,
995 providerTurnId,
996 nativeItemRef: null,
997 runtimeRequestId: null,
998 checkpointScopeId: null,
999 startedAt: now,
1000 completedAt: null,
1001 },
1002 });
1003 // A native subagent's turn belongs to no run attempt.
1004 yield* projections.apply({
1005 id: EventId.make(`event:${threadId}:provider-turn`),
1006 type: "provider-turn.updated",
1007 threadId,
1008 nodeId: rootNodeId,
1009 driver,
1010 occurredAt: now,
1011 payload: {
1012 id: providerTurnId,
1013 providerThreadId,
1014 nodeId: rootNodeId,
1015 runAttemptId: null,
1016 nativeTurnRef: null,
1017 ordinal: 1,
1018 status: "running",
1019 startedAt: now,
1020 completedAt: null,
1021 },
1022 });
1023​
1024 const subagentId = NodeId.make(`node:${parentThreadId}:subagent`);
1025 yield* projections.apply({
1026 id: EventId.make(`event:${parentThreadId}:subagent`),
1027 type: "subagent.updated",
1028 threadId: parentThreadId,
1029 occurredAt: now,
1030 payload: {
1031 id: subagentId,
1032 threadId: parentThreadId,
1033 runId: null,
1034 parentNodeId: NodeId.make(`node:${parentThreadId}:root`),
1035 origin: "provider_native",
1036 createdBy: "agent",
1037 driver,
1038 providerInstanceId,
1039 providerThreadId,
1040 childThreadId: threadId,
1041 nativeTaskRef: null,
1042 title: null,
1043 model: null,
1044 prompt: "sleep 300",
1045 status: "running",
1046 result: null,
1047 startedAt: now,
1048 completedAt: null,
1049 updatedAt: now,
1050 },
1051 });
1052​
1053 yield* recovery.reconcile("startup");
1054​
1055 const projection = yield* projections.getThreadProjection(threadId);
1056 assert.deepEqual(
1058 root: projection.nodes.find((node) => node.id === rootNodeId)?.status,
1059 providerTurn: projection.providerTurns.find((turn) => turn.id === providerTurnId)?.status,
1060 },
1061 { root: "cancelled", providerTurn: "cancelled" },
1062 "a root startup recovery cancelled left its provider turn running",
1063 );
1064 }).pipe(Effect.provide(layerRecoveryTest)),