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

CheckpointCaptureService.test.ts

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