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 * 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>;
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 | 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, sideChat } =
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 // The baselines this capture materializes are attributed to the run materializing them. The
107 // thread's scope may already be a later run's: one queued meanwhile, or sent after Stop.
108 const materializeBaseline = (ordinalWithinScope: number) =>
109 checkpoints.materializeBaselineCheckpoint({
110 scope,
111 ordinalWithinScope,
112 nodeId: rootNode.id,
113 capturedAt: run.requestedAt,
114 forceMissing: sideChat,
115 });
116 const threadStartCheckpoint =
117 baselineOrdinalWithinScope === 0 || hasReadyCheckpoint(0)
118 ? null
119 : yield* materializeBaseline(0);
120 const baselineCheckpoint = hasReadyCheckpoint(baselineOrdinalWithinScope)
121 ? null
122 : yield* materializeBaseline(baselineOrdinalWithinScope);
123 const checkpoint = yield* checkpoints.capture({
124 scope,
125 runId: run.id,
126 nodeId: rootNode.id,
127 ordinalWithinScope: run.ordinal,
128 appRunOrdinal: run.ordinal,
129 capturedAt,
130 forceMissing: sideChat,
131 });
132 // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run.
133 const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;
134 const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
135 yield* eventSink.commitCommand({
136 commandId,
137 threadId: input.threadId,
138 commandType: "checkpoint.capture",
139 acceptedAt: capturedAt,
140 effects: [],
141 events: [
142 ...(threadStartCheckpoint === 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: threadStartCheckpoint.nodeId,
150 driver: providerThread.driver,
151 providerInstanceId: run.providerInstanceId,
152 occurredAt: capturedAt,
153 payload: threadStartCheckpoint,
154 },
155 ]),
156 ...(baselineCheckpoint === null
157 ? []
158 : [
159 {
160 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
161 type: "checkpoint.captured" as const,
162 threadId: input.threadId,
163 nodeId: baselineCheckpoint.nodeId,
164 driver: providerThread.driver,
165 providerInstanceId: run.providerInstanceId,
166 occurredAt: capturedAt,
167 payload: baselineCheckpoint,
168 },
169 ]),
170 {
171 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
172 type: "checkpoint.captured",
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: checkpoint,
180 },
181 {
182 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
183 type: "turn-item.updated",
184 threadId: input.threadId,
185 runId: run.id,
186 nodeId: rootNode.id,
187 driver: providerThread.driver,
188 providerInstanceId: run.providerInstanceId,
189 occurredAt: capturedAt,
190 payload: makeCheckpointTurnItem({
191 idAllocator: ids,
192 run,
193 rootNode,
194 providerThread,
195 checkpoint,
196 completedAt: capturedAt,
197 }),
198 },
199 {
200 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
201 type: "run.updated",
202 threadId: input.threadId,
203 runId: run.id,
204 nodeId: rootNode.id,
205 providerInstanceId: run.providerInstanceId,
206 occurredAt: capturedAt,
207 payload: stopped
208 ? { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id }
209 : {
210 ...runWithoutDelegatedCompletion,
211 status: "completed",
212 completedAt: capturedAt,
213 checkpointId: checkpoint.id,
214 },
215 },
216 ...(stopped
217 ? []
218 : [
219 {
220 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
221 type: "node.updated" as const,
222 threadId: input.threadId,
223 runId: run.id,
224 nodeId: rootNode.id,
225 providerInstanceId: run.providerInstanceId,
226 occurredAt: capturedAt,
227 payload: {
228 ...rootNode,
229 status: "completed" as const,
230 completedAt: capturedAt,
231 checkpointScopeId: scope.id,
232 },
233 },
234 ]),
235 ],
236 });
237 });
238
239 return CheckpointCaptureServiceV2.of({
240 execute: Effect.fn("CheckpointCaptureServiceV2.execute")(function (input) {
241 return execute(input).pipe(
242 Effect.mapError((cause) =>
243 isCheckpointCaptureExecutionError(cause)
244 ? cause
245 : new CheckpointCaptureExecutionError({ ...input, cause }),
246 ),
247 );
248 }),
249 });
250 }),
251);
252
253function makeCheckpointTurnItem(input: {
254 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
255 readonly run: OrchestrationV2Run;
256 readonly rootNode: OrchestrationV2ExecutionNode;
257 readonly providerThread: OrchestrationV2ProviderThread;
258 readonly checkpoint: OrchestrationV2Checkpoint;
259 readonly completedAt: DateTime.Utc;
260}): OrchestrationV2TurnItem {
261 return {
262 id: input.idAllocator.derive.turnItemFromProviderItem({
263 driver: input.providerThread.driver,
264 nativeItemId: `checkpoint:${input.checkpoint.id}`,
265 }),
266 threadId: input.run.threadId,
267 runId: input.run.id,
268 nodeId: input.rootNode.id,
269 providerThreadId: input.providerThread.id,
270 providerTurnId: input.rootNode.providerTurnId,
271 nativeItemRef: null,
272 parentItemId: null,
273 ordinal: input.run.ordinal * 100 + 99,
274 status: "completed",
275 title: null,
276 startedAt: input.completedAt,
277 completedAt: input.completedAt,
278 updatedAt: input.completedAt,
279 type: "checkpoint",
280 checkpointId: input.checkpoint.id,
281 scopeId: input.checkpoint.scopeId,
282 files: input.checkpoint.files,
283 };
284}