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

CheckpointCaptureService.ts

278 lines9.8 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 * as CheckpointService from "./CheckpointService.ts";
19import * as EventSink from "./EventSink.ts";
20import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
21import * as ProjectionStore 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 | CheckpointService.CheckpointServiceV2
52 | EventSink.EventSinkV2
53 | IdAllocator.IdAllocatorV2
54 | ProjectionStore.ProjectionStoreV2
55> = Layer.effect(
56 CheckpointCaptureServiceV2,
57 Effect.gen(function* () {
58 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
59 const eventSink = yield* EventSink.EventSinkV2;
60 const ids = yield* IdAllocator.IdAllocatorV2;
61 const projections = yield* ProjectionStore.ProjectionStoreV2;
62​
63 const execute = Effect.fn("orchestrationV2.checkpointCapture.execute")(function* (input: {
64 readonly threadId: ThreadId;
65 readonly runId: RunId;
66 readonly scopeId: CheckpointScopeId;
67 }) {
68 const { run, rootNode, scope, providerThread, readyCheckpointOrdinals } =
69 yield* projections.getCheckpointCaptureContext(input.threadId, input);
70 // Stopped runs remain terminal; their checkpoint is the next message's rollback point.
71 const stopped = run?.status === "interrupted" || run?.status === "cancelled";
72​
73 // A checkpoint on a settled run proves this at-least-once effect already committed.
74 if (
75 run !== undefined &&
76 run.checkpointId !== null &&
77 (run.status === "completed" || stopped)
78 ) {
79 return;
80 }
81 // Rollback uses the same lane and can precede a capture retry; preserve the restored workspace and discarded run.
82 if (run?.status === "rolled_back") {
83 return;
84 }
85​
86 if (
87 run === undefined ||
88 (run.status !== "waiting" && !stopped) ||
89 rootNode === undefined ||
90 scope === undefined ||
91 rootNode.checkpointScopeId !== scope.id ||
92 providerThread === undefined
93 ) {
94 return yield* new CheckpointCaptureExecutionError({
95 threadId: input.threadId,
96 runId: input.runId,
97 scopeId: input.scopeId,
98 cause: "The persisted checkpoint capture target is incomplete or no longer waiting.",
99 });
100 }
101​
102 const capturedAt = yield* DateTime.now;
103 const baselineOrdinalWithinScope = Math.max(0, run.ordinal - 1);
104 const hasReadyCheckpoint = (ordinalWithinScope: number) =>
105 readyCheckpointOrdinals.includes(ordinalWithinScope);
106 const threadStartCheckpoint =
107 baselineOrdinalWithinScope === 0 || hasReadyCheckpoint(0)
108 ? null
109 : yield* checkpoints.materializeBaselineCheckpoint({
110 scope,
111 ordinalWithinScope: 0,
112 });
113 const baselineCheckpoint = hasReadyCheckpoint(baselineOrdinalWithinScope)
114 ? null
115 : yield* checkpoints.materializeBaselineCheckpoint({
116 scope,
117 ordinalWithinScope: baselineOrdinalWithinScope,
118 });
119 const checkpoint = yield* checkpoints.capture({
120 scope,
121 runId: run.id,
122 nodeId: rootNode.id,
123 ordinalWithinScope: run.ordinal,
124 appRunOrdinal: run.ordinal,
125 capturedAt,
126 });
127 // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run.
128 const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;
129 const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
130 yield* eventSink.commitCommand({
131 commandId,
132 threadId: input.threadId,
133 commandType: "checkpoint.capture",
134 acceptedAt: capturedAt,
135 effects: [],
136 events: [
137 ...(threadStartCheckpoint === null
138 ? []
139 : [
140 {
141 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
142 type: "checkpoint.captured" as const,
143 threadId: input.threadId,
144 nodeId: threadStartCheckpoint.nodeId,
145 driver: providerThread.driver,
146 providerInstanceId: run.providerInstanceId,
147 occurredAt: capturedAt,
148 payload: threadStartCheckpoint,
149 },
150 ]),
151 ...(baselineCheckpoint === null
152 ? []
153 : [
154 {
155 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
156 type: "checkpoint.captured" as const,
157 threadId: input.threadId,
158 nodeId: baselineCheckpoint.nodeId,
159 driver: providerThread.driver,
160 providerInstanceId: run.providerInstanceId,
161 occurredAt: capturedAt,
162 payload: baselineCheckpoint,
163 },
164 ]),
165 {
166 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
167 type: "checkpoint.captured",
168 threadId: input.threadId,
169 runId: run.id,
170 nodeId: rootNode.id,
171 driver: providerThread.driver,
172 providerInstanceId: run.providerInstanceId,
173 occurredAt: capturedAt,
174 payload: checkpoint,
175 },
176 {
177 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
178 type: "turn-item.updated",
179 threadId: input.threadId,
180 runId: run.id,
181 nodeId: rootNode.id,
182 driver: providerThread.driver,
183 providerInstanceId: run.providerInstanceId,
184 occurredAt: capturedAt,
185 payload: makeCheckpointTurnItem({
186 idAllocator: ids,
187 run,
188 rootNode,
189 providerThread,
190 checkpoint,
191 completedAt: capturedAt,
192 }),
193 },
194 {
195 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
196 type: "run.updated",
197 threadId: input.threadId,
198 runId: run.id,
199 nodeId: rootNode.id,
200 providerInstanceId: run.providerInstanceId,
201 occurredAt: capturedAt,
202 payload: stopped
203 ? { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id }
204 : {
205 ...runWithoutDelegatedCompletion,
206 status: "completed",
207 completedAt: capturedAt,
208 checkpointId: checkpoint.id,
209 },
210 },
211 ...(stopped
212 ? []
213 : [
214 {
215 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
216 type: "node.updated" as const,
217 threadId: input.threadId,
218 runId: run.id,
219 nodeId: rootNode.id,
220 providerInstanceId: run.providerInstanceId,
221 occurredAt: capturedAt,
222 payload: {
223 ...rootNode,
224 status: "completed" as const,
225 completedAt: capturedAt,
226 checkpointScopeId: scope.id,
227 },
228 },
229 ]),
230 ],
231 });
232 });
233​
234 return CheckpointCaptureServiceV2.of({
235 execute: (input) =>
236 execute(input).pipe(
237 Effect.mapError((cause) =>
238 isCheckpointCaptureExecutionError(cause)
239 ? cause
240 : new CheckpointCaptureExecutionError({ ...input, cause }),
241 ),
242 ),
243 });
244 }),
245);
246​
247function makeCheckpointTurnItem(input: {
248 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
249 readonly run: OrchestrationV2Run;
250 readonly rootNode: OrchestrationV2ExecutionNode;
251 readonly providerThread: OrchestrationV2ProviderThread;
252 readonly checkpoint: OrchestrationV2Checkpoint;
253 readonly completedAt: DateTime.Utc;
254}): OrchestrationV2TurnItem {
255 return {
256 id: input.idAllocator.derive.turnItemFromProviderItem({
257 driver: input.providerThread.driver,
258 nativeItemId: `checkpoint:${input.checkpoint.id}`,
259 }),
260 threadId: input.run.threadId,
261 runId: input.run.id,
262 nodeId: input.rootNode.id,
263 providerThreadId: input.providerThread.id,
264 providerTurnId: input.rootNode.providerTurnId,
265 nativeItemRef: null,
266 parentItemId: null,
267 ordinal: input.run.ordinal * 100 + 99,
268 status: "completed",
269 title: null,
270 startedAt: input.completedAt,
271 completedAt: input.completedAt,
272 updatedAt: input.completedAt,
273 type: "checkpoint",
274 checkpointId: input.checkpoint.id,
275 scopeId: input.checkpoint.scopeId,
276 files: input.checkpoint.files,
277 };