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 { makeInterruptResultTurnItem } from "./runInterruptResult.ts";
25import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
26
27// Git processes are already capped server-wide; this keeps one thread from taking every slot.
28const REPOSITORY_CAPTURE_CONCURRENCY = 6;
29
30export class CheckpointCaptureExecutionError extends Schema.TaggedError<CheckpointCaptureExecutionError>()(
31 "CheckpointCaptureExecutionError",
32 {
33 threadId: ThreadId,
34 runId: RunId,
35 scopeId: CheckpointScopeId,
36 cause: Schema.optional(Schema.Defect()),
37 },
38) {}
39
40const isCheckpointCaptureExecutionError = Schema.is(CheckpointCaptureExecutionError);
41
42export interface CheckpointCaptureServiceV2Shape {
43 readonly execute: (input: {
44 readonly threadId: ThreadId;
45 readonly runId: RunId;
46 readonly scopeId: CheckpointScopeId;
47 }) => Effect.Effect<void, CheckpointCaptureExecutionError>;
48}
49
50export class CheckpointCaptureServiceV2 extends Context.Service<
51 CheckpointCaptureServiceV2,
52 CheckpointCaptureServiceV2Shape
53>()("t3/orchestration-v2/CheckpointCaptureService/CheckpointCaptureServiceV2") {}
54
55export const layer: Layer.Layer<
56 CheckpointCaptureServiceV2,
57 never,
58 | CheckpointService.CheckpointServiceV2
59 | EventSink.EventSinkV2
60 | IdAllocator.IdAllocatorV2
61 | ProjectionStore.ProjectionStoreV2
62 | ThreadCommandExecutor.ThreadCommandExecutor
63> = Layer.effect(
64 CheckpointCaptureServiceV2,
65 Effect.gen(function* () {
66 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
67 const eventSink = yield* EventSink.EventSinkV2;
68 const ids = yield* IdAllocator.IdAllocatorV2;
69 const projections = yield* ProjectionStore.ProjectionStoreV2;
70 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
71
72 const execute = Effect.fn("orchestrationV2.checkpointCapture.execute")(function* (input: {
73 readonly threadId: ThreadId;
74 readonly runId: RunId;
75 readonly scopeId: CheckpointScopeId;
76 }) {
77 const context = yield* projections.getCheckpointCaptureContext(input.threadId, input, {
78 preservedCheckpoints: "baselines",
79 });
80 const { run, rootNode, scope, providerThread, preservedCheckpointOrdinals, sideChat } =
81 context;
82 // Runs settle before capture; `waiting` is a run persisted before captures ran after settling.
83 const settled =
84 run?.status === "completed" || run?.status === "interrupted" || run?.status === "cancelled";
85
86 // A checkpoint on a settled run proves this at-least-once effect already committed.
87 if (run !== undefined && run.checkpointId !== null && settled) {
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" && !settled) ||
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 was discarded.",
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 legacyWaiting = currentRun.status === "waiting";
258 if (
259 !legacyWaiting &&
260 currentRun.status !== "completed" &&
261 currentRun.status !== "interrupted" &&
262 currentRun.status !== "cancelled"
263 ) {
264 return;
265 }
266 // A Stop accepted once the provider's turn had ended stored only its request: the
267 // terminal already wrote `completed` (or legacy `waiting`). That Stop still wins here.
268 const stopSignals =
269 !legacyWaiting && currentRun.status !== "completed"
270 ? []
271 : (yield* projections.getThreadRecords(input.threadId, ["turnItems"], {
272 turnItemTypes: ["run_interrupt_request", "run_interrupt_result"],
273 turnItemStatuses: ["completed", "interrupted"],
274 turnItemRunIds: [run.id],
275 })).turnItems;
276 const stopRequest = stopSignals.some((item) => item.type === "run_interrupt_result")
277 ? undefined
278 : stopSignals.find((item) => item.type === "run_interrupt_request");
279 const settledStatus =
280 stopRequest === undefined ? ("completed" as const) : ("interrupted" as const);
281 const settlesRun = legacyWaiting || stopRequest !== undefined;
282 // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run.
283 const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } =
284 currentRun;
285 yield* eventSink.commitCommand({
286 commandId,
287 threadId: input.threadId,
288 commandType: "checkpoint.capture",
289 acceptedAt: capturedAt,
290 effects: [],
291 events: [
292 // Root records come last: a client that takes the latest ordinal-0 baseline gets the thread's.
293 ...repositoryEvents.flat(),
294 ...(threadStartCheckpoint === null
295 ? []
296 : [
297 {
298 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
299 type: "checkpoint.captured" as const,
300 threadId: input.threadId,
301 nodeId: threadStartCheckpoint.nodeId,
302 driver: providerThread.driver,
303 providerInstanceId: run.providerInstanceId,
304 occurredAt: capturedAt,
305 payload: threadStartCheckpoint,
306 },
307 ]),
308 ...(baselineCheckpoint === null
309 ? []
310 : [
311 {
312 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
313 type: "checkpoint.captured" as const,
314 threadId: input.threadId,
315 nodeId: baselineCheckpoint.nodeId,
316 driver: providerThread.driver,
317 providerInstanceId: run.providerInstanceId,
318 occurredAt: capturedAt,
319 payload: baselineCheckpoint,
320 },
321 ]),
322 {
323 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
324 type: "checkpoint.captured",
325 threadId: input.threadId,
326 runId: run.id,
327 nodeId: rootNode.id,
328 driver: providerThread.driver,
329 providerInstanceId: run.providerInstanceId,
330 occurredAt: capturedAt,
331 payload: checkpoint,
332 },
333 {
334 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
335 type: "turn-item.updated",
336 threadId: input.threadId,
337 runId: run.id,
338 nodeId: rootNode.id,
339 driver: providerThread.driver,
340 providerInstanceId: run.providerInstanceId,
341 occurredAt: capturedAt,
342 payload: makeCheckpointTurnItem({
343 idAllocator: ids,
344 run,
345 rootNode,
346 providerThread,
347 checkpoint,
348 completedAt: capturedAt,
349 }),
350 },
351 ...(stopRequest?.type !== "run_interrupt_request"
352 ? []
353 : [
354 {
355 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
356 type: "turn-item.updated" as const,
357 threadId: input.threadId,
358 runId: run.id,
359 nodeId: rootNode.id,
360 providerInstanceId: run.providerInstanceId,
361 occurredAt: capturedAt,
362 payload: makeInterruptResultTurnItem({
363 idAllocator: ids,
364 run,
365 rootNode,
366 providerThread,
367 reason: stopRequest.message,
368 completedAt: capturedAt,
369 }),
370 },
371 ]),
372 {
373 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
374 type: "run.updated",
375 threadId: input.threadId,
376 runId: run.id,
377 nodeId: rootNode.id,
378 providerInstanceId: run.providerInstanceId,
379 occurredAt: capturedAt,
380 payload: settlesRun
381 ? {
382 ...runWithoutDelegatedCompletion,
383 status: settledStatus,
384 completedAt: capturedAt,
385 checkpointId: checkpoint.id,
386 }
387 : { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id },
388 },
389 ...(!settlesRun
390 ? []
391 : [
392 {
393 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
394 type: "node.updated" as const,
395 threadId: input.threadId,
396 runId: run.id,
397 nodeId: rootNode.id,
398 providerInstanceId: run.providerInstanceId,
399 occurredAt: capturedAt,
400 payload: {
401 ...rootNode,
402 status: settledStatus,
403 completedAt: capturedAt,
404 checkpointScopeId: scope.id,
405 },
406 },
407 ]),
408 ],
409 });
410 }),
411 );
412 });
413
414 return CheckpointCaptureServiceV2.of({
415 execute: Effect.fn("CheckpointCaptureServiceV2.execute")(function (input) {
416 return execute(input).pipe(
417 Effect.mapError((cause) =>
418 isCheckpointCaptureExecutionError(cause)
419 ? cause
420 : new CheckpointCaptureExecutionError({ ...input, cause }),
421 ),
422 );
423 }),
424 });
425 }),
426);
427
428function makeCheckpointTurnItem(input: {
429 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
430 readonly run: OrchestrationV2Run;
431 readonly rootNode: OrchestrationV2ExecutionNode;
432 readonly providerThread: OrchestrationV2ProviderThread;
433 readonly checkpoint: OrchestrationV2Checkpoint;
434 readonly completedAt: DateTime.Utc;
435}): OrchestrationV2TurnItem {
436 return {
437 id: input.idAllocator.derive.turnItemFromProviderItem({
438 driver: input.providerThread.driver,
439 nativeItemId: `checkpoint:${input.checkpoint.id}`,
440 }),
441 threadId: input.run.threadId,
442 runId: input.run.id,
443 nodeId: input.rootNode.id,
444 providerThreadId: input.providerThread.id,
445 providerTurnId: input.rootNode.providerTurnId,
446 nativeItemRef: null,
447 parentItemId: null,
448 ordinal: input.run.ordinal * 100 + 99,
449 status: "completed",
450 title: null,
451 startedAt: input.completedAt,
452 completedAt: input.completedAt,
453 updatedAt: input.completedAt,
454 type: "checkpoint",
455 checkpointId: input.checkpoint.id,
456 scopeId: input.checkpoint.scopeId,
457 files: input.checkpoint.files,
458 };
459}