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

ProjectionRecovery.test.ts

753 lines26.9 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 RunId,
16 RuntimeRequestId,
17 ThreadId,
18 TurnItemId,
19} from "@t3tools/contracts";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as SqlClient from "effect/sql/SqlClient";
24​
25import * as SqlitePersistence from "../persistence/Sqlite.ts";
26import * as ServerSettings from "../serverSettings.ts";
27import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
28import * as EffectOutbox from "./EffectOutbox.ts";
29import * as ProjectionStore from "./ProjectionStore.ts";
30import * as EventSink from "./EventSink.ts";
31import * as EventStore from "./EventStore.ts";
32import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
33import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
34import { restartContinuationRun } from "./RestartContinuation.ts";
35​
36const layerTest = Layer.mergeAll(ProjectionStore.layer, EffectOutbox.layer).pipe(
37 Layer.provideMerge(SqlitePersistence.layerMemory),
38);
39const layerRecoveryTest = ProviderRuntimeRecovery.layer.pipe(
40 Layer.provideMerge(
41 EventSink.layer.pipe(
42 Layer.provideMerge(
43 Layer.mergeAll(
44 EventStore.layer,
45 ProjectionStore.layer,
46 EffectOutbox.layer,
47 IdAllocator.layer,
48 ).pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
49 ),
50 ),
51 ),
52 Layer.provide(ServerSettings.layerTest()),
53);
54const providerInstanceId = ProviderInstanceId.make("codex");
55const modelSelection = { instanceId: providerInstanceId, model: "gpt-5.4" };
56const driver = ProviderDriverKind.make("codex");
57​
58const createThread = Effect.fn(function* (
59 name: string,
60 overrides: Partial<OrchestrationV2AppThread> = {},
61) {
62 const projections = yield* ProjectionStore.ProjectionStoreV2;
63 const now = yield* DateTime.now;
64 const threadId = ThreadId.make(`thread:recovery:${name}`);
65 const thread: OrchestrationV2AppThread = {
66 createdBy: "user",
67 creationSource: "web",
68 id: threadId,
69 projectId: ProjectId.make("project:recovery"),
70 title: name,
71 providerInstanceId,
72 modelSelection,
73 runtimeMode: "full-access",
74 interactionMode: "default",
75 branch: null,
76 worktreePath: null,
77 activeProviderThreadId: null,
78 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
79 forkedFrom: null,
80 createdAt: now,
81 updatedAt: now,
82 archivedAt: null,
83 settledOverride: null,
84 settledAt: null,
85 lastVisitedAt: null,
86 deletedAt: null,
87 ...overrides,
88 };
89 yield* projections.apply({
90 id: EventId.make(`event:${threadId}:created`),
91 type: "thread.created",
92 threadId,
93 occurredAt: now,
94 payload: thread,
95 });
96 return threadId;
97});
98​
99const createRun = Effect.fn(function* (
100 threadId: ThreadId,
101 status: OrchestrationV2Run["status"],
102 overrides: Partial<OrchestrationV2Run> = {},
103) {
104 const projections = yield* ProjectionStore.ProjectionStoreV2;
105 const now = yield* DateTime.now;
106 const ordinal = overrides.ordinal ?? 1;
107 const runId = RunId.make(`run:${threadId}:${ordinal}`);
108 yield* projections.apply({
109 id: EventId.make(`event:${runId}:created`),
110 type: "run.created",
111 threadId,
112 runId,
113 occurredAt: now,
114 payload: {
115 id: runId,
116 threadId,
117 ordinal,
118 providerInstanceId,
119 modelSelection,
120 providerThreadId: null,
121 userMessageId: MessageId.make(`message:${runId}`),
122 rootNodeId: null,
123 activeAttemptId: null,
124 status,
125 requestedAt: now,
126 startedAt: now,
127 completedAt: status === "completed" ? now : null,
128 checkpointId: null,
129 contextHandoffId: null,
130 ...overrides,
131 },
132 });
133 return runId;
134});
135​
136it.effect.each(["startup", "shutdown"] as const)(
137 "%s cancels queued buffered wakes and holds durable messages",
138 (trigger) =>
139 Effect.gen(function* () {
140 const projections = yield* ProjectionStore.ProjectionStoreV2;
141 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
142 const now = yield* DateTime.now;
143 const bufferedThreads = [] as ThreadId[];
144 const durableThreads = [] as ThreadId[];
145 for (const kind of ["buffered", "user", "notification", "delegated"] as const) {
146 const threadId = yield* createThread(`wake:${trigger}:${kind}`);
147 const buffered = kind === "buffered";
148 (buffered ? bufferedThreads : durableThreads).push(threadId);
149 const messageId = MessageId.make(`message:${threadId}`);
150 const runId = yield* createRun(threadId, "queued", {
151 userMessageId: messageId,
152 startedAt: null,
153 queuePosition: 1,
154 });
155 yield* createRun(threadId, "completed", { ordinal: 2 });
156 yield* projections.apply({
157 id: EventId.make(`message:${threadId}`),
158 type: "message.updated",
159 threadId,
160 runId,
161 occurredAt: now,
162 payload: {
163 id: messageId,
164 threadId,
165 runId,
166 nodeId: null,
167 role: "user",
168 text: "Queued work",
169 attachments: [],
170 streaming: false,
171 createdAt: now,
172 updatedAt: now,
173 createdBy: kind === "user" ? "user" : "agent",
174 creationSource: buffered ? "provider" : "server",
175 ...(kind === "user" || kind === "delegated"
176 ? {}
177 : {
178 notification: {
179 source: { kind: "background_task" as const },
180 outcome: "updated" as const,
181 summary: "Background activity updated",
182 },
183 }),
184 ...(kind === "delegated"
185 ? { delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [] } }
186 : {}),
187 },
188 });
189 }
190 assert.deepEqual(
191 new Set(yield* projections.getRecoveryThreadIds("runtime")),
192 new Set([...bufferedThreads, ...durableThreads]),
193 );
194 const summary = yield* recovery.reconcile(trigger);
195 assert.equal(summary.terminalizedRuns, 1);
196 for (const threadId of bufferedThreads) {
197 const projection = yield* projections.getThreadProjection(threadId);
198 assert.equal(projection.runs[0]?.status, "cancelled");
199 assert.isNotNull(projection.runs[0]?.completedAt);
200 assert.isNull(projection.runs[0]?.queuePosition);
201 assert.equal(projection.runs[1]?.status, "completed");
202 }
203 for (const threadId of durableThreads) {
204 const projection = yield* projections.getThreadProjection(threadId);
205 assert.equal(projection.runs[0]?.status, "queued");
206 assert.isTrue(projection.runs[0]?.queueHeld);
207 }
208 assert.deepEqual(yield* projections.getRecoveryThreadIds("runtime"), []);
209 }).pipe(Effect.provide(layerRecoveryTest)),
210);
211​
212it.effect("stops a session its thread detached, which kept its live status", () =>
213 Effect.gen(function* () {
214 const projections = yield* ProjectionStore.ProjectionStoreV2;
215 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
216 const now = yield* DateTime.now;
217 const threadId = yield* createThread("detached-session");
218 const providerSessionId = ProviderSessionId.make("session:recovery:detached");
219 yield* projections.apply({
220 id: EventId.make("event:recovery:detached-session:attached"),
221 type: "provider-session.attached",
222 threadId,
223 driver,
224 providerInstanceId,
225 occurredAt: now,
226 payload: {
227 id: providerSessionId,
228 driver,
229 providerInstanceId,
230 status: "ready",
231 cwd: "/workspace",
232 model: modelSelection.model,
233 capabilities: CodexProviderCapabilitiesV2,
234 createdAt: now,
235 updatedAt: now,
236 lastError: null,
237 },
238 });
239 yield* projections.apply({
240 id: EventId.make("event:recovery:detached-session:detached"),
241 type: "provider-session.detached",
242 threadId,
243 driver,
244 providerInstanceId,
245 occurredAt: now,
246 payload: { providerSessionId, detachedAt: now, reason: "Thread settled." },
247 });
248 assert.deepEqual(yield* projections.getRecoveryThreadIds("runtime"), [threadId]);
249​
250 const summary = yield* recovery.reconcile("startup");
251​
252 assert.equal(summary.stoppedSessions, 1);
253 const sql = yield* SqlClient.SqlClient;
254 const rows = yield* sql<{ readonly status: string }>`
255 SELECT status FROM orchestration_v2_projection_provider_sessions
256 WHERE provider_session_id = ${providerSessionId}
257 `;
258 assert.deepEqual(rows, [{ status: "stopped" }]);
259 assert.deepEqual(yield* projections.getRecoveryThreadIds("runtime"), []);
260 }).pipe(Effect.provide(layerRecoveryTest)),
261);
262​
263it.effect("selects unfinished recovery work without reading settled thread histories", () =>
264 Effect.gen(function* () {
265 const projections = yield* ProjectionStore.ProjectionStoreV2;
266 const outbox = yield* EffectOutbox.EffectOutboxV2;
267 const sql = yield* SqlClient.SqlClient;
268 const now = yield* DateTime.now;
269 for (let index = 0; index < 600; index += 1) {
270 yield* createRun(yield* createThread(`settled-${index}`), "completed");
271 }
272 const queued = yield* createThread("queued");
273 const archived = yield* createThread("archived", { archivedAt: now });
274 const deleted = yield* createThread("deleted", { deletedAt: now });
275 const blocked = yield* createThread("blocked");
276 yield* createRun(queued, "completed");
277 for (const threadId of [queued, archived, deleted, blocked]) {
278 yield* createRun(threadId, "queued", threadId === queued ? { ordinal: 2 } : {});
279 }
280 yield* createRun(blocked, "waiting", { ordinal: 2 });
281 const background = yield* createThread("background");
282 yield* createRun(background, "completed");
283 yield* projections.apply({
284 id: EventId.make("event:recovery:background"),
285 type: "turn-item.updated",
286 threadId: background,
287 occurredAt: now,
288 payload: {
289 id: TurnItemId.make("item:recovery:background"),
290 threadId: background,
291 runId: null,
292 nodeId: null,
293 providerThreadId: null,
294 providerTurnId: null,
295 nativeItemRef: null,
296 parentItemId: null,
297 ordinal: 1,
298 type: "dynamic_tool",
299 status: "waiting",
300 title: null,
301 startedAt: now,
302 completedAt: null,
303 updatedAt: now,
304 toolName: "background",
305 input: null,
306 output: null,
307 },
308 });
309 const outboxOnly = yield* createThread("outbox-only");
310 yield* outbox.enqueue([
311 {
312 id: "effect:recovery:outbox-only",
313 commandId: CommandId.make("command:recovery:outbox-only"),
314 threadId: outboxOnly,
315 request: { type: "provider-turn.start", runId: RunId.make("run:outbox-only") },
316 },
317 ]);
318 const requestOnly = yield* createThread("request-only");
319 yield* projections.apply({
320 id: EventId.make("event:recovery:request-only"),
321 type: "runtime-request.updated",
322 threadId: requestOnly,
323 occurredAt: now,
324 payload: {
325 id: RuntimeRequestId.make("request:recovery:pending"),
326 nodeId: NodeId.make("node:recovery:request"),
327 providerTurnId: null,
328 nativeRequestRef: null,
329 kind: "user_input",
330 status: "pending",
331 responseCapability: { type: "not_resumable", reason: "Process stopped" },
332 createdAt: now,
333 resolvedAt: null,
334 },
335 });
336 const delivery = yield* createThread("delivery", { archivedAt: now });
337 yield* createRun(delivery, "completed", {
338 delegatedCompletion: {
339 disposition: "open",
340 nextGeneration: 2,
341 delivery: { generation: 1, messageId: MessageId.make("message:delivery"), taskIds: [] },
342 },
343 });
344​
345 yield* sql`
346 UPDATE orchestration_v2_projection_runs SET payload_json = '{broken'
347 WHERE thread_id = ${ThreadId.make("thread:recovery:settled-599")}
348 `;
349 yield* sql`
350 UPDATE orchestration_v2_projection_runs SET payload_json = '{broken'
351 WHERE thread_id = ${queued} AND ordinal = 1
352 `;
353 assert.deepEqual(yield* projections.getRecoveryThreadIds("queued-runs"), [queued]);
354 assert.deepEqual(
355 new Set(yield* projections.getRecoveryThreadIds("runtime")),
356 new Set([queued, archived, blocked, background, outboxOnly, requestOnly]),
357 );
358 assert.deepEqual(yield* projections.getRecoveryThreadIds("delegated-completions"), [delivery]);
359 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
360 const recoveryState = yield* projections.getRuntimeRecoveryProjection(queued);
361 assert.deepEqual(
362 recoveryState.runs.map((run) => run.id),
363 [RunId.make(`run:${queued}:2`)],
364 );
365 assert.deepEqual(yield* projections.getUnreadableThreadIds(), [
366 queued,
367 ThreadId.make("thread:recovery:settled-599"),
368 ]);
369 }).pipe(Effect.provide(layerTest)),
370);
371​
372it.effect("recovers terminal subagent results until their cross-thread transfer exists", () =>
373 Effect.gen(function* () {
374 const projections = yield* ProjectionStore.ProjectionStoreV2;
375 const sql = yield* SqlClient.SqlClient;
376 const now = yield* DateTime.now;
377 const parent = yield* createThread("subagent-parent");
378 const children: Array<ThreadId> = [];
379 for (const name of ["terminal", "archived", "deleted", "running", "held", "queued"]) {
380 const child = yield* createThread(`subagent-${name}`, {
381 lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent },
382 forkedFrom: { type: "node", nodeId: NodeId.make(`node:${name}`) },
383 archivedAt: name === "archived" ? now : null,
384 deletedAt: name === "deleted" ? now : null,
385 });
386 yield* createRun(child, name === "running" ? "running" : "completed");
387 if (name === "held" || name === "queued") {
388 yield* createRun(child, "queued", {
389 ordinal: 2,
390 startedAt: null,
391 ...(name === "held" ? { queueHeld: true } : {}),
392 });
393 }
394 children.push(child);
395 }
396 const terminalChildren = new Set([children[0]!, children[1]!, children[4]!]);
397 assert.deepEqual(
398 new Set(yield* projections.getRecoveryThreadIds("subagent-results")),
399 terminalChildren,
400 );
401​
402 const completed = children[0]!;
403 const transferId = ContextTransferId.make("transfer:recovery:subagent-result");
404 yield* projections.apply({
405 id: EventId.make("event:recovery:subagent-result"),
406 type: "context-transfer.created",
407 threadId: parent,
408 occurredAt: now,
409 payload: {
410 id: transferId,
411 type: "subagent_result",
412 sourceThreadId: completed,
413 targetThreadId: parent,
414 sourcePoint: { threadId: completed },
415 basePoint: null,
416 sourceProviderInstanceId: providerInstanceId,
417 targetProviderInstanceId: providerInstanceId,
418 targetRunId: null,
419 status: "pending",
420 resolution: null,
421 createdBy: "system",
422 error: null,
423 createdAt: now,
424 updatedAt: now,
425 consumedAt: null,
426 },
427 });
428 const archivedChild = children[1];
429 assert.isDefined(archivedChild);
430 assert.deepEqual(
431 new Set(yield* projections.getRecoveryThreadIds("subagent-results")),
432 new Set([archivedChild, children[4]!]),
433 );
434 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
435 yield* sql`
436 UPDATE orchestration_v2_projection_context_transfers SET payload_json = '{}'
437 WHERE context_transfer_id = ${transferId}
438 `;
439 assert.deepEqual(
440 new Set(yield* projections.getUnreadableThreadIds()),
441 new Set([parent, completed]),
442 );
443 }).pipe(Effect.provide(layerTest)),
444);
445​
446it.effect.each([
447 { name: "SQLite", layer: layerTest },
448 { name: "memory", layer: ProjectionStore.layerMemory },
449])("recovers only recorded follow-up results with $name projections", ({ layer }) =>
450 Effect.gen(function* () {
451 const projections = yield* ProjectionStore.ProjectionStoreV2;
452 const now = yield* DateTime.now;
453 const parent = yield* createThread("followup-parent");
454 const child = yield* createThread("followup-child", {
455 lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent },
456 forkedFrom: { type: "node", nodeId: NodeId.make("node:original") },
457 });
458 const originalRunId = yield* createRun(child, "completed");
459 yield* projections.apply({
460 id: EventId.make("event:original-result"),
461 type: "context-transfer.created",
462 threadId: parent,
463 occurredAt: now,
464 payload: {
465 id: ContextTransferId.make("transfer:original-result"),
466 type: "subagent_result",
467 sourceThreadId: child,
468 targetThreadId: parent,
469 sourcePoint: { threadId: child, runId: originalRunId },
470 basePoint: null,
471 sourceProviderInstanceId: providerInstanceId,
472 targetProviderInstanceId: providerInstanceId,
473 targetRunId: null,
474 status: "pending",
475 resolution: null,
476 createdBy: "system",
477 error: null,
478 createdAt: now,
479 updatedAt: now,
480 consumedAt: null,
481 },
482 });
483 yield* createRun(child, "completed", { ordinal: 2 });
484 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
485 const taskId = NodeId.make("node:followup");
486 yield* createRun(child, "completed", { ordinal: 3, delegatedTaskId: taskId });
487 yield* createRun(child, "running", { ordinal: 4 });
488 const task = {
489 id: taskId,
490 threadId: parent,
491 runId: null,
492 parentNodeId: NodeId.make("node:parent"),
493 origin: "app_owned" as const,
494 createdBy: "agent" as const,
495 driver,
496 providerInstanceId,
497 providerThreadId: null,
498 childThreadId: child,
499 nativeTaskRef: null,
500 prompt: "Check the follow-up.",
501 title: null,
502 model: null,
503 status: "running" as const,
504 result: null,
505 startedAt: now,
506 completedAt: null,
507 updatedAt: now,
508 };
509 yield* projections.apply({
510 id: EventId.make("event:followup-task"),
511 type: "subagent.updated",
512 threadId: parent,
513 occurredAt: now,
514 payload: task,
515 });
516 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), [child]);
517 yield* projections.apply({
518 id: EventId.make("event:followup-settled"),
519 type: "subagent.updated",
520 threadId: parent,
521 occurredAt: now,
522 payload: { ...task, status: "completed", result: "Follow-up result.", completedAt: now },
523 });
524 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
525 }).pipe(Effect.provide(layer)),
526);
527​
528it.effect("includes shared sessions and provider-owned background rosters in recovery", () =>
529 Effect.gen(function* () {
530 const projections = yield* ProjectionStore.ProjectionStoreV2;
531 const now = yield* DateTime.now;
532 const first = yield* createThread("shared-first");
533 const second = yield* createThread("shared-second", { archivedAt: now });
534 const providerSessionId = ProviderSessionId.make("session:recovery:shared");
535 for (const threadId of [first, second]) {
536 yield* projections.apply({
537 id: EventId.make(`event:${threadId}:session`),
538 type: "provider-session.attached",
539 threadId,
540 driver,
541 providerInstanceId,
542 occurredAt: now,
543 payload: {
544 id: providerSessionId,
545 driver,
546 providerInstanceId,
547 status: "ready",
548 cwd: "/workspace",
549 model: modelSelection.model,
550 capabilities: CodexProviderCapabilitiesV2,
551 createdAt: now,
552 updatedAt: now,
553 lastError: null,
554 },
555 });
556 }
557 const roster = yield* createThread("roster");
558 yield* projections.apply({
559 id: EventId.make("event:recovery:roster"),
560 type: "provider-thread.updated",
561 threadId: roster,
562 driver,
563 providerInstanceId,
564 occurredAt: now,
565 payload: {
566 id: ProviderThreadId.make("provider-thread:recovery:roster"),
567 appThreadId: roster,
568 ownerNodeId: null,
569 driver,
570 providerInstanceId,
571 providerSessionId: null,
572 nativeThreadRef: null,
573 nativeConversationHeadRef: null,
574 status: "idle",
575 firstRunOrdinal: null,
576 lastRunOrdinal: null,
577 handoffIds: [],
578 forkedFrom: null,
579 createdAt: now,
580 updatedAt: now,
581 pendingBackgroundTasks: [
582 { taskId: "background", description: "Still running", kind: "command" },
583 ],
584 },
585 });
586 const prepared = yield* createThread("prepared-continuation");
587 const preparedSessionId = ProviderSessionId.make("session:recovery:prepared");
588 const preparedProviderThreadId = ProviderThreadId.make("provider-thread:recovery:prepared");
589 yield* projections.apply({
590 id: EventId.make("event:recovery:prepared-session"),
591 type: "provider-session.attached",
592 threadId: prepared,
593 driver,
594 providerInstanceId,
595 occurredAt: now,
596 payload: {
597 id: preparedSessionId,
598 driver,
599 providerInstanceId,
600 status: "stopped",
601 cwd: "/workspace",
602 model: modelSelection.model,
603 capabilities: CodexProviderCapabilitiesV2,
604 createdAt: now,
605 updatedAt: now,
606 lastError: null,
607 },
608 });
609 yield* projections.apply({
610 id: EventId.make("event:recovery:prepared-thread"),
611 type: "provider-thread.updated",
612 threadId: prepared,
613 driver,
614 providerInstanceId,
615 occurredAt: now,
616 payload: {
617 id: preparedProviderThreadId,
618 appThreadId: prepared,
619 ownerNodeId: null,
620 driver,
621 providerInstanceId,
622 providerSessionId: preparedSessionId,
623 nativeThreadRef: { driver, nativeId: "native:prepared", strength: "strong" },
624 nativeConversationHeadRef: null,
625 status: "idle",
626 firstRunOrdinal: 1,
627 lastRunOrdinal: 1,
628 handoffIds: [],
629 forkedFrom: null,
630 createdAt: now,
631 updatedAt: now,
632 pendingBackgroundTasks: [],
633 },
634 });
635 const preparedRunId = yield* createRun(prepared, "starting", {
636 providerThreadId: preparedProviderThreadId,
637 restartContinuationOfRunId: RunId.make("run:recovery:source"),
638 });
639 assert.deepEqual(
640 new Set(yield* projections.getRecoveryThreadIds("runtime")),
641 new Set([first, second, roster, prepared]),
642 );
643 const preparedState = yield* projections.getRuntimeRecoveryProjection(prepared);
644 assert.deepEqual(
645 preparedState.providerSessions.map((session) => session.id),
646 [preparedSessionId],
647 );
648 assert.equal(restartContinuationRun(preparedState, yield* DateTime.now)?.id, preparedRunId);
649 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
650 const sql = yield* SqlClient.SqlClient;
651 yield* sql`
652 UPDATE orchestration_v2_projection_provider_sessions SET payload_json = '{}'
653 WHERE provider_session_id = ${providerSessionId}
654 `;
655 assert.deepEqual(
656 new Set(yield* projections.getUnreadableThreadIds()),
657 new Set([first, second]),
658 );
659 }).pipe(Effect.provide(layerTest)),
660);
661​
662it.effect("reads the run that owns a background roster, not a queued or resumed one", () =>
663 Effect.gen(function* () {
664 const projections = yield* ProjectionStore.ProjectionStoreV2;
665 const now = yield* DateTime.now;
666 const withRoster = Effect.fn(function* (threadId: ThreadId) {
667 yield* projections.apply({
668 id: EventId.make(`event:${threadId}:roster`),
669 type: "provider-thread.updated",
670 threadId,
671 driver,
672 providerInstanceId,
673 occurredAt: now,
674 payload: {
675 id: ProviderThreadId.make(`provider-thread:${threadId}`),
676 appThreadId: threadId,
677 ownerNodeId: null,
678 driver,
679 providerInstanceId,
680 providerSessionId: null,
681 nativeThreadRef: null,
682 nativeConversationHeadRef: null,
683 status: "idle",
684 firstRunOrdinal: null,
685 lastRunOrdinal: null,
686 handoffIds: [],
687 forkedFrom: null,
688 createdAt: now,
689 updatedAt: now,
690 pendingBackgroundTasks: [
691 { taskId: "background", description: "Still running", kind: "command" },
692 ],
693 },
694 });
695 });
696 const runIds = (threadId: ThreadId) =>
697 projections
698 .getRuntimeRecoveryProjection(threadId)
699 .pipe(Effect.map((state) => state.runs.map((run) => run.id)));
700 const settled = yield* createThread("roster-before-queue");
701 const settledRun = yield* createRun(settled, "completed", {
702 providerThreadId: ProviderThreadId.make(`provider-thread:${settled}`),
703 });
704 const queuedRun = yield* createRun(settled, "queued", { ordinal: 2, completedAt: null });
705 yield* withRoster(settled);
706 assert.deepEqual(yield* runIds(settled), [settledRun, queuedRun]);
707 const resumed = yield* createThread("roster-after-resume");
708 const resumedRun = yield* createRun(resumed, "completed", {
709 providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`),
710 completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z"),
711 });
712 const continuationRun = yield* createRun(resumed, "completed", {
713 providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`),
714 ordinal: 2,
715 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
716 });
717 yield* withRoster(resumed);
718 assert.deepEqual(yield* runIds(resumed), [resumedRun, continuationRun]);
719 const quiet = yield* createThread("no-roster-before-queue");
720 yield* createRun(quiet, "completed");
721 const quietQueued = yield* createRun(quiet, "queued", { ordinal: 2, completedAt: null });
722 assert.deepEqual(yield* runIds(quiet), [quietQueued]);
723 }).pipe(Effect.provide(layerTest)),
724);
725​
726it.effect("marks fork descendants unreadable when their source is missing or corrupt", () =>
727 Effect.gen(function* () {
728 const projections = yield* ProjectionStore.ProjectionStoreV2;
729 const sql = yield* SqlClient.SqlClient;
730 const source = yield* createThread("source");
731 const sourceRun = yield* createRun(source, "completed");
732 const fork = yield* createThread("fork", {
733 forkedFrom: { type: "run", threadId: source, runId: sourceRun },
734 });
735 const descendant = yield* createThread("descendant", {
736 forkedFrom: { type: "run", threadId: fork, runId: RunId.make("run:fork") },
737 });
738 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
739 yield* sql`
740 UPDATE orchestration_v2_projection_runs SET payload_json = '{}'
741 WHERE run_id = ${sourceRun}
742 `;
743 assert.deepEqual(
744 new Set(yield* projections.getUnreadableThreadIds()),
745 new Set([source, fork, descendant]),
746 );
747 yield* sql`DELETE FROM orchestration_v2_projection_threads WHERE thread_id = ${source}`;
748 assert.deepEqual(
749 new Set(yield* projections.getUnreadableThreadIds()),
750 new Set([fork, descendant]),
751 );
752 }).pipe(Effect.provide(layerTest)),
753);