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