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