Open History to see the last commit
1import {
2 CheckpointScopeId,
3 CommandId,
4 type OrchestrationV2Checkpoint,
5 type OrchestrationV2ExecutionNode,
6 type OrchestrationV2ProviderThread,
7 type OrchestrationV2Run,
8 type OrchestrationV2TurnItem,
9 RunId,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Schema from "effect/Schema";
17
18import { CheckpointServiceV2 } from "./CheckpointService.ts";
19import { EventSinkV2 } from "./EventSink.ts";
20import { IdAllocatorV2, type IdAllocatorV2Shape } from "./IdAllocator.ts";
21import { ProjectionStoreV2 } from "./ProjectionStore.ts";
22
23export class CheckpointCaptureExecutionError extends Schema.TaggedError<CheckpointCaptureExecutionError>()(
24 "CheckpointCaptureExecutionError",
25 {
26 threadId: ThreadId,
27 runId: RunId,
28 scopeId: CheckpointScopeId,
29 cause: Schema.optional(Schema.Defect()),
30 },
31) {}
32
33const isCheckpointCaptureExecutionError = Schema.is(CheckpointCaptureExecutionError);
34
35export interface CheckpointCaptureServiceV2Shape {
36 readonly execute: (input: {
37 readonly threadId: ThreadId;
38 readonly runId: RunId;
39 readonly scopeId: CheckpointScopeId;
40 }) => Effect.Effect<void, CheckpointCaptureExecutionError>;
41}
42
43export class CheckpointCaptureServiceV2 extends Context.Service<
44 CheckpointCaptureServiceV2,
45 CheckpointCaptureServiceV2Shape
46>()("t3/orchestration-v2/CheckpointCaptureService/CheckpointCaptureServiceV2") {}
47
48export const layer: Layer.Layer<
49 CheckpointCaptureServiceV2,
50 never,
51 CheckpointServiceV2 | EventSinkV2 | IdAllocatorV2 | ProjectionStoreV2
52> = Layer.effect(
53 CheckpointCaptureServiceV2,
54 Effect.gen(function* () {
55 const checkpoints = yield* CheckpointServiceV2;
56 const eventSink = yield* EventSinkV2;
57 const ids = yield* IdAllocatorV2;
58 const projections = yield* ProjectionStoreV2;
59
60 const execute = Effect.fn("orchestrationV2.checkpointCapture.execute")(function* (input: {
61 readonly threadId: ThreadId;
62 readonly runId: RunId;
63 readonly scopeId: CheckpointScopeId;
64 }) {
65 const projection = yield* projections.getThreadProjection(input.threadId);
66 const run = projection.runs.find((candidate) => candidate.id === input.runId);
67
68 // The effect is at-least-once. A completed run with a checkpoint proves
69 // that an earlier execution committed its result.
70 if (run?.status === "completed" && run.checkpointId !== null) {
71 return;
72 }
73
74 const rootNode = projection.nodes.find((candidate) => candidate.id === run?.rootNodeId);
75 const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
76 const providerThread = projection.providerThreads.find(
77 (candidate) => candidate.id === run?.providerThreadId,
78 );
79 if (
80 run === undefined ||
81 run.status !== "waiting" ||
82 rootNode === undefined ||
83 scope === undefined ||
84 rootNode.checkpointScopeId !== scope.id ||
85 providerThread === undefined
86 ) {
87 return yield* new CheckpointCaptureExecutionError({
88 threadId: input.threadId,
89 runId: input.runId,
90 scopeId: input.scopeId,
91 cause: "The persisted checkpoint capture target is incomplete or no longer waiting.",
92 });
93 }
94
95 const capturedAt = yield* DateTime.now;
96 const baselineOrdinalWithinScope = Math.max(0, run.ordinal - 1);
97 const hasReadyCheckpoint = (ordinalWithinScope: number) =>
98 projection.checkpoints.some(
99 (candidate) =>
100 candidate.scopeId === scope.id &&
101 candidate.ordinalWithinScope === ordinalWithinScope &&
102 candidate.status === "ready",
103 );
104 const threadStartCheckpoint =
105 baselineOrdinalWithinScope === 0 || hasReadyCheckpoint(0)
106 ? null
107 : yield* checkpoints.materializeBaselineCheckpoint({
108 scope,
109 ordinalWithinScope: 0,
110 });
111 const baselineCheckpoint = hasReadyCheckpoint(baselineOrdinalWithinScope)
112 ? null
113 : yield* checkpoints.materializeBaselineCheckpoint({
114 scope,
115 ordinalWithinScope: baselineOrdinalWithinScope,
116 });
117 const checkpoint = yield* checkpoints.capture({
118 scope,
119 runId: run.id,
120 nodeId: rootNode.id,
121 ordinalWithinScope: run.ordinal,
122 appRunOrdinal: run.ordinal,
123 capturedAt,
124 });
125 // Match RunExecutionService: capture loaded the waiting run before
126 // materializing baselines. Omit delegatedCompletion so a newer cohort
127 // write during capture is not overwritten by this stale snapshot
128 // (ProjectionStore preserves the field when absent from the payload).
129 const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;
130 const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
131 yield* eventSink.commitCommand({
132 commandId,
133 threadId: input.threadId,
134 commandType: "checkpoint.capture",
135 acceptedAt: capturedAt,
136 effects: [],
137 events: [
138 ...(threadStartCheckpoint === null
139 ? []
140 : [
141 {
142 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
143 type: "checkpoint.captured" as const,
144 threadId: input.threadId,
145 nodeId: threadStartCheckpoint.nodeId,
146 driver: providerThread.driver,
147 providerInstanceId: run.providerInstanceId,
148 occurredAt: capturedAt,
149 payload: threadStartCheckpoint,
150 },
151 ]),
152 ...(baselineCheckpoint === null
153 ? []
154 : [
155 {
156 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
157 type: "checkpoint.captured" as const,
158 threadId: input.threadId,
159 nodeId: baselineCheckpoint.nodeId,
160 driver: providerThread.driver,
161 providerInstanceId: run.providerInstanceId,
162 occurredAt: capturedAt,
163 payload: baselineCheckpoint,
164 },
165 ]),
166 {
167 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
168 type: "checkpoint.captured",
169 threadId: input.threadId,
170 runId: run.id,
171 nodeId: rootNode.id,
172 driver: providerThread.driver,
173 providerInstanceId: run.providerInstanceId,
174 occurredAt: capturedAt,
175 payload: checkpoint,
176 },
177 {
178 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
179 type: "turn-item.updated",
180 threadId: input.threadId,
181 runId: run.id,
182 nodeId: rootNode.id,
183 driver: providerThread.driver,
184 providerInstanceId: run.providerInstanceId,
185 occurredAt: capturedAt,
186 payload: makeCheckpointTurnItem({
187 idAllocator: ids,
188 run,
189 rootNode,
190 providerThread,
191 checkpoint,
192 completedAt: capturedAt,
193 }),
194 },
195 {
196 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
197 type: "run.updated",
198 threadId: input.threadId,
199 runId: run.id,
200 nodeId: rootNode.id,
201 providerInstanceId: run.providerInstanceId,
202 occurredAt: capturedAt,
203 payload: {
204 ...runWithoutDelegatedCompletion,
205 status: "completed",
206 completedAt: capturedAt,
207 checkpointId: checkpoint.id,
208 },
209 },
210 {
211 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
212 type: "node.updated",
213 threadId: input.threadId,
214 runId: run.id,
215 nodeId: rootNode.id,
216 providerInstanceId: run.providerInstanceId,
217 occurredAt: capturedAt,
218 payload: {
219 ...rootNode,
220 status: "completed",
221 completedAt: capturedAt,
222 checkpointScopeId: scope.id,
223 },
224 },
225 ],
226 });
227 });
228
229 return CheckpointCaptureServiceV2.of({
230 execute: (input) =>
231 execute(input).pipe(
232 Effect.mapError((cause) =>
233 isCheckpointCaptureExecutionError(cause)
234 ? cause
235 : new CheckpointCaptureExecutionError({ ...input, cause }),
236 ),
237 ),
238 });
239 }),
240);
241
242function makeCheckpointTurnItem(input: {
243 readonly idAllocator: IdAllocatorV2Shape;
244 readonly run: OrchestrationV2Run;
245 readonly rootNode: OrchestrationV2ExecutionNode;
246 readonly providerThread: OrchestrationV2ProviderThread;
247 readonly checkpoint: OrchestrationV2Checkpoint;
248 readonly completedAt: DateTime.Utc;
249}): OrchestrationV2TurnItem {
250 return {
251 id: input.idAllocator.derive.turnItemFromProviderItem({
252 driver: input.providerThread.driver,
253 nativeItemId: `checkpoint:${input.checkpoint.id}`,
254 }),
255 threadId: input.run.threadId,
256 runId: input.run.id,
257 nodeId: input.rootNode.id,
258 providerThreadId: input.providerThread.id,
259 providerTurnId: input.rootNode.providerTurnId,
260 nativeItemRef: null,
261 parentItemId: null,
262 ordinal: input.run.ordinal * 100 + 99,
263 status: "completed",
264 title: null,
265 startedAt: input.completedAt,
266 completedAt: input.completedAt,
267 updatedAt: input.completedAt,
268 type: "checkpoint",
269 checkpointId: input.checkpoint.id,
270 scopeId: input.checkpoint.scopeId,
271 files: input.checkpoint.files,
272 };
273}