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.TaggedErrorClass<CheckpointCaptureExecutionError>()(
24 "CheckpointCaptureExecutionError",
25 {
26 threadId: ThreadId,
27 runId: RunId,
28 scopeId: CheckpointScopeId,
29 cause: Schema.optional(Schema.Defect()),
30 },
31) {}
32
33export interface CheckpointCaptureServiceV2Shape {
34 readonly execute: (input: {
35 readonly threadId: ThreadId;
36 readonly runId: RunId;
37 readonly scopeId: CheckpointScopeId;
38 }) => Effect.Effect<void, CheckpointCaptureExecutionError>;
39}
40
41export class CheckpointCaptureServiceV2 extends Context.Service<
42 CheckpointCaptureServiceV2,
43 CheckpointCaptureServiceV2Shape
44>()("t3/orchestration-v2/CheckpointCaptureService/CheckpointCaptureServiceV2") {}
45
46export const layer: Layer.Layer<
47 CheckpointCaptureServiceV2,
48 never,
49 CheckpointServiceV2 | EventSinkV2 | IdAllocatorV2 | ProjectionStoreV2
50> = Layer.effect(
51 CheckpointCaptureServiceV2,
52 Effect.gen(function* () {
53 const checkpoints = yield* CheckpointServiceV2;
54 const eventSink = yield* EventSinkV2;
55 const ids = yield* IdAllocatorV2;
56 const projections = yield* ProjectionStoreV2;
57
58 const execute = Effect.fn("orchestrationV2.checkpointCapture.execute")(function* (input: {
59 readonly threadId: ThreadId;
60 readonly runId: RunId;
61 readonly scopeId: CheckpointScopeId;
62 }) {
63 const projection = yield* projections.getThreadProjection(input.threadId);
64 const run = projection.runs.find((candidate) => candidate.id === input.runId);
65
66 // The effect is at-least-once. A completed run with a checkpoint proves
67 // that an earlier execution committed its result.
68 if (run?.status === "completed" && run.checkpointId !== null) {
69 return;
70 }
71
72 const rootNode = projection.nodes.find((candidate) => candidate.id === run?.rootNodeId);
73 const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
74 const providerThread = projection.providerThreads.find(
75 (candidate) => candidate.id === run?.providerThreadId,
76 );
77 if (
78 run === undefined ||
79 run.status !== "waiting" ||
80 rootNode === undefined ||
81 scope === undefined ||
82 rootNode.checkpointScopeId !== scope.id ||
83 providerThread === undefined
84 ) {
85 return yield* new CheckpointCaptureExecutionError({
86 threadId: input.threadId,
87 runId: input.runId,
88 scopeId: input.scopeId,
89 cause: "The persisted checkpoint capture target is incomplete or no longer waiting.",
90 });
91 }
92
93 const capturedAt = yield* DateTime.now;
94 const baselineCheckpoint = projection.checkpoints.some(
95 (candidate) => candidate.scopeId === scope.id && candidate.ordinalWithinScope === 0,
96 )
97 ? null
98 : yield* checkpoints.materializeBaselineCheckpoint({ scope });
99 const checkpoint = yield* checkpoints.capture({
100 scope,
101 runId: run.id,
102 nodeId: rootNode.id,
103 ordinalWithinScope: run.ordinal,
104 appRunOrdinal: run.ordinal,
105 capturedAt,
106 });
107 const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
108 yield* eventSink.commitCommand({
109 commandId,
110 threadId: input.threadId,
111 commandType: "checkpoint.capture",
112 acceptedAt: capturedAt,
113 effects: [],
114 events: [
115 ...(baselineCheckpoint === null
116 ? []
117 : [
118 {
119 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
120 type: "checkpoint.captured" as const,
121 threadId: input.threadId,
122 nodeId: baselineCheckpoint.nodeId,
123 driver: providerThread.driver,
124 providerInstanceId: run.providerInstanceId,
125 occurredAt: capturedAt,
126 payload: baselineCheckpoint,
127 },
128 ]),
129 {
130 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
131 type: "checkpoint.captured",
132 threadId: input.threadId,
133 runId: run.id,
134 nodeId: rootNode.id,
135 driver: providerThread.driver,
136 providerInstanceId: run.providerInstanceId,
137 occurredAt: capturedAt,
138 payload: checkpoint,
139 },
140 {
141 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
142 type: "turn-item.updated",
143 threadId: input.threadId,
144 runId: run.id,
145 nodeId: rootNode.id,
146 driver: providerThread.driver,
147 providerInstanceId: run.providerInstanceId,
148 occurredAt: capturedAt,
149 payload: makeCheckpointTurnItem({
150 idAllocator: ids,
151 run,
152 rootNode,
153 providerThread,
154 checkpoint,
155 completedAt: capturedAt,
156 }),
157 },
158 {
159 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
160 type: "run.updated",
161 threadId: input.threadId,
162 runId: run.id,
163 nodeId: rootNode.id,
164 providerInstanceId: run.providerInstanceId,
165 occurredAt: capturedAt,
166 payload: {
167 ...run,
168 status: "completed",
169 completedAt: capturedAt,
170 checkpointId: checkpoint.id,
171 },
172 },
173 {
174 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
175 type: "node.updated",
176 threadId: input.threadId,
177 runId: run.id,
178 nodeId: rootNode.id,
179 providerInstanceId: run.providerInstanceId,
180 occurredAt: capturedAt,
181 payload: {
182 ...rootNode,
183 status: "completed",
184 completedAt: capturedAt,
185 checkpointScopeId: scope.id,
186 },
187 },
188 ],
189 });
190 });
191
192 return CheckpointCaptureServiceV2.of({
193 execute: (input) =>
194 execute(input).pipe(
195 Effect.mapError((cause) =>
196 Schema.is(CheckpointCaptureExecutionError)(cause)
197 ? cause
198 : new CheckpointCaptureExecutionError({ ...input, cause }),
199 ),
200 ),
201 });
202 }),
203);
204
205function makeCheckpointTurnItem(input: {
206 readonly idAllocator: IdAllocatorV2Shape;
207 readonly run: OrchestrationV2Run;
208 readonly rootNode: OrchestrationV2ExecutionNode;
209 readonly providerThread: OrchestrationV2ProviderThread;
210 readonly checkpoint: OrchestrationV2Checkpoint;
211 readonly completedAt: DateTime.Utc;
212}): OrchestrationV2TurnItem {
213 return {
214 id: input.idAllocator.derive.turnItemFromProviderItem({
215 driver: input.providerThread.driver,
216 nativeItemId: `checkpoint:${input.checkpoint.id}`,
217 }),
218 threadId: input.run.threadId,
219 runId: input.run.id,
220 nodeId: input.rootNode.id,
221 providerThreadId: input.providerThread.id,
222 providerTurnId: input.rootNode.providerTurnId,
223 nativeItemRef: null,
224 parentItemId: null,
225 ordinal: input.run.ordinal * 100 + 99,
226 status: "completed",
227 title: null,
228 startedAt: input.completedAt,
229 completedAt: input.completedAt,
230 updatedAt: input.completedAt,
231 type: "checkpoint",
232 checkpointId: input.checkpoint.id,
233 scopeId: input.checkpoint.scopeId,
234 files: input.checkpoint.files,
235 };
236}