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

CheckpointCaptureService.ts

458 lines18.3 KB

1import {
2 CheckpointScopeId,
3 CommandId,
4 type OrchestrationV2Checkpoint,
5 type OrchestrationV2CheckpointScope,
6 type OrchestrationV2ExecutionNode,
7 type OrchestrationV2ProviderThread,
8 type OrchestrationV2Run,
9 type OrchestrationV2TurnItem,
10 RunId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Context from "effect/Context";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Schema from "effect/Schema";
19​
20import * as CheckpointService from "./CheckpointService.ts";
21import * as EventSink from "./EventSink.ts";
22import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
23import * as ProjectionStore from "./ProjectionStore.ts";
24import { makeInterruptResultTurnItem } from "./runInterruptResult.ts";
25import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
26​
27// Git processes are already capped server-wide; this keeps one thread from taking every slot.
28const REPOSITORY_CAPTURE_CONCURRENCY = 6;
29​
30export class CheckpointCaptureExecutionError extends Schema.TaggedError<CheckpointCaptureExecutionError>()(
31 "CheckpointCaptureExecutionError",
32 {
33 threadId: ThreadId,
34 runId: RunId,
35 scopeId: CheckpointScopeId,
36 cause: Schema.optional(Schema.Defect()),
37 },
38) {}
39​
40const isCheckpointCaptureExecutionError = Schema.is(CheckpointCaptureExecutionError);
41​
42export interface CheckpointCaptureServiceV2Shape {
43 readonly execute: (input: {
44 readonly threadId: ThreadId;
45 readonly runId: RunId;
46 readonly scopeId: CheckpointScopeId;
47 }) => Effect.Effect<void, CheckpointCaptureExecutionError>;
49​
50export class CheckpointCaptureServiceV2 extends Context.Service<
51 CheckpointCaptureServiceV2,
52 CheckpointCaptureServiceV2Shape
53>()("t3/orchestration-v2/CheckpointCaptureService/CheckpointCaptureServiceV2") {}
54​
55export const layer: Layer.Layer<
56 CheckpointCaptureServiceV2,
57 never,
58 | CheckpointService.CheckpointServiceV2
59 | EventSink.EventSinkV2
60 | IdAllocator.IdAllocatorV2
61 | ProjectionStore.ProjectionStoreV2
62 | ThreadCommandExecutor.ThreadCommandExecutor
63> = Layer.effect(
64 CheckpointCaptureServiceV2,
65 Effect.gen(function* () {
66 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
67 const eventSink = yield* EventSink.EventSinkV2;
68 const ids = yield* IdAllocator.IdAllocatorV2;
69 const projections = yield* ProjectionStore.ProjectionStoreV2;
70 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
71​
72 const execute = Effect.fn("orchestrationV2.checkpointCapture.execute")(function* (input: {
73 readonly threadId: ThreadId;
74 readonly runId: RunId;
75 readonly scopeId: CheckpointScopeId;
76 }) {
77 const context = yield* projections.getCheckpointCaptureContext(input.threadId, input, {
78 preservedCheckpoints: "baselines",
79 });
80 const { run, rootNode, scope, providerThread, preservedCheckpointOrdinals, sideChat } =
81 context;
82 // Runs settle before capture; `waiting` is a run persisted before captures ran after settling.
83 const settled =
84 run?.status === "completed" || run?.status === "interrupted" || run?.status === "cancelled";
85​
86 // A checkpoint on a settled run proves this at-least-once effect already committed.
87 if (run !== undefined && run.checkpointId !== null && settled) {
88 return;
89 }
90 // Rollback uses the same lane and can precede a capture retry; preserve the restored workspace and discarded run.
91 if (run?.status === "rolled_back") {
92 return;
93 }
94​
95 if (
96 run === undefined ||
97 (run.status !== "waiting" && !settled) ||
98 rootNode === undefined ||
99 scope === undefined ||
100 rootNode.checkpointScopeId !== scope.id ||
101 providerThread === undefined
102 ) {
103 return yield* new CheckpointCaptureExecutionError({
104 threadId: input.threadId,
105 runId: input.runId,
106 scopeId: input.scopeId,
107 cause: "The persisted checkpoint capture target is incomplete or was discarded.",
108 });
109 }
110​
111 const capturedAt = yield* DateTime.now;
112 const baselineOrdinalWithinScope = Math.max(0, run.ordinal - 1);
113 const isPreserved = (ordinalWithinScope: number) =>
114 preservedCheckpointOrdinals.includes(ordinalWithinScope);
115 // The baselines this capture materializes are attributed to the run materializing them. The
116 // thread's scope may already be a later run's: one queued meanwhile, or sent after Stop.
117 const materializeBaseline = (ordinalWithinScope: number) =>
118 checkpoints.materializeBaselineCheckpoint({
119 scope,
120 ordinalWithinScope,
121 nodeId: rootNode.id,
122 capturedAt: run.requestedAt,
123 forceMissing: sideChat,
124 });
125 // The tracked Git folders the thread reaches now. One added since the turn began has no
126 // baseline, so its first checkpoint lists no files; one removed is simply not captured.
127 const repositoryScopes =
128 sideChat || context.thread === undefined
129 ? []
130 : yield* checkpoints.repositoryScopes({ rootScope: scope, ...context.thread });
131 const nested =
132 repositoryScopes.length === 0
133 ? undefined
134 : yield* checkpoints.nestedScopePaths([scope, ...repositoryScopes]);
135 const excluded = (target: OrchestrationV2CheckpointScope) => {
136 const excludePaths = nested?.get(target.id);
137 return excludePaths === undefined ? {} : { excludePaths };
138 };
139 // Each scope is checked on its own, so a retried capture fills only what is missing.
140 const captureRoot = Effect.gen(function* () {
141 // Materializing a baseline waits on the folder's lock before the capture does.
142 const capturesBeforeLock = yield* checkpoints.capturesSoFar(scope.cwd);
143 const threadStartCheckpoint =
144 baselineOrdinalWithinScope === 0 || isPreserved(0) ? null : yield* materializeBaseline(0);
145 const baselineCheckpoint = isPreserved(baselineOrdinalWithinScope)
146 ? null
147 : yield* materializeBaseline(baselineOrdinalWithinScope);
148 const checkpoint = yield* checkpoints.capture({
149 scope,
150 runId: run.id,
151 nodeId: rootNode.id,
152 ordinalWithinScope: run.ordinal,
153 appRunOrdinal: run.ordinal,
154 capturedAt,
155 forceMissing: sideChat,
156 capturesBeforeLock,
157 ...excluded(scope),
158 });
159 return { threadStartCheckpoint, baselineCheckpoint, checkpoint };
160 });
161 const recordedScopes = new Map(
162 context.repositoryScopes.map((recorded) => [recorded.id, recorded]),
163 );
164 const captureRepository = Effect.fnUntraced(function* (
165 prepared: OrchestrationV2CheckpointScope,
166 ) {
167 const recorded = recordedScopes.get(prepared.id);
168 // A recorded scope keeps the run that first used it; only a renamed folder rewrites it.
169 const changed =
170 recorded === undefined ||
171 recorded.cwd !== prepared.cwd ||
172 recorded.label !== prepared.label;
173 const target =
174 recorded === undefined
175 ? prepared
176 : changed
177 ? {
178 ...prepared,
179 runId: recorded.runId,
180 nodeId: recorded.nodeId,
181 createdAt: recorded.createdAt,
182 }
183 : recorded;
184 const captured = yield* checkpoints.captureRepository({
185 scope: target,
186 runId: run.id,
187 nodeId: rootNode.id,
188 ordinalWithinScope: run.ordinal,
189 capturedAt,
190 baselineCapturedAt: run.requestedAt,
191 baselineRecorded: context.repositoryScopesWithBaseline.includes(target.id),
192 ...excluded(target),
193 });
194 // Only a repository with something to show is recorded, so the rest cost no events,
195 // rows or bytes on the wire.
196 return Option.match(captured, {
197 onNone: () => [],
198 onSome: (capture) => [{ scope: changed ? target : null, ...capture }],
199 });
200 });
201 const [{ threadStartCheckpoint, baselineCheckpoint, checkpoint }, repositoryCaptures] =
202 yield* Effect.all(
203 [
204 captureRoot,
205 Effect.forEach(repositoryScopes, captureRepository, {
206 concurrency: REPOSITORY_CAPTURE_CONCURRENCY,
207 }),
208 ],
209 { concurrency: 2 },
210 );
211 const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
212 const checkpointEvent = (payload: OrchestrationV2Checkpoint) =>
213 Effect.map(ids.allocate.event({ threadId: input.threadId, commandId }), (id) => ({
214 id,
215 type: "checkpoint.captured" as const,
216 threadId: input.threadId,
217 ...(payload.runId === null ? {} : { runId: payload.runId }),
218 nodeId: payload.nodeId,
219 driver: providerThread.driver,
220 providerInstanceId: run.providerInstanceId,
221 occurredAt: capturedAt,
222 payload,
223 }));
224 const repositoryEvents = yield* Effect.forEach(repositoryCaptures.flat(), (capture) =>
225 Effect.gen(function* () {
226 return [
227 ...(capture.scope === null
228 ? []
229 : [
230 {
231 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
232 type: "checkpoint-scope.created" as const,
233 threadId: input.threadId,
234 runId: run.id,
235 nodeId: rootNode.id,
236 providerInstanceId: run.providerInstanceId,
237 occurredAt: capturedAt,
238 payload: capture.scope,
239 },
240 ]),
241 ...(capture.baseline === null ? [] : [yield* checkpointEvent(capture.baseline)]),
242 yield* checkpointEvent(capture.checkpoint),
243 ];
244 }),
245 );
246 // Stop and deletion may commit while Git captures; reread under their lock before finalizing.
247 yield* threadCommands.withLock(
248 input.threadId,
249 Effect.gen(function* () {
250 const { runs } = yield* projections.getThreadRecords(input.threadId, ["runs"], {
251 runIds: [run.id],
252 });
253 const currentRun = runs[0];
254 if (currentRun === undefined || currentRun.activeAttemptId !== run.activeAttemptId) {
255 return;
256 }
257 const legacyWaiting = currentRun.status === "waiting";
258 if (
259 !legacyWaiting &&
260 currentRun.status !== "completed" &&
261 currentRun.status !== "interrupted" &&
262 currentRun.status !== "cancelled"
263 ) {
264 return;
265 }
266 // A Stop accepted once the provider's turn had ended stored only its request: the
267 // terminal already wrote `completed` (or legacy `waiting`). That Stop still wins here.
268 const stopSignals =
269 !legacyWaiting && currentRun.status !== "completed"
270 ? []
271 : (yield* projections.getThreadRecords(input.threadId, ["turnItems"], {
272 turnItemTypes: ["run_interrupt_request", "run_interrupt_result"],
273 turnItemRunIds: [run.id],
274 })).turnItems;
275 const stopRequest = stopSignals.some((item) => item.type === "run_interrupt_result")
276 ? undefined
277 : stopSignals.find((item) => item.type === "run_interrupt_request");
278 const settledStatus =
279 stopRequest === undefined ? ("completed" as const) : ("interrupted" as const);
280 const settlesRun = legacyWaiting || stopRequest !== undefined;
281 // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run.
282 const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } =
283 currentRun;
284 yield* eventSink.commitCommand({
285 commandId,
286 threadId: input.threadId,
287 commandType: "checkpoint.capture",
288 acceptedAt: capturedAt,
289 effects: [],
290 events: [
291 // Root records come last: a client that takes the latest ordinal-0 baseline gets the thread's.
292 ...repositoryEvents.flat(),
293 ...(threadStartCheckpoint === null
294 ? []
295 : [
296 {
297 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
298 type: "checkpoint.captured" as const,
299 threadId: input.threadId,
300 nodeId: threadStartCheckpoint.nodeId,
301 driver: providerThread.driver,
302 providerInstanceId: run.providerInstanceId,
303 occurredAt: capturedAt,
304 payload: threadStartCheckpoint,
305 },
306 ]),
307 ...(baselineCheckpoint === null
308 ? []
309 : [
310 {
311 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
312 type: "checkpoint.captured" as const,
313 threadId: input.threadId,
314 nodeId: baselineCheckpoint.nodeId,
315 driver: providerThread.driver,
316 providerInstanceId: run.providerInstanceId,
317 occurredAt: capturedAt,
318 payload: baselineCheckpoint,
319 },
320 ]),
321 {
322 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
323 type: "checkpoint.captured",
324 threadId: input.threadId,
325 runId: run.id,
326 nodeId: rootNode.id,
327 driver: providerThread.driver,
328 providerInstanceId: run.providerInstanceId,
329 occurredAt: capturedAt,
330 payload: checkpoint,
331 },
332 {
333 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
334 type: "turn-item.updated",
335 threadId: input.threadId,
336 runId: run.id,
337 nodeId: rootNode.id,
338 driver: providerThread.driver,
339 providerInstanceId: run.providerInstanceId,
340 occurredAt: capturedAt,
341 payload: makeCheckpointTurnItem({
342 idAllocator: ids,
343 run,
344 rootNode,
345 providerThread,
346 checkpoint,
347 completedAt: capturedAt,
348 }),
349 },
350 ...(stopRequest?.type !== "run_interrupt_request"
351 ? []
352 : [
353 {
354 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
355 type: "turn-item.updated" as const,
356 threadId: input.threadId,
357 runId: run.id,
358 nodeId: rootNode.id,
359 providerInstanceId: run.providerInstanceId,
360 occurredAt: capturedAt,
361 payload: makeInterruptResultTurnItem({
362 idAllocator: ids,
363 run,
364 rootNode,
365 providerThread,
366 reason: stopRequest.message,
367 completedAt: capturedAt,
368 }),
369 },
370 ]),
371 {
372 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
373 type: "run.updated",
374 threadId: input.threadId,
375 runId: run.id,
376 nodeId: rootNode.id,
377 providerInstanceId: run.providerInstanceId,
378 occurredAt: capturedAt,
379 payload: settlesRun
380 ? {
381 ...runWithoutDelegatedCompletion,
382 status: settledStatus,
383 completedAt: capturedAt,
384 checkpointId: checkpoint.id,
385 }
386 : { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id },
387 },
388 ...(!settlesRun
389 ? []
390 : [
391 {
392 id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
393 type: "node.updated" as const,
394 threadId: input.threadId,
395 runId: run.id,
396 nodeId: rootNode.id,
397 providerInstanceId: run.providerInstanceId,
398 occurredAt: capturedAt,
399 payload: {
400 ...rootNode,
401 status: settledStatus,
402 completedAt: capturedAt,
403 checkpointScopeId: scope.id,
404 },
405 },
406 ]),
407 ],
408 });
409 }),
410 );
411 });
412​
413 return CheckpointCaptureServiceV2.of({
414 execute: Effect.fn("CheckpointCaptureServiceV2.execute")(function (input) {
415 return execute(input).pipe(
416 Effect.mapError((cause) =>
417 isCheckpointCaptureExecutionError(cause)
418 ? cause
419 : new CheckpointCaptureExecutionError({ ...input, cause }),
420 ),
421 );
422 }),
423 });
424 }),
425);
426​
427function makeCheckpointTurnItem(input: {
428 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
429 readonly run: OrchestrationV2Run;
430 readonly rootNode: OrchestrationV2ExecutionNode;
431 readonly providerThread: OrchestrationV2ProviderThread;
432 readonly checkpoint: OrchestrationV2Checkpoint;
433 readonly completedAt: DateTime.Utc;
434}): OrchestrationV2TurnItem {
435 return {
436 id: input.idAllocator.derive.turnItemFromProviderItem({
437 driver: input.providerThread.driver,
438 nativeItemId: `checkpoint:${input.checkpoint.id}`,
439 }),
440 threadId: input.run.threadId,
441 runId: input.run.id,
442 nodeId: input.rootNode.id,
443 providerThreadId: input.providerThread.id,
444 providerTurnId: input.rootNode.providerTurnId,
445 nativeItemRef: null,
446 parentItemId: null,
447 ordinal: input.run.ordinal * 100 + 99,
448 status: "completed",
449 title: null,
450 startedAt: input.completedAt,
451 completedAt: input.completedAt,
452 updatedAt: input.completedAt,
453 type: "checkpoint",
454 checkpointId: input.checkpoint.id,
455 scopeId: input.checkpoint.scopeId,
456 files: input.checkpoint.files,
457 };