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

ProjectionRecovery.test.ts

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