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

ProjectionRecovery.test.ts

450 lines15.5 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/unstable/sql/SqlClient";
24​
25import { SqlitePersistenceMemory } from "../persistence/Layers/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 TestLayer = Layer.mergeAll(ProjectionStore.layer, EffectOutbox.layer).pipe(
32 Layer.provideMerge(SqlitePersistenceMemory),
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(TestLayer)),
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"]) {
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 children.push(child);
243 }
244 assert.deepEqual(
245 new Set(yield* projections.getRecoveryThreadIds("subagent-results")),
246 new Set(children.slice(0, 2)),
247 );
248 const completed = children[0]!;
249 const transferId = ContextTransferId.make("transfer:recovery:subagent-result");
250 yield* projections.apply({
251 id: EventId.make("event:recovery:subagent-result"),
252 type: "context-transfer.created",
253 threadId: parent,
254 occurredAt: now,
255 payload: {
256 id: transferId,
257 type: "subagent_result",
258 sourceThreadId: completed,
259 targetThreadId: parent,
260 sourcePoint: { threadId: completed },
261 basePoint: null,
262 sourceProviderInstanceId: providerInstanceId,
263 targetProviderInstanceId: providerInstanceId,
264 targetRunId: null,
265 status: "pending",
266 resolution: null,
267 createdBy: "system",
268 error: null,
269 createdAt: now,
270 updatedAt: now,
271 consumedAt: null,
272 },
273 });
274 const archivedChild = children[1];
275 assert.isDefined(archivedChild);
276 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), [archivedChild]);
277 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
278 yield* sql`
279 UPDATE orchestration_v2_projection_context_transfers SET payload_json = '{}'
280 WHERE context_transfer_id = ${transferId}
281 `;
282 assert.deepEqual(
283 new Set(yield* projections.getUnreadableThreadIds()),
284 new Set([parent, completed]),
285 );
286 }).pipe(Effect.provide(TestLayer)),
287);
288​
289it.effect("includes shared sessions and provider-owned background rosters in recovery", () =>
290 Effect.gen(function* () {
291 const projections = yield* ProjectionStore.ProjectionStoreV2;
292 const now = yield* DateTime.now;
293 const first = yield* createThread("shared-first");
294 const second = yield* createThread("shared-second", { archivedAt: now });
295 const providerSessionId = ProviderSessionId.make("session:recovery:shared");
296 for (const threadId of [first, second]) {
297 yield* projections.apply({
298 id: EventId.make(`event:${threadId}:session`),
299 type: "provider-session.attached",
300 threadId,
301 driver,
302 providerInstanceId,
303 occurredAt: now,
304 payload: {
305 id: providerSessionId,
306 driver,
307 providerInstanceId,
308 status: "ready",
309 cwd: "/workspace",
310 model: modelSelection.model,
311 capabilities: CodexProviderCapabilitiesV2,
312 createdAt: now,
313 updatedAt: now,
314 lastError: null,
315 },
316 });
317 }
318 const roster = yield* createThread("roster");
319 yield* projections.apply({
320 id: EventId.make("event:recovery:roster"),
321 type: "provider-thread.updated",
322 threadId: roster,
323 driver,
324 providerInstanceId,
325 occurredAt: now,
326 payload: {
327 id: ProviderThreadId.make("provider-thread:recovery:roster"),
328 appThreadId: roster,
329 ownerNodeId: null,
330 driver,
331 providerInstanceId,
332 providerSessionId: null,
333 nativeThreadRef: null,
334 nativeConversationHeadRef: null,
335 status: "idle",
336 firstRunOrdinal: null,
337 lastRunOrdinal: null,
338 handoffIds: [],
339 forkedFrom: null,
340 createdAt: now,
341 updatedAt: now,
342 pendingBackgroundTasks: [
343 { taskId: "background", description: "Still running", kind: "command" },
344 ],
345 },
346 });
347 const prepared = yield* createThread("prepared-continuation");
348 const preparedSessionId = ProviderSessionId.make("session:recovery:prepared");
349 const preparedProviderThreadId = ProviderThreadId.make("provider-thread:recovery:prepared");
350 yield* projections.apply({
351 id: EventId.make("event:recovery:prepared-session"),
352 type: "provider-session.attached",
353 threadId: prepared,
354 driver,
355 providerInstanceId,
356 occurredAt: now,
357 payload: {
358 id: preparedSessionId,
359 driver,
360 providerInstanceId,
361 status: "stopped",
362 cwd: "/workspace",
363 model: modelSelection.model,
364 capabilities: CodexProviderCapabilitiesV2,
365 createdAt: now,
366 updatedAt: now,
367 lastError: null,
368 },
369 });
370 yield* projections.apply({
371 id: EventId.make("event:recovery:prepared-thread"),
372 type: "provider-thread.updated",
373 threadId: prepared,
374 driver,
375 providerInstanceId,
376 occurredAt: now,
377 payload: {
378 id: preparedProviderThreadId,
379 appThreadId: prepared,
380 ownerNodeId: null,
381 driver,
382 providerInstanceId,
383 providerSessionId: preparedSessionId,
384 nativeThreadRef: { driver, nativeId: "native:prepared", strength: "strong" },
385 nativeConversationHeadRef: null,
386 status: "idle",
387 firstRunOrdinal: 1,
388 lastRunOrdinal: 1,
389 handoffIds: [],
390 forkedFrom: null,
391 createdAt: now,
392 updatedAt: now,
393 pendingBackgroundTasks: [],
394 },
395 });
396 const preparedRunId = yield* createRun(prepared, "starting", {
397 providerThreadId: preparedProviderThreadId,
398 restartContinuationOfRunId: RunId.make("run:recovery:source"),
399 });
400 assert.deepEqual(
401 new Set(yield* projections.getRecoveryThreadIds("runtime")),
402 new Set([first, second, roster, prepared]),
403 );
404 const preparedState = yield* projections.getRuntimeRecoveryProjection(prepared);
405 assert.deepEqual(
406 preparedState.providerSessions.map((session) => session.id),
407 [preparedSessionId],
408 );
409 assert.equal(restartContinuationRun(preparedState)?.id, preparedRunId);
410 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
411 const sql = yield* SqlClient.SqlClient;
412 yield* sql`
413 UPDATE orchestration_v2_projection_provider_sessions SET payload_json = '{}'
414 WHERE provider_session_id = ${providerSessionId}
415 `;
416 assert.deepEqual(
417 new Set(yield* projections.getUnreadableThreadIds()),
418 new Set([first, second]),
419 );
420 }).pipe(Effect.provide(TestLayer)),
421);
422​
423it.effect("marks fork descendants unreadable when their source is missing or corrupt", () =>
424 Effect.gen(function* () {
425 const projections = yield* ProjectionStore.ProjectionStoreV2;
426 const sql = yield* SqlClient.SqlClient;
427 const source = yield* createThread("source");
428 const sourceRun = yield* createRun(source, "completed");
429 const fork = yield* createThread("fork", {
430 forkedFrom: { type: "run", threadId: source, runId: sourceRun },
431 });
432 const descendant = yield* createThread("descendant", {
433 forkedFrom: { type: "run", threadId: fork, runId: RunId.make("run:fork") },
434 });
435 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
436 yield* sql`
437 UPDATE orchestration_v2_projection_runs SET payload_json = '{}'
438 WHERE run_id = ${sourceRun}
439 `;
440 assert.deepEqual(
441 new Set(yield* projections.getUnreadableThreadIds()),
442 new Set([source, fork, descendant]),
443 );
444 yield* sql`DELETE FROM orchestration_v2_projection_threads WHERE thread_id = ${source}`;
445 assert.deepEqual(
446 new Set(yield* projections.getUnreadableThreadIds()),
447 new Set([fork, descendant]),
448 );
449 }).pipe(Effect.provide(TestLayer)),
450);