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

CheckpointCaptureService.ts

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