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

ProjectionRecovery.test.ts

613 lines21.8 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 { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
27import * as EffectOutbox from "./EffectOutbox.ts";
28import * as ProjectionStore from "./ProjectionStore.ts";
29import { restartContinuationRun } from "./RestartContinuation.ts";
30​
31const layerTest = Layer.mergeAll(ProjectionStore.layer, EffectOutbox.layer).pipe(
32 Layer.provideMerge(SqlitePersistence.layerMemory),
33);
34const providerInstanceId = ProviderInstanceId.make("codex");
35const modelSelection = { instanceId: providerInstanceId, model: "gpt-5.4" };
36const driver = ProviderDriverKind.make("codex");
37​
38const createThread = Effect.fn(function* (
39 name: string,
40 overrides: Partial<OrchestrationV2AppThread> = {},
41) {
42 const projections = yield* ProjectionStore.ProjectionStoreV2;
43 const now = yield* DateTime.now;
44 const threadId = ThreadId.make(`thread:recovery:${name}`);
45 const thread: OrchestrationV2AppThread = {
46 createdBy: "user",
47 creationSource: "web",
48 id: threadId,
49 projectId: ProjectId.make("project:recovery"),
50 title: name,
51 providerInstanceId,
52 modelSelection,
53 runtimeMode: "full-access",
54 interactionMode: "default",
55 branch: null,
56 worktreePath: null,
57 activeProviderThreadId: null,
58 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
59 forkedFrom: null,
60 createdAt: now,
61 updatedAt: now,
62 archivedAt: null,
63 settledOverride: null,
64 settledAt: null,
65 lastVisitedAt: null,
66 deletedAt: null,
67 ...overrides,
68 };
69 yield* projections.apply({
70 id: EventId.make(`event:${threadId}:created`),
71 type: "thread.created",
72 threadId,
73 occurredAt: now,
74 payload: thread,
75 });
76 return threadId;
77});
78​
79const createRun = Effect.fn(function* (
80 threadId: ThreadId,
81 status: OrchestrationV2Run["status"],
82 overrides: Partial<OrchestrationV2Run> = {},
83) {
84 const projections = yield* ProjectionStore.ProjectionStoreV2;
85 const now = yield* DateTime.now;
86 const ordinal = overrides.ordinal ?? 1;
87 const runId = RunId.make(`run:${threadId}:${ordinal}`);
88 yield* projections.apply({
89 id: EventId.make(`event:${runId}:created`),
90 type: "run.created",
91 threadId,
92 runId,
93 occurredAt: now,
94 payload: {
95 id: runId,
96 threadId,
97 ordinal,
98 providerInstanceId,
99 modelSelection,
100 providerThreadId: null,
101 userMessageId: MessageId.make(`message:${runId}`),
102 rootNodeId: null,
103 activeAttemptId: null,
104 status,
105 requestedAt: now,
106 startedAt: now,
107 completedAt: status === "completed" ? now : null,
108 checkpointId: null,
109 contextHandoffId: null,
110 ...overrides,
111 },
112 });
113 return runId;
114});
115​
116it.effect("selects unfinished recovery work without reading settled thread histories", () =>
117 Effect.gen(function* () {
118 const projections = yield* ProjectionStore.ProjectionStoreV2;
119 const outbox = yield* EffectOutbox.EffectOutboxV2;
120 const sql = yield* SqlClient.SqlClient;
121 const now = yield* DateTime.now;
122 for (let index = 0; index < 600; index += 1) {
123 yield* createRun(yield* createThread(`settled-${index}`), "completed");
124 }
125 const queued = yield* createThread("queued");
126 const archived = yield* createThread("archived", { archivedAt: now });
127 const deleted = yield* createThread("deleted", { deletedAt: now });
128 const blocked = yield* createThread("blocked");
129 yield* createRun(queued, "completed");
130 for (const threadId of [queued, archived, deleted, blocked]) {
131 yield* createRun(threadId, "queued", threadId === queued ? { ordinal: 2 } : {});
132 }
133 yield* createRun(blocked, "waiting", { ordinal: 2 });
134 const background = yield* createThread("background");
135 yield* createRun(background, "completed");
136 yield* projections.apply({
137 id: EventId.make("event:recovery:background"),
138 type: "turn-item.updated",
139 threadId: background,
140 occurredAt: now,
141 payload: {
142 id: TurnItemId.make("item:recovery:background"),
143 threadId: background,
144 runId: null,
145 nodeId: null,
146 providerThreadId: null,
147 providerTurnId: null,
148 nativeItemRef: null,
149 parentItemId: null,
150 ordinal: 1,
151 type: "dynamic_tool",
152 status: "waiting",
153 title: null,
154 startedAt: now,
155 completedAt: null,
156 updatedAt: now,
157 toolName: "background",
158 input: null,
159 output: null,
160 },
161 });
162 const outboxOnly = yield* createThread("outbox-only");
163 yield* outbox.enqueue([
164 {
165 id: "effect:recovery:outbox-only",
166 commandId: CommandId.make("command:recovery:outbox-only"),
167 threadId: outboxOnly,
168 request: { type: "provider-turn.start", runId: RunId.make("run:outbox-only") },
169 },
170 ]);
171 const requestOnly = yield* createThread("request-only");
172 yield* projections.apply({
173 id: EventId.make("event:recovery:request-only"),
174 type: "runtime-request.updated",
175 threadId: requestOnly,
176 occurredAt: now,
177 payload: {
178 id: RuntimeRequestId.make("request:recovery:pending"),
179 nodeId: NodeId.make("node:recovery:request"),
180 providerTurnId: null,
181 nativeRequestRef: null,
182 kind: "user_input",
183 status: "pending",
184 responseCapability: { type: "not_resumable", reason: "Process stopped" },
185 createdAt: now,
186 resolvedAt: null,
187 },
188 });
189 const delivery = yield* createThread("delivery", { archivedAt: now });
190 yield* createRun(delivery, "completed", {
191 delegatedCompletion: {
192 disposition: "open",
193 nextGeneration: 2,
194 delivery: { generation: 1, messageId: MessageId.make("message:delivery"), taskIds: [] },
195 },
196 });
197​
198 // This historical payload cannot be decoded. Candidate discovery must not
199 // materialize it while deciding which threads have work to reconcile.
200 yield* sql`
201 UPDATE orchestration_v2_projection_runs SET payload_json = '{broken'
202 WHERE thread_id = ${ThreadId.make("thread:recovery:settled-599")}
203 `;
204 yield* sql`
205 UPDATE orchestration_v2_projection_runs SET payload_json = '{broken'
206 WHERE thread_id = ${queued} AND ordinal = 1
207 `;
208 assert.deepEqual(yield* projections.getRecoveryThreadIds("queued-runs"), [queued]);
209 assert.deepEqual(
210 new Set(yield* projections.getRecoveryThreadIds("runtime")),
211 new Set([queued, archived, blocked, background, outboxOnly, requestOnly]),
212 );
213 assert.deepEqual(yield* projections.getRecoveryThreadIds("delegated-completions"), [delivery]);
214 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
215 const recoveryState = yield* projections.getRuntimeRecoveryProjection(queued);
216 assert.deepEqual(
217 recoveryState.runs.map((run) => run.id),
218 [RunId.make(`run:${queued}:2`)],
219 );
220 assert.deepEqual(yield* projections.getUnreadableThreadIds(), [
221 queued,
222 ThreadId.make("thread:recovery:settled-599"),
223 ]);
224 }).pipe(Effect.provide(layerTest)),
225);
226​
227it.effect("recovers terminal subagent results until their cross-thread transfer exists", () =>
228 Effect.gen(function* () {
229 const projections = yield* ProjectionStore.ProjectionStoreV2;
230 const sql = yield* SqlClient.SqlClient;
231 const now = yield* DateTime.now;
232 const parent = yield* createThread("subagent-parent");
233 const children: Array<ThreadId> = [];
234 for (const name of ["terminal", "archived", "deleted", "running", "held", "queued"]) {
235 const child = yield* createThread(`subagent-${name}`, {
236 lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent },
237 forkedFrom: { type: "node", nodeId: NodeId.make(`node:${name}`) },
238 archivedAt: name === "archived" ? now : null,
239 deletedAt: name === "deleted" ? now : null,
240 });
241 yield* createRun(child, name === "running" ? "running" : "completed");
242 // A wake queued behind the result: held by Stop or a restart, or still deliverable.
243 if (name === "held" || name === "queued") {
244 yield* createRun(child, "queued", {
245 ordinal: 2,
246 startedAt: null,
247 ...(name === "held" ? { queueHeld: true } : {}),
248 });
249 }
250 children.push(child);
251 }
252 const terminalChildren = new Set([children[0]!, children[1]!, children[4]!]);
253 assert.deepEqual(
254 new Set(yield* projections.getRecoveryThreadIds("subagent-results")),
255 terminalChildren,
256 );
257​
258 const completed = children[0]!;
259 const transferId = ContextTransferId.make("transfer:recovery:subagent-result");
260 yield* projections.apply({
261 id: EventId.make("event:recovery:subagent-result"),
262 type: "context-transfer.created",
263 threadId: parent,
264 occurredAt: now,
265 payload: {
266 id: transferId,
267 type: "subagent_result",
268 sourceThreadId: completed,
269 targetThreadId: parent,
270 sourcePoint: { threadId: completed },
271 basePoint: null,
272 sourceProviderInstanceId: providerInstanceId,
273 targetProviderInstanceId: providerInstanceId,
274 targetRunId: null,
275 status: "pending",
276 resolution: null,
277 createdBy: "system",
278 error: null,
279 createdAt: now,
280 updatedAt: now,
281 consumedAt: null,
282 },
283 });
284 const archivedChild = children[1];
285 assert.isDefined(archivedChild);
286 assert.deepEqual(
287 new Set(yield* projections.getRecoveryThreadIds("subagent-results")),
288 new Set([archivedChild, children[4]!]),
289 );
290 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
291 yield* sql`
292 UPDATE orchestration_v2_projection_context_transfers SET payload_json = '{}'
293 WHERE context_transfer_id = ${transferId}
294 `;
295 assert.deepEqual(
296 new Set(yield* projections.getUnreadableThreadIds()),
297 new Set([parent, completed]),
298 );
299 }).pipe(Effect.provide(layerTest)),
300);
301​
302it.effect.each([
303 { name: "SQLite", layer: layerTest },
304 { name: "memory", layer: ProjectionStore.layerMemory },
305])("recovers only recorded follow-up results with $name projections", ({ layer }) =>
306 Effect.gen(function* () {
307 const projections = yield* ProjectionStore.ProjectionStoreV2;
308 const now = yield* DateTime.now;
309 const parent = yield* createThread("followup-parent");
310 const child = yield* createThread("followup-child", {
311 lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent },
312 forkedFrom: { type: "node", nodeId: NodeId.make("node:original") },
313 });
314 const originalRunId = yield* createRun(child, "completed");
315 yield* projections.apply({
316 id: EventId.make("event:original-result"),
317 type: "context-transfer.created",
318 threadId: parent,
319 occurredAt: now,
320 payload: {
321 id: ContextTransferId.make("transfer:original-result"),
322 type: "subagent_result",
323 sourceThreadId: child,
324 targetThreadId: parent,
325 sourcePoint: { threadId: child, runId: originalRunId },
326 basePoint: null,
327 sourceProviderInstanceId: providerInstanceId,
328 targetProviderInstanceId: providerInstanceId,
329 targetRunId: null,
330 status: "pending",
331 resolution: null,
332 createdBy: "system",
333 error: null,
334 createdAt: now,
335 updatedAt: now,
336 consumedAt: null,
337 },
338 });
339 // Historical untracked work does not acquire a notification on restart.
340 yield* createRun(child, "completed", { ordinal: 2 });
341 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
342 const taskId = NodeId.make("node:followup");
343 yield* createRun(child, "completed", { ordinal: 3, delegatedTaskId: taskId });
344 yield* createRun(child, "running", { ordinal: 4 });
345 const task = {
346 id: taskId,
347 threadId: parent,
348 runId: null,
349 parentNodeId: NodeId.make("node:parent"),
350 origin: "app_owned" as const,
351 createdBy: "agent" as const,
352 driver,
353 providerInstanceId,
354 providerThreadId: null,
355 childThreadId: child,
356 nativeTaskRef: null,
357 prompt: "Check the follow-up.",
358 title: null,
359 model: null,
360 status: "running" as const,
361 result: null,
362 startedAt: now,
363 completedAt: null,
364 updatedAt: now,
365 };
366 yield* projections.apply({
367 id: EventId.make("event:followup-task"),
368 type: "subagent.updated",
369 threadId: parent,
370 occurredAt: now,
371 payload: task,
372 });
373 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), [child]);
374 yield* projections.apply({
375 id: EventId.make("event:followup-settled"),
376 type: "subagent.updated",
377 threadId: parent,
378 occurredAt: now,
379 payload: { ...task, status: "completed", result: "Follow-up result.", completedAt: now },
380 });
381 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
382 }).pipe(Effect.provide(layer)),
383);
384​
385it.effect("includes shared sessions and provider-owned background rosters in recovery", () =>
386 Effect.gen(function* () {
387 const projections = yield* ProjectionStore.ProjectionStoreV2;
388 const now = yield* DateTime.now;
389 const first = yield* createThread("shared-first");
390 const second = yield* createThread("shared-second", { archivedAt: now });
391 const providerSessionId = ProviderSessionId.make("session:recovery:shared");
392 for (const threadId of [first, second]) {
393 yield* projections.apply({
394 id: EventId.make(`event:${threadId}:session`),
395 type: "provider-session.attached",
396 threadId,
397 driver,
398 providerInstanceId,
399 occurredAt: now,
400 payload: {
401 id: providerSessionId,
402 driver,
403 providerInstanceId,
404 status: "ready",
405 cwd: "/workspace",
406 model: modelSelection.model,
407 capabilities: CodexProviderCapabilitiesV2,
408 createdAt: now,
409 updatedAt: now,
410 lastError: null,
411 },
412 });
413 }
414 const roster = yield* createThread("roster");
415 yield* projections.apply({
416 id: EventId.make("event:recovery:roster"),
417 type: "provider-thread.updated",
418 threadId: roster,
419 driver,
420 providerInstanceId,
421 occurredAt: now,
422 payload: {
423 id: ProviderThreadId.make("provider-thread:recovery:roster"),
424 appThreadId: roster,
425 ownerNodeId: null,
426 driver,
427 providerInstanceId,
428 providerSessionId: null,
429 nativeThreadRef: null,
430 nativeConversationHeadRef: null,
431 status: "idle",
432 firstRunOrdinal: null,
433 lastRunOrdinal: null,
434 handoffIds: [],
435 forkedFrom: null,
436 createdAt: now,
437 updatedAt: now,
438 pendingBackgroundTasks: [
439 { taskId: "background", description: "Still running", kind: "command" },
440 ],
441 },
442 });
443 const prepared = yield* createThread("prepared-continuation");
444 const preparedSessionId = ProviderSessionId.make("session:recovery:prepared");
445 const preparedProviderThreadId = ProviderThreadId.make("provider-thread:recovery:prepared");
446 yield* projections.apply({
447 id: EventId.make("event:recovery:prepared-session"),
448 type: "provider-session.attached",
449 threadId: prepared,
450 driver,
451 providerInstanceId,
452 occurredAt: now,
453 payload: {
454 id: preparedSessionId,
455 driver,
456 providerInstanceId,
457 status: "stopped",
458 cwd: "/workspace",
459 model: modelSelection.model,
460 capabilities: CodexProviderCapabilitiesV2,
461 createdAt: now,
462 updatedAt: now,
463 lastError: null,
464 },
465 });
466 yield* projections.apply({
467 id: EventId.make("event:recovery:prepared-thread"),
468 type: "provider-thread.updated",
469 threadId: prepared,
470 driver,
471 providerInstanceId,
472 occurredAt: now,
473 payload: {
474 id: preparedProviderThreadId,
475 appThreadId: prepared,
476 ownerNodeId: null,
477 driver,
478 providerInstanceId,
479 providerSessionId: preparedSessionId,
480 nativeThreadRef: { driver, nativeId: "native:prepared", strength: "strong" },
481 nativeConversationHeadRef: null,
482 status: "idle",
483 firstRunOrdinal: 1,
484 lastRunOrdinal: 1,
485 handoffIds: [],
486 forkedFrom: null,
487 createdAt: now,
488 updatedAt: now,
489 pendingBackgroundTasks: [],
490 },
491 });
492 const preparedRunId = yield* createRun(prepared, "starting", {
493 providerThreadId: preparedProviderThreadId,
494 restartContinuationOfRunId: RunId.make("run:recovery:source"),
495 });
496 assert.deepEqual(
497 new Set(yield* projections.getRecoveryThreadIds("runtime")),
498 new Set([first, second, roster, prepared]),
499 );
500 const preparedState = yield* projections.getRuntimeRecoveryProjection(prepared);
501 assert.deepEqual(
502 preparedState.providerSessions.map((session) => session.id),
503 [preparedSessionId],
504 );
505 assert.equal(restartContinuationRun(preparedState)?.id, preparedRunId);
506 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
507 const sql = yield* SqlClient.SqlClient;
508 yield* sql`
509 UPDATE orchestration_v2_projection_provider_sessions SET payload_json = '{}'
510 WHERE provider_session_id = ${providerSessionId}
511 `;
512 assert.deepEqual(
513 new Set(yield* projections.getUnreadableThreadIds()),
514 new Set([first, second]),
515 );
516 }).pipe(Effect.provide(layerTest)),
517);
518​
519it.effect("reads the run that owns a background roster, not a queued or resumed one", () =>
520 Effect.gen(function* () {
521 const projections = yield* ProjectionStore.ProjectionStoreV2;
522 const now = yield* DateTime.now;
523 const withRoster = Effect.fn(function* (threadId: ThreadId) {
524 yield* projections.apply({
525 id: EventId.make(`event:${threadId}:roster`),
526 type: "provider-thread.updated",
527 threadId,
528 driver,
529 providerInstanceId,
530 occurredAt: now,
531 payload: {
532 id: ProviderThreadId.make(`provider-thread:${threadId}`),
533 appThreadId: threadId,
534 ownerNodeId: null,
535 driver,
536 providerInstanceId,
537 providerSessionId: null,
538 nativeThreadRef: null,
539 nativeConversationHeadRef: null,
540 status: "idle",
541 firstRunOrdinal: null,
542 lastRunOrdinal: null,
543 handoffIds: [],
544 forkedFrom: null,
545 createdAt: now,
546 updatedAt: now,
547 pendingBackgroundTasks: [
548 { taskId: "background", description: "Still running", kind: "command" },
549 ],
550 },
551 });
552 });
553 const runIds = (threadId: ThreadId) =>
554 projections
555 .getRuntimeRecoveryProjection(threadId)
556 .pipe(Effect.map((state) => state.runs.map((run) => run.id)));
557 // Settled with background work left, then a queued follow-up.
558 const settled = yield* createThread("roster-before-queue");
559 const settledRun = yield* createRun(settled, "completed", {
560 providerThreadId: ProviderThreadId.make(`provider-thread:${settled}`),
561 });
562 const queuedRun = yield* createRun(settled, "queued", { ordinal: 2, completedAt: null });
563 yield* withRoster(settled);
564 assert.deepEqual(yield* runIds(settled), [settledRun, queuedRun]);
565 // A resumed queued run (ordinal 1) ended after a continuation (ordinal 2).
566 const resumed = yield* createThread("roster-after-resume");
567 const resumedRun = yield* createRun(resumed, "completed", {
568 providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`),
569 completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z"),
570 });
571 const continuationRun = yield* createRun(resumed, "completed", {
572 providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`),
573 ordinal: 2,
574 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
575 });
576 yield* withRoster(resumed);
577 assert.deepEqual(yield* runIds(resumed), [resumedRun, continuationRun]);
578 // Without a roster, settled history is not read.
579 const quiet = yield* createThread("no-roster-before-queue");
580 yield* createRun(quiet, "completed");
581 const quietQueued = yield* createRun(quiet, "queued", { ordinal: 2, completedAt: null });
582 assert.deepEqual(yield* runIds(quiet), [quietQueued]);
583 }).pipe(Effect.provide(layerTest)),
584);
585​
586it.effect("marks fork descendants unreadable when their source is missing or corrupt", () =>
587 Effect.gen(function* () {
588 const projections = yield* ProjectionStore.ProjectionStoreV2;
589 const sql = yield* SqlClient.SqlClient;
590 const source = yield* createThread("source");
591 const sourceRun = yield* createRun(source, "completed");
592 const fork = yield* createThread("fork", {
593 forkedFrom: { type: "run", threadId: source, runId: sourceRun },
594 });
595 const descendant = yield* createThread("descendant", {
596 forkedFrom: { type: "run", threadId: fork, runId: RunId.make("run:fork") },
597 });
598 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
599 yield* sql`
600 UPDATE orchestration_v2_projection_runs SET payload_json = '{}'
601 WHERE run_id = ${sourceRun}
602 `;
603 assert.deepEqual(
604 new Set(yield* projections.getUnreadableThreadIds()),
605 new Set([source, fork, descendant]),
606 );
607 yield* sql`DELETE FROM orchestration_v2_projection_threads WHERE thread_id = ${source}`;
608 assert.deepEqual(
609 new Set(yield* projections.getUnreadableThreadIds()),
610 new Set([fork, descendant]),
611 );
612 }).pipe(Effect.provide(layerTest)),
613);