Open History to see the last commit
1import {
2 CheckpointScopeId,
3 CommandId,
4 type OrchestrationV2Checkpoint,
5 type OrchestrationV2CheckpointScope,
6 type OrchestrationV2ExecutionNode,
7 type OrchestrationV2ProviderThread,
8 type OrchestrationV2Run,
9 type OrchestrationV2TurnItem,
10 RunId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Context from "effect/Context";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Schema from "effect/Schema";
19
20import * as CheckpointService from "./CheckpointService.ts";
21import * as EventSink from "./EventSink.ts";
22import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
23import * as ProjectionStore from "./ProjectionStore.ts";
24
25// Git processes are already capped server-wide; this keeps one thread from taking every slot.
26const REPOSITORY_CAPTURE_CONCURRENCY = 6;
27
28export class CheckpointCaptureExecutionError extends Schema.TaggedError<CheckpointCaptureExecutionError>()(
29 "CheckpointCaptureExecutionError",
30 {
31 threadId: ThreadId,
32 runId: RunId,
33 scopeId: CheckpointScopeId,
34 cause: Schema.optional(Schema.Defect()),
35 },
36) {}
37
38const isCheckpointCaptureExecutionError = Schema.is(CheckpointCaptureExecutionError);
39
40export interface CheckpointCaptureServiceV2Shape {
41 readonly execute: (input: {
42 readonly threadId: ThreadId;
43 readonly runId: RunId;
44 readonly scopeId: CheckpointScopeId;
45 }) => Effect.Effect<void, CheckpointCaptureExecutionError>;
46}
47
48export class CheckpointCaptureServiceV2 extends Context.Service<
49 CheckpointCaptureServiceV2,
50 CheckpointCaptureServiceV2Shape
51>()("t3/orchestration-v2/CheckpointCaptureService/CheckpointCaptureServiceV2") {}
52
53export const layer: Layer.Layer<
54 CheckpointCaptureServiceV2,
55 never,
56 | CheckpointService.CheckpointServiceV2
57 | EventSink.EventSinkV2
58 | IdAllocator.IdAllocatorV2
59 | ProjectionStore.ProjectionStoreV2
60> = Layer.effect(
61 CheckpointCaptureServiceV2,
62 Effect.gen(function* () {
63 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
64 const eventSink = yield* EventSink.EventSinkV2;
65 const ids = yield* IdAllocator.IdAllocatorV2;
66 const projections = yield* ProjectionStore.ProjectionStoreV2;
67
68 const execute = Effect.fn("orchestrationV2.checkpointCapture.execute")(function* (input: {
69 readonly threadId: ThreadId;
70 readonly runId: RunId;
71 readonly scopeId: CheckpointScopeId;
72 }) {
73 const context = yield* projections.getCheckpointCaptureContext(input.threadId, input);
74 const { run, rootNode, scope, providerThread, preservedCheckpointOrdinals, sideChat } =
75 context;
76 // Stopped runs remain terminal; their checkpoint is the next message's rollback point.
77 const stopped = run?.status === "interrupted" || run?.status === "cancelled";
78
79 // A checkpoint on a settled run proves this at-least-once effect already committed.
80 if (
81 run !== undefined &&
82 run.checkpointId !== null &&
83 (run.status === "completed" || stopped)
84 ) {
85 return;
86 }
87 // Rollback uses the same lane and can precede a capture retry; preserve the restored workspace and discarded run.
88 if (run?.status === "rolled_back") {
89 return;
90 }
91
92 if (
93 run === undefined ||
94 (run.status !== "waiting" && !stopped) ||
95 rootNode === undefined ||
96 scope === undefined ||
97 rootNode.checkpointScopeId !== scope.id ||
98 providerThread === undefined
99 ) {
100 return yield* new CheckpointCaptureExecutionError({
101 threadId: input.threadId,
102 runId: input.runId,
103 scopeId: input.scopeId,
104 cause: "The persisted checkpoint capture target is incomplete or no longer waiting.",
105 });
106 }
107
108 const capturedAt = yield* DateTime.now;
109 const baselineOrdinalWithinScope = Math.max(0, run.ordinal - 1);
110 const isPreserved = (ordinalWithinScope: number) =>
111 preservedCheckpointOrdinals.includes(ordinalWithinScope);
112 // The baselines this capture materializes are attributed to the run materializing them. The
113 // thread's scope may already be a later run's: one queued meanwhile, or sent after Stop.
114 const materializeBaseline = (ordinalWithinScope: number) =>
115 checkpoints.materializeBaselineCheckpoint({
116 scope,
117 ordinalWithinScope,
118 nodeId: rootNode.id,
119 capturedAt: run.requestedAt,
120 forceMissing: sideChat,
121 });
122 // The tracked Git folders the thread reaches now. One added since the turn began has no
123 // baseline, so its first checkpoint lists no files; one removed is simply not captured.
124 const repositoryScopes =
125 sideChat || context.thread === undefined
126 ? []
127 : yield* checkpoints.repositoryScopes({ rootScope: scope, ...context.thread });
128 const nested =
129 repositoryScopes.length === 0
130 ? undefined
131 : yield* checkpoints.nestedScopePaths([scope, ...repositoryScopes]);
132 const excluded = (target: OrchestrationV2CheckpointScope) => {
133 const excludePaths = nested?.get(target.id);
134 return excludePaths === undefined ? {} : { excludePaths };
135 };
136 // Each scope is checked on its own, so a retried capture fills only what is missing.
137 const captureRoot = Effect.gen(function* () {
138 // Materializing a baseline waits on the folder's lock before the capture does.
139 const capturesBeforeLock = yield* checkpoints.capturesSoFar(scope.cwd);
140 const threadStartCheckpoint =
141 baselineOrdinalWithinScope === 0 || isPreserved(0) ? null : yield* materializeBaseline(0);
142 const baselineCheckpoint = isPreserved(baselineOrdinalWithinScope)
143 ? null
144 : yield* materializeBaseline(baselineOrdinalWithinScope);
145 const checkpoint = yield* checkpoints.capture({
146 scope,
147 runId: run.id,
148 nodeId: rootNode.id,
149 ordinalWithinScope: run.ordinal,
150 appRunOrdinal: run.ordinal,
151 capturedAt,
152 forceMissing: sideChat,
153 capturesBeforeLock,
154 ...excluded(scope),
155 });
156 return { threadStartCheckpoint, baselineCheckpoint, checkpoint };
157 });
158 const recordedScopes = new Map(
159 context.repositoryScopes.map((recorded) => [recorded.id, recorded]),
160 );
161 const captureRepository = Effect.fnUntraced(function* (
162 prepared: OrchestrationV2CheckpointScope,
163 ) {
164 const recorded = recordedScopes.get(prepared.id);
165 // A recorded scope keeps the run that first used it; only a renamed folder rewrites it.
166 const changed =
167 recorded === undefined ||
168 recorded.cwd !== prepared.cwd ||
169 recorded.label !== prepared.label;
170 const target =
171 recorded === undefined
172 ? prepared
173 : changed
174 ? {
175 ...prepared,
176 runId: recorded.runId,
177 nodeId: recorded.nodeId,
178 createdAt: recorded.createdAt,
179 }
180 : recorded;
181 const captured = yield* checkpoints.captureRepository({
182 scope: target,
183 runId: run.id,
184 nodeId: rootNode.id,
185 ordinalWithinScope: run.ordinal,
186 capturedAt,
187 baselineCapturedAt: run.requestedAt,
188 baselineRecorded: context.repositoryScopesWithBaseline.includes(target.id),
189 ...excluded(target),
190 });
191 // Only a repository with something to show is recorded, so the rest cost no events,
192 // rows or bytes on the wire.
193 return Option.match(captured, {
194 onNone: () => [],
195 onSome: (capture) => [{ scope: changed ? target : null, ...capture }],
196 });
197 });
198 const [{ threadStartCheckpoint, baselineCheckpoint, checkpoint }, repositoryCaptures] =
199 yield* Effect.all(
200 [
201 captureRoot,
202 Effect.forEach(repositoryScopes, captureRepository, {
203 concurrency: REPOSITORY_CAPTURE_CONCURRENCY,
204 }),
205 ],
206 { concurrency: 2 },
207 );
208 // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run.
209 const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;
210 const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
211 const checkpointEvent = (payload: OrchestrationV2Checkpoint) =>
212 Effect.map(ids.allocate.event({ threadId: input.threadId, commandId }), (id) => ({
213 id,
214 type: "checkpoint.captured" as const,
215 threadId: input.threadId,
216 ...(payload.runId === null ? {} : { runId: payload.runId }),
217 nodeId: payload.nodeId,
218 driver: providerThread.driver,
219 providerInstanceId: run.providerInstanceId,
220 occurredAt: capturedAt,
221 payload,
222 }));
223 const repositoryEvents = yield* Effect.forEach(repositoryCaptures.flat(), (capture) =>
224 Effect.gen(function* () {
225 return [
226 ...(capture.scope === null
227 ? []
228 : [
229 {
230 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
231 type: "checkpoint-scope.created" as const,
232 threadId: input.threadId,
233 runId: run.id,
234 nodeId: rootNode.id,
235 providerInstanceId: run.providerInstanceId,
236 occurredAt: capturedAt,
237 payload: capture.scope,
238 },
239 ]),
240 ...(capture.baseline === null ? [] : [yield* checkpointEvent(capture.baseline)]),
241 yield* checkpointEvent(capture.checkpoint),
242 ];
243 }),
244 );
245 yield* eventSink.commitCommand({
246 commandId,
247 threadId: input.threadId,
248 commandType: "checkpoint.capture",
249 acceptedAt: capturedAt,
250 effects: [],
251 events: [
252 // Root records come last: a client that takes the latest ordinal-0 baseline gets the thread's.
253 ...repositoryEvents.flat(),
254 ...(threadStartCheckpoint === null
255 ? []
256 : [
257 {
258 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
259 type: "checkpoint.captured" as const,
260 threadId: input.threadId,
261 nodeId: threadStartCheckpoint.nodeId,
262 driver: providerThread.driver,
263 providerInstanceId: run.providerInstanceId,
264 occurredAt: capturedAt,
265 payload: threadStartCheckpoint,
266 },
267 ]),
268 ...(baselineCheckpoint === null
269 ? []
270 : [
271 {
272 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
273 type: "checkpoint.captured" as const,
274 threadId: input.threadId,
275 nodeId: baselineCheckpoint.nodeId,
276 driver: providerThread.driver,
277 providerInstanceId: run.providerInstanceId,
278 occurredAt: capturedAt,
279 payload: baselineCheckpoint,
280 },
281 ]),
282 {
283 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
284 type: "checkpoint.captured",
285 threadId: input.threadId,
286 runId: run.id,
287 nodeId: rootNode.id,
288 driver: providerThread.driver,
289 providerInstanceId: run.providerInstanceId,
290 occurredAt: capturedAt,
291 payload: checkpoint,
292 },
293 {
294 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
295 type: "turn-item.updated",
296 threadId: input.threadId,
297 runId: run.id,
298 nodeId: rootNode.id,
299 driver: providerThread.driver,
300 providerInstanceId: run.providerInstanceId,
301 occurredAt: capturedAt,
302 payload: makeCheckpointTurnItem({
303 idAllocator: ids,
304 run,
305 rootNode,
306 providerThread,
307 checkpoint,
308 completedAt: capturedAt,
309 }),
310 },
311 {
312 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
313 type: "run.updated",
314 threadId: input.threadId,
315 runId: run.id,
316 nodeId: rootNode.id,
317 providerInstanceId: run.providerInstanceId,
318 occurredAt: capturedAt,
319 payload: stopped
320 ? { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id }
321 : {
322 ...runWithoutDelegatedCompletion,
323 status: "completed",
324 completedAt: capturedAt,
325 checkpointId: checkpoint.id,
326 },
327 },
328 ...(stopped
329 ? []
330 : [
331 {
332 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
333 type: "node.updated" as const,
334 threadId: input.threadId,
335 runId: run.id,
336 nodeId: rootNode.id,
337 providerInstanceId: run.providerInstanceId,
338 occurredAt: capturedAt,
339 payload: {
340 ...rootNode,
341 status: "completed" as const,
342 completedAt: capturedAt,
343 checkpointScopeId: scope.id,
344 },
345 },
346 ]),
347 ],
348 });
349 });
350
351 return CheckpointCaptureServiceV2.of({
352 execute: Effect.fn("CheckpointCaptureServiceV2.execute")(function (input) {
353 return execute(input).pipe(
354 Effect.mapError((cause) =>
355 isCheckpointCaptureExecutionError(cause)
356 ? cause
357 : new CheckpointCaptureExecutionError({ ...input, cause }),
358 ),
359 );
360 }),
361 });
362 }),
363);
364
365function makeCheckpointTurnItem(input: {
366 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
367 readonly run: OrchestrationV2Run;
368 readonly rootNode: OrchestrationV2ExecutionNode;
369 readonly providerThread: OrchestrationV2ProviderThread;
370 readonly checkpoint: OrchestrationV2Checkpoint;
371 readonly completedAt: DateTime.Utc;
372}): OrchestrationV2TurnItem {
373 return {
374 id: input.idAllocator.derive.turnItemFromProviderItem({
375 driver: input.providerThread.driver,
376 nativeItemId: `checkpoint:${input.checkpoint.id}`,
377 }),
378 threadId: input.run.threadId,
379 runId: input.run.id,
380 nodeId: input.rootNode.id,
381 providerThreadId: input.providerThread.id,
382 providerTurnId: input.rootNode.providerTurnId,
383 nativeItemRef: null,
384 parentItemId: null,
385 ordinal: input.run.ordinal * 100 + 99,
386 status: "completed",
387 title: null,
388 startedAt: input.completedAt,
389 completedAt: input.completedAt,
390 updatedAt: input.completedAt,
391 type: "checkpoint",
392 checkpointId: input.checkpoint.id,
393 scopeId: input.checkpoint.scopeId,
394 files: input.checkpoint.files,
395 };
396}