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

CheckpointCaptureService.test.ts

384 lines14.0 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CheckpointId,
4 CheckpointRef,
5 CheckpointScopeId,
6 EventId,
7 MessageId,
8 NodeId,
9 type OrchestrationV2DomainEvent,
10 type OrchestrationV2Run,
11 ProjectId,
12 ProviderDriverKind,
13 ProviderInstanceId,
14 ProviderThreadId,
15 RunId,
16 ThreadId,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Ref from "effect/Ref";
22import * as SqlClient from "effect/unstable/sql/SqlClient";
23​
24import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
25import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
26import { VcsProcessTimeoutError } from "@t3tools/contracts";
27import { CheckpointServiceV2, layer as checkpointServiceLayer } from "./CheckpointService.ts";
28import * as CheckpointCaptureService from "./CheckpointCaptureService.ts";
29import { EventSinkV2 } from "./EventSink.ts";
30import * as IdAllocator from "./IdAllocator.ts";
31import * as ProjectionStore from "./ProjectionStore.ts";
32​
33const ProjectionStoreTestLayer = Layer.mergeAll(
34 ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
35 SqlitePersistenceMemory,
36);
37​
38const threadId = ThreadId.make("thread:checkpoint-capture-delegated");
39const projectId = ProjectId.make("project:checkpoint-capture-delegated");
40const runId = RunId.make("run:checkpoint-capture-delegated");
41const scopeId = CheckpointScopeId.make("scope:checkpoint-capture-delegated");
42const rootNodeId = NodeId.make("node:checkpoint-capture-delegated-root");
43const taskId = NodeId.make("node:checkpoint-capture-task");
44const deliveryMessageId = MessageId.make("message:checkpoint-capture-delivery");
45const providerThreadId = ProviderThreadId.make("provider-thread:checkpoint-capture-delegated");
46const providerInstanceId = ProviderInstanceId.make("codex");
47const driver = ProviderDriverKind.make("codex");
48const modelSelection = {
49 instanceId: providerInstanceId,
50 model: "gpt-5.4",
51} as const;
52​
53it.layer(ProjectionStoreTestLayer)("CheckpointCaptureServiceV2", (it) => {
54 it.effect.each([false, true])(
55 "captures without decoding history or losing newer delegated completion, ref lookup fails=%s",
56 (refLookupFails) =>
57 Effect.gen(function* () {
58 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
59 const now = yield* DateTime.now;
60 const later = DateTime.add(now, { seconds: 1 });
61​
62 const staleDelegatedCompletion = {
63 disposition: "open" as const,
64 nextGeneration: 1,
65 settledDeliveryCount: 0,
66 delivery: null,
67 };
68 const newerCohort = {
69 disposition: "open" as const,
70 nextGeneration: 2,
71 settledDeliveryCount: 1,
72 delivery: {
73 generation: 1,
74 messageId: deliveryMessageId,
75 taskIds: [taskId],
76 },
77 };
78 const staleRun: OrchestrationV2Run = {
79 id: runId,
80 threadId,
81 ordinal: 1,
82 providerInstanceId,
83 modelSelection,
84 providerThreadId,
85 userMessageId: MessageId.make("message:checkpoint-capture-user"),
86 rootNodeId,
87 activeAttemptId: null,
88 status: "waiting",
89 requestedAt: now,
90 startedAt: now,
91 completedAt: null,
92 checkpointId: null,
93 contextHandoffId: null,
94 // Snapshot taken before a concurrent cohort advanced during capture work.
95 delegatedCompletion: staleDelegatedCompletion,
96 };
97 const rootNode = {
98 id: rootNodeId,
99 threadId,
100 runId,
101 parentNodeId: null,
102 rootNodeId,
103 kind: "root_turn" as const,
104 status: "waiting" as const,
105 countsForRun: true,
106 providerThreadId,
107 providerTurnId: null,
108 nativeItemRef: null,
109 runtimeRequestId: null,
110 checkpointScopeId: scopeId,
111 startedAt: now,
112 completedAt: null,
113 };
114 const scope = {
115 id: scopeId,
116 threadId,
117 runId,
118 nodeId: rootNodeId,
119 parentScopeId: null,
120 providerThreadId,
121 kind: "root_run" as const,
122 ordinalWithinParent: 0,
123 advancesAppRunCount: true,
124 cwd: "/repo",
125 createdAt: now,
126 };
127 const providerThread = {
128 id: providerThreadId,
129 driver,
130 providerInstanceId,
131 providerSessionId: null,
132 appThreadId: threadId,
133 ownerNodeId: rootNodeId,
134 nativeThreadRef: null,
135 nativeConversationHeadRef: null,
136 status: "idle" as const,
137 firstRunOrdinal: 1,
138 lastRunOrdinal: 1,
139 handoffIds: [],
140 forkedFrom: null,
141 createdAt: now,
142 updatedAt: now,
143 };
144 const readyBaseline = {
145 id: CheckpointId.make("checkpoint:baseline-0"),
146 threadId,
147 scopeId,
148 runId: null,
149 nodeId: rootNodeId,
150 parentCheckpointId: null,
151 ordinalWithinScope: 0,
152 appRunOrdinal: null,
153 ref: CheckpointRef.make("checkpoint-ref:baseline-0"),
154 status: "ready" as const,
155 files: [],
156 capturedAt: now,
157 };
158 const captured = {
159 id: CheckpointId.make("checkpoint:captured-1"),
160 threadId,
161 scopeId,
162 runId,
163 nodeId: rootNodeId,
164 parentCheckpointId: readyBaseline.id,
165 ordinalWithinScope: 1,
166 appRunOrdinal: 1,
167 ref: CheckpointRef.make("checkpoint-ref:captured-1"),
168 status: "ready" as const,
169 files: [],
170 capturedAt: now,
171 };
172​
173 yield* projectionStore.apply({
174 id: EventId.make("event:checkpoint-capture:thread"),
175 type: "thread.created",
176 threadId,
177 occurredAt: now,
178 payload: {
179 createdBy: "user",
180 creationSource: "web",
181 id: threadId,
182 projectId,
183 title: "Checkpoint capture delegated completion",
184 providerInstanceId,
185 modelSelection,
186 runtimeMode: "full-access",
187 interactionMode: "default",
188 branch: null,
189 worktreePath: null,
190 activeProviderThreadId: null,
191 lineage: {
192 parentThreadId: null,
193 relationshipToParent: null,
194 rootThreadId: threadId,
195 },
196 forkedFrom: null,
197 createdAt: now,
198 updatedAt: now,
199 archivedAt: null,
200 settledOverride: null,
201 settledAt: null,
202 lastVisitedAt: null,
203 deletedAt: null,
204 },
205 });
206 yield* projectionStore.apply({
207 id: EventId.make("event:checkpoint-capture:run-stale"),
208 type: "run.updated",
209 threadId,
210 runId,
211 nodeId: rootNodeId,
212 providerInstanceId,
213 occurredAt: now,
214 payload: staleRun,
215 });
216 yield* projectionStore.apply({
217 id: EventId.make("event:checkpoint-capture:node"),
218 type: "node.updated",
219 threadId,
220 runId,
221 nodeId: rootNodeId,
222 providerInstanceId,
223 occurredAt: now,
224 payload: rootNode,
225 });
226 yield* projectionStore.apply({
227 id: EventId.make("event:checkpoint-capture:provider-thread"),
228 type: "provider-thread.updated",
229 threadId,
230 nodeId: rootNodeId,
231 driver,
232 providerInstanceId,
233 occurredAt: now,
234 payload: providerThread,
235 });
236 yield* projectionStore.apply({
237 id: EventId.make("event:checkpoint-capture:scope"),
238 type: "checkpoint-scope.created",
239 threadId,
240 runId,
241 nodeId: rootNodeId,
242 occurredAt: now,
243 payload: scope,
244 });
245 yield* projectionStore.apply({
246 id: EventId.make("event:checkpoint-capture:baseline"),
247 type: "checkpoint.captured",
248 threadId,
249 nodeId: rootNodeId,
250 driver,
251 providerInstanceId,
252 occurredAt: now,
253 payload: readyBaseline,
254 });
255 const sql = yield* SqlClient.SqlClient;
256 yield* sql`INSERT OR REPLACE INTO orchestration_v2_projection_turn_items
257 (turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
258 parent_item_id, ordinal, type, status, updated_at, payload_json)
259 VALUES ('obsolete-history', ${threadId}, ${runId}, ${rootNodeId}, NULL, NULL,
260 NULL, 1, 'assistant_message', 'completed', ${DateTime.formatIso(now)}, '{"obsolete":true}')`;
261 yield* sql`UPDATE orchestration_v2_projection_checkpoints
262 SET payload_json = json_set(payload_json, '$.files', 'obsolete file summary')
263 WHERE checkpoint_id = ${readyBaseline.id}`;
264 assert.equal(
265 (yield* Effect.exit(projectionStore.getThreadProjection(threadId)))._tag,
266 "Failure",
267 );
268​
269 const committed = yield* Ref.make<ReadonlyArray<OrchestrationV2DomainEvent>>([]);
270 const captureLayer = CheckpointCaptureService.layer.pipe(
271 Layer.provide(
272 Layer.mergeAll(
273 IdAllocator.layer,
274 refLookupFails
275 ? checkpointServiceLayer.pipe(
276 Layer.provide(
277 Layer.mergeAll(
278 IdAllocator.layer,
279 Layer.mock(CheckpointStore.CheckpointStore)({
280 isGitRepository: () => Effect.succeed(true),
281 captureCheckpoint: () => Effect.void,
282 hasCheckpointRef: () =>
283 Effect.fail(
284 new VcsProcessTimeoutError({
285 operation: "test.hasCheckpointRef",
286 command: "git",
287 cwd: "/repo",
288 timeoutMs: 30000,
289 }),
290 ),
291 }),
292 ),
293 ),
294 )
295 : Layer.mock(CheckpointServiceV2)({
296 materializeBaselineCheckpoint: () =>
297 Effect.die(
298 "baseline materialization must be skipped when ordinal 0 is ready",
299 ),
300 capture: () => Effect.succeed(captured),
301 }),
302 Layer.mock(EventSinkV2)({
303 commitCommand: (input) =>
304 Ref.set(committed, input.events).pipe(
305 Effect.as({
306 commandId: input.commandId,
307 committed: true,
308 sequence: 1,
309 events: input.events,
310 effects: [],
311 } as never),
312 ),
313 }),
314 ),
315 ),
316 );
317​
318 yield* Effect.gen(function* () {
319 const service = yield* CheckpointCaptureService.CheckpointCaptureServiceV2;
320 const incomplete = yield* service
321 .execute({ threadId, runId, scopeId: CheckpointScopeId.make("missing-scope") })
322 .pipe(Effect.flip);
323 assert.instanceOf(incomplete, CheckpointCaptureService.CheckpointCaptureExecutionError);
324 // Capture reads the waiting run while the projection still holds the stale cohort.
325 yield* service.execute({ threadId, runId, scopeId });
326​
327 const events = yield* Ref.get(committed);
328 const runUpdated = events.find((event) => event.type === "run.updated");
329 assert.isDefined(runUpdated);
330 if (runUpdated?.type !== "run.updated") {
331 return;
332 }
333 assert.equal(runUpdated.payload.status, "completed");
334 const capturedEvent = events.find((event) => event.type === "checkpoint.captured");
335 assert.equal(
336 runUpdated.payload.checkpointId,
337 refLookupFails ? capturedEvent?.payload.id : captured.id,
338 );
339 if (refLookupFails && capturedEvent?.type === "checkpoint.captured") {
340 assert.equal(capturedEvent.payload.status, "ready");
341 assert.deepEqual(capturedEvent.payload.files, []);
342 }
343 assert.isUndefined(
344 runUpdated.payload.delegatedCompletion,
345 "checkpoint capture must omit delegatedCompletion so ProjectionStore can keep a newer cohort",
346 );
347​
348 // Race: a newer cohort lands on the projection after capture read the stale
349 // waiting run and before the capture command's run.updated is applied.
350 yield* projectionStore.apply({
351 id: EventId.make("event:checkpoint-capture:newer-cohort"),
352 type: "run.updated",
353 threadId,
354 runId,
355 nodeId: rootNodeId,
356 providerInstanceId,
357 occurredAt: later,
358 payload: {
359 ...staleRun,
360 delegatedCompletion: newerCohort,
361 },
362 });
363​
364 // Apply the real capture-emitted run.updated through ProjectionStore.
365 yield* projectionStore.apply(runUpdated);
366​
367 const projectedRun = (yield* projectionStore.getCheckpointCaptureContext(threadId, {
368 runId,
369 scopeId,
370 })).run;
371 assert.isDefined(projectedRun);
372 assert.equal(projectedRun?.status, "completed");
373 assert.equal(projectedRun?.checkpointId, runUpdated.payload.checkpointId);
374 assert.deepEqual(projectedRun?.delegatedCompletion, newerCohort);
375 assert.equal(projectedRun?.delegatedCompletion?.delivery?.messageId, deliveryMessageId);
376 assert.deepEqual(projectedRun?.delegatedCompletion?.delivery?.taskIds, [taskId]);
377 // The persisted completion is the at-least-once capture receipt.
378 yield* Ref.set(committed, []);
379 yield* service.execute({ threadId, runId, scopeId });
380 assert.deepEqual(yield* Ref.get(committed), []);
381 }).pipe(Effect.provide(captureLayer));
382 }),
383 );
384});