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