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

CheckpointCaptureService.test.ts

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