Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CheckpointCaptureService.ts

266 lines9.2 KB

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>;
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 baselineOrdinalWithinScope = Math.max(0, run.ordinal - 1);
95 const hasReadyCheckpoint = (ordinalWithinScope: number) =>
96 projection.checkpoints.some(
97 (candidate) =>
98 candidate.scopeId === scope.id &&
99 candidate.ordinalWithinScope === ordinalWithinScope &&
100 candidate.status === "ready",
101 );
102 const threadStartCheckpoint =
103 baselineOrdinalWithinScope === 0 || hasReadyCheckpoint(0)
104 ? null
105 : yield* checkpoints.materializeBaselineCheckpoint({
106 scope,
107 ordinalWithinScope: 0,
108 });
109 const baselineCheckpoint = hasReadyCheckpoint(baselineOrdinalWithinScope)
110 ? null
111 : yield* checkpoints.materializeBaselineCheckpoint({
112 scope,
113 ordinalWithinScope: baselineOrdinalWithinScope,
114 });
115 const checkpoint = yield* checkpoints.capture({
116 scope,
117 runId: run.id,
118 nodeId: rootNode.id,
119 ordinalWithinScope: run.ordinal,
120 appRunOrdinal: run.ordinal,
121 capturedAt,
122 });
123 const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
124 yield* eventSink.commitCommand({
125 commandId,
126 threadId: input.threadId,
127 commandType: "checkpoint.capture",
128 acceptedAt: capturedAt,
129 effects: [],
130 events: [
131 ...(threadStartCheckpoint === null
132 ? []
133 : [
134 {
135 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
136 type: "checkpoint.captured" as const,
137 threadId: input.threadId,
138 nodeId: threadStartCheckpoint.nodeId,
139 driver: providerThread.driver,
140 providerInstanceId: run.providerInstanceId,
141 occurredAt: capturedAt,
142 payload: threadStartCheckpoint,
143 },
144 ]),
145 ...(baselineCheckpoint === null
146 ? []
147 : [
148 {
149 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
150 type: "checkpoint.captured" as const,
151 threadId: input.threadId,
152 nodeId: baselineCheckpoint.nodeId,
153 driver: providerThread.driver,
154 providerInstanceId: run.providerInstanceId,
155 occurredAt: capturedAt,
156 payload: baselineCheckpoint,
157 },
158 ]),
159 {
160 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
161 type: "checkpoint.captured",
162 threadId: input.threadId,
163 runId: run.id,
164 nodeId: rootNode.id,
165 driver: providerThread.driver,
166 providerInstanceId: run.providerInstanceId,
167 occurredAt: capturedAt,
168 payload: checkpoint,
169 },
170 {
171 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
172 type: "turn-item.updated",
173 threadId: input.threadId,
174 runId: run.id,
175 nodeId: rootNode.id,
176 driver: providerThread.driver,
177 providerInstanceId: run.providerInstanceId,
178 occurredAt: capturedAt,
179 payload: makeCheckpointTurnItem({
180 idAllocator: ids,
181 run,
182 rootNode,
183 providerThread,
184 checkpoint,
185 completedAt: capturedAt,
186 }),
187 },
188 {
189 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
190 type: "run.updated",
191 threadId: input.threadId,
192 runId: run.id,
193 nodeId: rootNode.id,
194 providerInstanceId: run.providerInstanceId,
195 occurredAt: capturedAt,
196 payload: {
197 ...run,
198 status: "completed",
199 completedAt: capturedAt,
200 checkpointId: checkpoint.id,
201 },
202 },
203 {
204 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
205 type: "node.updated",
206 threadId: input.threadId,
207 runId: run.id,
208 nodeId: rootNode.id,
209 providerInstanceId: run.providerInstanceId,
210 occurredAt: capturedAt,
211 payload: {
212 ...rootNode,
213 status: "completed",
214 completedAt: capturedAt,
215 checkpointScopeId: scope.id,
216 },
217 },
218 ],
219 });
220 });
221​
222 return CheckpointCaptureServiceV2.of({
223 execute: (input) =>
224 execute(input).pipe(
225 Effect.mapError((cause) =>
226 Schema.is(CheckpointCaptureExecutionError)(cause)
227 ? cause
228 : new CheckpointCaptureExecutionError({ ...input, cause }),
229 ),
230 ),
231 });
232 }),
233);
234​
235function makeCheckpointTurnItem(input: {
236 readonly idAllocator: IdAllocatorV2Shape;
237 readonly run: OrchestrationV2Run;
238 readonly rootNode: OrchestrationV2ExecutionNode;
239 readonly providerThread: OrchestrationV2ProviderThread;
240 readonly checkpoint: OrchestrationV2Checkpoint;
241 readonly completedAt: DateTime.Utc;
242}): OrchestrationV2TurnItem {
243 return {
244 id: input.idAllocator.derive.turnItemFromProviderItem({
245 driver: input.providerThread.driver,
246 nativeItemId: `checkpoint:${input.checkpoint.id}`,
247 }),
248 threadId: input.run.threadId,
249 runId: input.run.id,
250 nodeId: input.rootNode.id,
251 providerThreadId: input.providerThread.id,
252 providerTurnId: input.rootNode.providerTurnId,
253 nativeItemRef: null,
254 parentItemId: null,
255 ordinal: input.run.ordinal * 100 + 99,
256 status: "completed",
257 title: null,
258 startedAt: input.completedAt,
259 completedAt: input.completedAt,
260 updatedAt: input.completedAt,
261 type: "checkpoint",
262 checkpointId: input.checkpoint.id,
263 scopeId: input.checkpoint.scopeId,
264 files: input.checkpoint.files,
265 };