Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointRef,
4 CheckpointScopeId,
5 NodeId,
6 OrchestrationV2Checkpoint,
7 OrchestrationV2CheckpointScope,
8 ProviderThreadId,
9 RunId,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as NodeCrypto from "node:crypto";
13import * as Context from "effect/Context";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Base64Url from "effect/encoding/Base64Url";
17import * as KeyedLock from "@t3tools/shared/KeyedLock";
18import * as Layer from "effect/Layer";
19import * as Schema from "effect/Schema";
20
21import { parseTurnDiffFilesFromNumstat } from "../checkpointing/Diffs.ts";
22import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
23import * as IdAllocator from "./IdAllocator.ts";
24
25const CHECKPOINT_REFS_PREFIX = "refs/t3/orchestration-v2/checkpoints";
26const ROOT_CHECKPOINT_SCOPE_NAME = "root";
27
28export class CheckpointRootScopePrepareError extends Schema.TaggedError<CheckpointRootScopePrepareError>()(
29 "CheckpointRootScopePrepareError",
30 {
31 threadId: ThreadId,
32 runId: RunId,
33 cause: Schema.Defect(),
34 },
35) {
36 override get message(): string {
37 return `Failed to prepare root checkpoint scope for run ${this.runId}.`;
38 }
39}
40
41export class CheckpointScopeEnsureError extends Schema.TaggedError<CheckpointScopeEnsureError>()(
42 "CheckpointScopeEnsureError",
43 {
44 scopeId: CheckpointScopeId,
45 cause: Schema.Defect(),
46 },
47) {
48 override get message(): string {
49 return `Failed to ensure checkpoint scope ${this.scopeId}.`;
50 }
51}
52
53export class CheckpointBaselineCaptureError extends Schema.TaggedError<CheckpointBaselineCaptureError>()(
54 "CheckpointBaselineCaptureError",
55 {
56 scopeId: CheckpointScopeId,
57 ordinalWithinScope: Schema.Number,
58 cause: Schema.Defect(),
59 },
60) {
61 override get message(): string {
62 return `Failed to capture checkpoint baseline ${this.ordinalWithinScope} for scope ${this.scopeId}.`;
63 }
64}
65
66export class CheckpointCaptureError extends Schema.TaggedError<CheckpointCaptureError>()(
67 "CheckpointCaptureError",
68 {
69 scopeId: CheckpointScopeId,
70 parentCheckpointId: Schema.optional(CheckpointId),
71 cause: Schema.Defect(),
72 },
73) {
74 override get message(): string {
75 return `Failed to capture checkpoint for scope ${this.scopeId}.`;
76 }
77}
78
79export class CheckpointRestoreError extends Schema.TaggedError<CheckpointRestoreError>()(
80 "CheckpointRestoreError",
81 {
82 scopeId: CheckpointScopeId,
83 checkpointId: CheckpointId,
84 cause: Schema.Defect(),
85 },
86) {
87 override get message(): string {
88 return `Failed to restore checkpoint ${this.checkpointId} for scope ${this.scopeId}.`;
89 }
90}
91
92export class CheckpointDeleteStaleRefsError extends Schema.TaggedError<CheckpointDeleteStaleRefsError>()(
93 "CheckpointDeleteStaleRefsError",
94 {
95 scopeId: CheckpointScopeId,
96 checkpointIds: Schema.Array(CheckpointId),
97 cause: Schema.Defect(),
98 },
99) {
100 override get message(): string {
101 return `Failed to delete stale checkpoint refs for scope ${this.scopeId}.`;
102 }
103}
104
105export const CheckpointServiceV2Error = Schema.Union([
106 CheckpointRootScopePrepareError,
107 CheckpointScopeEnsureError,
108 CheckpointBaselineCaptureError,
109 CheckpointCaptureError,
110 CheckpointRestoreError,
111 CheckpointDeleteStaleRefsError,
112]);
113export type CheckpointServiceV2Error = typeof CheckpointServiceV2Error.Type;
114
115const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);
116
117export interface CheckpointServiceV2Shape {
118 readonly prepareRootRunScope: (input: {
119 readonly threadId: ThreadId;
120 readonly runId: RunId;
121 readonly rootNodeId: NodeId;
122 readonly providerThreadId: ProviderThreadId;
123 readonly cwd: string;
124 readonly createdAt: DateTime.Utc;
125 }) => Effect.Effect<OrchestrationV2CheckpointScope, CheckpointServiceV2Error>;
126 readonly ensureScope: (
127 scope: OrchestrationV2CheckpointScope,
128 ) => Effect.Effect<OrchestrationV2CheckpointScope, CheckpointServiceV2Error>;
129 readonly captureBaseline: (input: {
130 readonly scope: OrchestrationV2CheckpointScope;
131 readonly ordinalWithinScope: number;
132 }) => Effect.Effect<void, CheckpointServiceV2Error>;
133 readonly materializeBaselineCheckpoint: (input: {
134 readonly scope: OrchestrationV2CheckpointScope;
135 readonly ordinalWithinScope: number;
136 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
137 readonly capture: (input: {
138 readonly scope: OrchestrationV2CheckpointScope;
139 readonly runId: RunId | null;
140 readonly nodeId: NodeId;
141 readonly ordinalWithinScope: number;
142 readonly appRunOrdinal: number | null;
143 readonly capturedAt: DateTime.Utc;
144 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
145 readonly restore: (input: {
146 readonly scope: OrchestrationV2CheckpointScope;
147 readonly checkpoint: OrchestrationV2Checkpoint;
148 }) => Effect.Effect<void, CheckpointServiceV2Error>;
149 readonly deleteStaleRefs: (input: {
150 readonly scope: OrchestrationV2CheckpointScope;
151 readonly checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>;
152 }) => Effect.Effect<void, CheckpointServiceV2Error>;
153}
154
155export class CheckpointServiceV2 extends Context.Service<
156 CheckpointServiceV2,
157 CheckpointServiceV2Shape
158>()("t3/orchestration-v2/CheckpointService/CheckpointServiceV2") {}
159
160export function checkpointRefForScopeOrdinal(input: {
161 readonly scopeId: CheckpointScopeId;
162 readonly ordinalWithinScope: number;
163}): CheckpointRef {
164 const scopeKey = NodeCrypto.createHash("sha256").update(input.scopeId).digest("hex").slice(0, 32);
165 return CheckpointRef.make(
166 `${CHECKPOINT_REFS_PREFIX}/${Base64Url.encode(scopeKey)}/ordinal/${input.ordinalWithinScope}`,
167 );
168}
169
170function checkpointIdForScopeOrdinal(
171 idAllocator: IdAllocator.IdAllocatorV2Shape,
172 input: {
173 readonly scopeId: CheckpointScopeId;
174 readonly ordinalWithinScope: number;
175 },
176) {
177 return idAllocator.allocate.checkpoint({
178 checkpointScopeId: input.scopeId,
179 name: String(input.ordinalWithinScope),
180 });
181}
182
183function makeRootRunScope(input: {
184 readonly idAllocator: IdAllocator.IdAllocatorV2Shape;
185 readonly threadId: ThreadId;
186 readonly runId: RunId;
187 readonly rootNodeId: NodeId;
188 readonly providerThreadId: ProviderThreadId;
189 readonly cwd: string;
190 readonly createdAt: DateTime.Utc;
191}) {
192 return Effect.gen(function* () {
193 const scopeId = yield* input.idAllocator.allocate.checkpointScope({
194 threadId: input.threadId,
195 name: ROOT_CHECKPOINT_SCOPE_NAME,
196 });
197 return {
198 id: scopeId,
199 threadId: input.threadId,
200 runId: input.runId,
201 nodeId: input.rootNodeId,
202 parentScopeId: null,
203 providerThreadId: input.providerThreadId,
204 kind: "root_run",
205 ordinalWithinParent: 0,
206 advancesAppRunCount: true,
207 cwd: input.cwd,
208 createdAt: input.createdAt,
209 } satisfies OrchestrationV2CheckpointScope;
210 });
211}
212
213function makeCheckpoint(input: {
214 readonly id: CheckpointId;
215 readonly scope: OrchestrationV2CheckpointScope;
216 readonly runId: RunId | null;
217 readonly nodeId: NodeId;
218 readonly parentCheckpointId: CheckpointId | null;
219 readonly ordinalWithinScope: number;
220 readonly appRunOrdinal: number | null;
221 readonly ref: CheckpointRef;
222 readonly status: OrchestrationV2Checkpoint["status"];
223 readonly files: OrchestrationV2Checkpoint["files"];
224 readonly capturedAt: DateTime.Utc;
225}): OrchestrationV2Checkpoint {
226 return {
227 id: input.id,
228 threadId: input.scope.threadId,
229 scopeId: input.scope.id,
230 runId: input.runId,
231 nodeId: input.nodeId,
232 parentCheckpointId: input.parentCheckpointId,
233 ordinalWithinScope: input.ordinalWithinScope,
234 appRunOrdinal: input.appRunOrdinal,
235 ref: input.ref,
236 status: input.status,
237 files: input.files,
238 capturedAt: input.capturedAt,
239 };
240}
241
242export const layer: Layer.Layer<
243 CheckpointServiceV2,
244 never,
245 CheckpointStore.CheckpointStore | IdAllocator.IdAllocatorV2
246> = Layer.effect(
247 CheckpointServiceV2,
248 Effect.gen(function* () {
249 const checkpointStore = yield* CheckpointStore.CheckpointStore;
250 const idAllocator = yield* IdAllocator.IdAllocatorV2;
251 const workspaceLocks = yield* KeyedLock.make<string>();
252 const withWorkspaceLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
253 workspaceLocks.withLock(cwd, effect);
254
255 const isGitCheckpointable = (cwd: string) =>
256 checkpointStore.isGitRepository(cwd).pipe(Effect.orElseSucceed(() => false));
257
258 const ensureScope: CheckpointServiceV2Shape["ensureScope"] = (scope) => Effect.succeed(scope);
259
260 const captureBaseline: CheckpointServiceV2Shape["captureBaseline"] = (input) =>
261 withWorkspaceLock(
262 input.scope.cwd,
263 Effect.gen(function* () {
264 if (!(yield* isGitCheckpointable(input.scope.cwd))) {
265 return;
266 }
267
268 const checkpointRef = checkpointRefForScopeOrdinal({
269 scopeId: input.scope.id,
270 ordinalWithinScope: input.ordinalWithinScope,
271 });
272 const exists = yield* checkpointStore.hasCheckpointRef({
273 cwd: input.scope.cwd,
274 checkpointRef,
275 });
276 if (exists) {
277 return;
278 }
279
280 yield* checkpointStore.captureCheckpoint({
281 cwd: input.scope.cwd,
282 checkpointRef,
283 });
284 }),
285 ).pipe(
286 Effect.mapError(
287 (cause) =>
288 new CheckpointBaselineCaptureError({
289 scopeId: input.scope.id,
290 ordinalWithinScope: input.ordinalWithinScope,
291 cause,
292 }),
293 ),
294 );
295
296 const materializeBaselineCheckpoint: CheckpointServiceV2Shape["materializeBaselineCheckpoint"] =
297 (input) =>
298 withWorkspaceLock(
299 input.scope.cwd,
300 Effect.gen(function* () {
301 const checkpointRef = checkpointRefForScopeOrdinal({
302 scopeId: input.scope.id,
303 ordinalWithinScope: input.ordinalWithinScope,
304 });
305 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
306 scopeId: input.scope.id,
307 ordinalWithinScope: input.ordinalWithinScope,
308 });
309 const checkpointable = yield* isGitCheckpointable(input.scope.cwd);
310 const available = checkpointable
311 ? yield* checkpointStore
312 .hasCheckpointRef({
313 cwd: input.scope.cwd,
314 checkpointRef,
315 })
316 .pipe(
317 Effect.catch((cause) =>
318 Effect.logWarning("orchestration V2 baseline ref lookup failed", {
319 scopeId: input.scope.id,
320 checkpointRef,
321 cause: String(cause),
322 }).pipe(Effect.as(false)),
323 ),
324 )
325 : false;
326 return makeCheckpoint({
327 id: checkpointId,
328 scope: input.scope,
329 runId: null,
330 nodeId: input.scope.nodeId,
331 parentCheckpointId: null,
332 ordinalWithinScope: input.ordinalWithinScope,
333 appRunOrdinal: null,
334 ref: checkpointRef,
335 status: available ? "ready" : "missing",
336 files: [],
337 capturedAt: input.scope.createdAt,
338 });
339 }),
340 ).pipe(
341 Effect.mapError(
342 (cause) =>
343 new CheckpointCaptureError({
344 scopeId: input.scope.id,
345 cause,
346 }),
347 ),
348 );
349
350 const capture: CheckpointServiceV2Shape["capture"] = (input) =>
351 withWorkspaceLock(
352 input.scope.cwd,
353 Effect.gen(function* () {
354 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
355 scopeId: input.scope.id,
356 ordinalWithinScope: input.ordinalWithinScope,
357 });
358 const parentCheckpointId =
359 input.ordinalWithinScope > 0
360 ? yield* checkpointIdForScopeOrdinal(idAllocator, {
361 scopeId: input.scope.id,
362 ordinalWithinScope: input.ordinalWithinScope - 1,
363 })
364 : null;
365 const checkpointRef = checkpointRefForScopeOrdinal({
366 scopeId: input.scope.id,
367 ordinalWithinScope: input.ordinalWithinScope,
368 });
369 const previousCheckpointRef = checkpointRefForScopeOrdinal({
370 scopeId: input.scope.id,
371 ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1),
372 });
373
374 if (!(yield* isGitCheckpointable(input.scope.cwd))) {
375 return makeCheckpoint({
376 id: checkpointId,
377 scope: input.scope,
378 runId: input.runId,
379 nodeId: input.nodeId,
380 parentCheckpointId,
381 ordinalWithinScope: input.ordinalWithinScope,
382 appRunOrdinal: input.appRunOrdinal,
383 ref: checkpointRef,
384 status: "missing",
385 files: [],
386 capturedAt: input.capturedAt,
387 });
388 }
389
390 const captured = yield* checkpointStore
391 .captureCheckpoint({
392 cwd: input.scope.cwd,
393 checkpointRef,
394 })
395 .pipe(
396 Effect.as(true),
397 Effect.catch((cause) =>
398 Effect.logWarning("orchestration V2 checkpoint capture failed", {
399 scopeId: input.scope.id,
400 checkpointRef,
401 cause: String(cause),
402 }).pipe(Effect.as(false)),
403 ),
404 );
405
406 if (!captured) {
407 return makeCheckpoint({
408 id: checkpointId,
409 scope: input.scope,
410 runId: input.runId,
411 nodeId: input.nodeId,
412 parentCheckpointId,
413 ordinalWithinScope: input.ordinalWithinScope,
414 appRunOrdinal: input.appRunOrdinal,
415 ref: checkpointRef,
416 status: "error",
417 files: [],
418 capturedAt: input.capturedAt,
419 });
420 }
421
422 const previousExists = yield* checkpointStore
423 .hasCheckpointRef({
424 cwd: input.scope.cwd,
425 checkpointRef: previousCheckpointRef,
426 })
427 .pipe(
428 Effect.catch((cause) =>
429 Effect.logWarning("orchestration V2 previous checkpoint ref lookup failed", {
430 scopeId: input.scope.id,
431 checkpointRef: previousCheckpointRef,
432 cause: String(cause),
433 }).pipe(Effect.as(false)),
434 ),
435 );
436 const files = previousExists
437 ? yield* checkpointStore
438 .diffCheckpoints({
439 cwd: input.scope.cwd,
440 fromCheckpointRef: previousCheckpointRef,
441 toCheckpointRef: checkpointRef,
442 fallbackFromToHead: false,
443 ignoreWhitespace: false,
444 format: "numstat",
445 })
446 .pipe(
447 Effect.map((diff) =>
448 parseTurnDiffFilesFromNumstat(diff).map((file) => ({
449 path: file.path,
450 kind: "modified",
451 additions: file.additions,
452 deletions: file.deletions,
453 })),
454 ),
455 Effect.catch((cause) =>
456 Effect.logWarning("orchestration V2 checkpoint diff summary failed", {
457 scopeId: input.scope.id,
458 checkpointRef,
459 cause: String(cause),
460 }).pipe(Effect.as([])),
461 ),
462 )
463 : [];
464
465 return makeCheckpoint({
466 id: checkpointId,
467 scope: input.scope,
468 runId: input.runId,
469 nodeId: input.nodeId,
470 parentCheckpointId,
471 ordinalWithinScope: input.ordinalWithinScope,
472 appRunOrdinal: input.appRunOrdinal,
473 ref: checkpointRef,
474 status: "ready",
475 files,
476 capturedAt: input.capturedAt,
477 });
478 }),
479 ).pipe(
480 Effect.mapError(
481 (cause) =>
482 new CheckpointCaptureError({
483 scopeId: input.scope.id,
484 cause,
485 }),
486 ),
487 );
488
489 const restore: CheckpointServiceV2Shape["restore"] = (input) =>
490 withWorkspaceLock(
491 input.scope.cwd,
492 Effect.gen(function* () {
493 if (input.checkpoint.status !== "ready") {
494 return yield* new CheckpointRestoreError({
495 scopeId: input.scope.id,
496 checkpointId: input.checkpoint.id,
497 cause: `Checkpoint status is ${input.checkpoint.status}.`,
498 });
499 }
500
501 const restored = yield* checkpointStore.restoreCheckpoint({
502 cwd: input.scope.cwd,
503 checkpointRef: input.checkpoint.ref,
504 fallbackToHead: false,
505 });
506 if (!restored) {
507 return yield* new CheckpointRestoreError({
508 scopeId: input.scope.id,
509 checkpointId: input.checkpoint.id,
510 cause: "Checkpoint ref is unavailable.",
511 });
512 }
513 }),
514 ).pipe(
515 Effect.mapError((cause) =>
516 isCheckpointRestoreError(cause)
517 ? cause
518 : new CheckpointRestoreError({
519 scopeId: input.scope.id,
520 checkpointId: input.checkpoint.id,
521 cause,
522 }),
523 ),
524 );
525
526 const deleteStaleRefs: CheckpointServiceV2Shape["deleteStaleRefs"] = (input) =>
527 withWorkspaceLock(
528 input.scope.cwd,
529 checkpointStore.deleteCheckpointRefs({
530 cwd: input.scope.cwd,
531 checkpointRefs: input.checkpoints.map((checkpoint) => checkpoint.ref),
532 }),
533 ).pipe(
534 Effect.mapError(
535 (cause) =>
536 new CheckpointDeleteStaleRefsError({
537 scopeId: input.scope.id,
538 checkpointIds: input.checkpoints.map((checkpoint) => checkpoint.id),
539 cause,
540 }),
541 ),
542 );
543
544 return CheckpointServiceV2.of({
545 prepareRootRunScope: (input) =>
546 makeRootRunScope({ ...input, idAllocator }).pipe(
547 Effect.mapError(
548 (cause) =>
549 new CheckpointRootScopePrepareError({
550 threadId: input.threadId,
551 runId: input.runId,
552 cause,
553 }),
554 ),
555 ),
556 ensureScope,
557 captureBaseline,
558 materializeBaselineCheckpoint,
559 capture,
560 restore,
561 deleteStaleRefs,
562 } satisfies CheckpointServiceV2Shape);
563 }),
564);