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

CheckpointCaptureService.ts

263 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.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>;
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 { run, rootNode, scope, providerThread, readyCheckpointOrdinals } =
66 yield* projections.getCheckpointCaptureContext(input.threadId, input);
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 if (
75 run === undefined ||
76 run.status !== "waiting" ||
77 rootNode === undefined ||
78 scope === undefined ||
79 rootNode.checkpointScopeId !== scope.id ||
80 providerThread === undefined
81 ) {
82 return yield* new CheckpointCaptureExecutionError({
83 threadId: input.threadId,
84 runId: input.runId,
85 scopeId: input.scopeId,
86 cause: "The persisted checkpoint capture target is incomplete or no longer waiting.",
87 });
88 }
89​
90 const capturedAt = yield* DateTime.now;
91 const baselineOrdinalWithinScope = Math.max(0, run.ordinal - 1);
92 const hasReadyCheckpoint = (ordinalWithinScope: number) =>
93 readyCheckpointOrdinals.includes(ordinalWithinScope);
94 const threadStartCheckpoint =
95 baselineOrdinalWithinScope === 0 || hasReadyCheckpoint(0)
96 ? null
97 : yield* checkpoints.materializeBaselineCheckpoint({
98 scope,
99 ordinalWithinScope: 0,
100 });
101 const baselineCheckpoint = hasReadyCheckpoint(baselineOrdinalWithinScope)
102 ? null
103 : yield* checkpoints.materializeBaselineCheckpoint({
104 scope,
105 ordinalWithinScope: baselineOrdinalWithinScope,
106 });
107 const checkpoint = yield* checkpoints.capture({
108 scope,
109 runId: run.id,
110 nodeId: rootNode.id,
111 ordinalWithinScope: run.ordinal,
112 appRunOrdinal: run.ordinal,
113 capturedAt,
114 });
115 // Match RunExecutionService: capture loaded the waiting run before
116 // materializing baselines. Omit delegatedCompletion so a newer cohort
117 // write during capture is not overwritten by this stale snapshot
118 // (ProjectionStore preserves the field when absent from the payload).
119 const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;
120 const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
121 yield* eventSink.commitCommand({
122 commandId,
123 threadId: input.threadId,
124 commandType: "checkpoint.capture",
125 acceptedAt: capturedAt,
126 effects: [],
127 events: [
128 ...(threadStartCheckpoint === null
129 ? []
130 : [
131 {
132 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
133 type: "checkpoint.captured" as const,
134 threadId: input.threadId,
135 nodeId: threadStartCheckpoint.nodeId,
136 driver: providerThread.driver,
137 providerInstanceId: run.providerInstanceId,
138 occurredAt: capturedAt,
139 payload: threadStartCheckpoint,
140 },
141 ]),
142 ...(baselineCheckpoint === null
143 ? []
144 : [
145 {
146 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
147 type: "checkpoint.captured" as const,
148 threadId: input.threadId,
149 nodeId: baselineCheckpoint.nodeId,
150 driver: providerThread.driver,
151 providerInstanceId: run.providerInstanceId,
152 occurredAt: capturedAt,
153 payload: baselineCheckpoint,
154 },
155 ]),
156 {
157 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
158 type: "checkpoint.captured",
159 threadId: input.threadId,
160 runId: run.id,
161 nodeId: rootNode.id,
162 driver: providerThread.driver,
163 providerInstanceId: run.providerInstanceId,
164 occurredAt: capturedAt,
165 payload: checkpoint,
166 },
167 {
168 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
169 type: "turn-item.updated",
170 threadId: input.threadId,
171 runId: run.id,
172 nodeId: rootNode.id,
173 driver: providerThread.driver,
174 providerInstanceId: run.providerInstanceId,
175 occurredAt: capturedAt,
176 payload: makeCheckpointTurnItem({
177 idAllocator: ids,
178 run,
179 rootNode,
180 providerThread,
181 checkpoint,
182 completedAt: capturedAt,
183 }),
184 },
185 {
186 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
187 type: "run.updated",
188 threadId: input.threadId,
189 runId: run.id,
190 nodeId: rootNode.id,
191 providerInstanceId: run.providerInstanceId,
192 occurredAt: capturedAt,
193 payload: {
194 ...runWithoutDelegatedCompletion,
195 status: "completed",
196 completedAt: capturedAt,
197 checkpointId: checkpoint.id,
198 },
199 },
200 {
201 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
202 type: "node.updated",
203 threadId: input.threadId,
204 runId: run.id,
205 nodeId: rootNode.id,
206 providerInstanceId: run.providerInstanceId,
207 occurredAt: capturedAt,
208 payload: {
209 ...rootNode,
210 status: "completed",
211 completedAt: capturedAt,
212 checkpointScopeId: scope.id,
213 },
214 },
215 ],
216 });
217 });
218​
219 return CheckpointCaptureServiceV2.of({
220 execute: (input) =>
221 execute(input).pipe(
222 Effect.mapError((cause) =>
223 isCheckpointCaptureExecutionError(cause)
224 ? cause
225 : new CheckpointCaptureExecutionError({ ...input, cause }),
226 ),
227 ),
228 });
229 }),
230);
231​
232function makeCheckpointTurnItem(input: {
233 readonly idAllocator: IdAllocatorV2Shape;
234 readonly run: OrchestrationV2Run;
235 readonly rootNode: OrchestrationV2ExecutionNode;
236 readonly providerThread: OrchestrationV2ProviderThread;
237 readonly checkpoint: OrchestrationV2Checkpoint;
238 readonly completedAt: DateTime.Utc;
239}): OrchestrationV2TurnItem {
240 return {
241 id: input.idAllocator.derive.turnItemFromProviderItem({
242 driver: input.providerThread.driver,
243 nativeItemId: `checkpoint:${input.checkpoint.id}`,
244 }),
245 threadId: input.run.threadId,
246 runId: input.run.id,
247 nodeId: input.rootNode.id,
248 providerThreadId: input.providerThread.id,
249 providerTurnId: input.rootNode.providerTurnId,
250 nativeItemRef: null,
251 parentItemId: null,
252 ordinal: input.run.ordinal * 100 + 99,
253 status: "completed",
254 title: null,
255 startedAt: input.completedAt,
256 completedAt: input.completedAt,
257 updatedAt: input.completedAt,
258 type: "checkpoint",
259 checkpointId: input.checkpoint.id,
260 scopeId: input.checkpoint.scopeId,
261 files: input.checkpoint.files,
262 };