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

CheckpointService.ts

564 lines18.3 KB

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 { parseTurnDiffFilesFromUnifiedDiff } 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.TaggedErrorClass<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 }
41​
42export class CheckpointScopeEnsureError extends Schema.TaggedErrorClass<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 }
53​
54export class CheckpointBaselineCaptureError extends Schema.TaggedErrorClass<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 }
66​
67export class CheckpointCaptureError extends Schema.TaggedErrorClass<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 }
79​
80export class CheckpointRestoreError extends Schema.TaggedErrorClass<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 }
92​
93export class CheckpointDeleteStaleRefsError extends Schema.TaggedErrorClass<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 }
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 }) => 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>;
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}/${Encoding.encodeBase64Url(scopeKey)}/ordinal/${input.ordinalWithinScope}`,
167 );
169​
170function checkpointIdForScopeOrdinal(
171 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 });
182​
183function makeRootRunScope(input: {
184 readonly 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 });
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 };
241​
242export const layer: Layer.Layer<
243 CheckpointServiceV2,
244 never,
245 CheckpointStore.CheckpointStore | IdAllocatorV2
246> = Layer.effect(
247 CheckpointServiceV2,
248 Effect.gen(function* () {
249 const checkpointStore = yield* CheckpointStore.CheckpointStore;
250 const idAllocator = yield* IdAllocatorV2;
251 const workspaceSemaphores = yield* Ref.make(new Map<string, Semaphore.Semaphore>());
252​
253 const getWorkspaceSemaphore = (cwd: string) =>
254 Effect.gen(function* () {
255 const existing = (yield* Ref.get(workspaceSemaphores)).get(cwd);
256 if (existing !== undefined) {
257 return existing;
258 }
259​
260 const created = yield* Semaphore.make(1);
261 return yield* Ref.modify(workspaceSemaphores, (current) => {
262 const concurrent = current.get(cwd);
263 if (concurrent !== undefined) {
264 return [concurrent, current];
265 }
266 const updated = new Map(current);
267 updated.set(cwd, created);
268 return [created, updated];
269 });
270 });
271​
272 const withWorkspaceLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
273 Effect.flatMap(getWorkspaceSemaphore(cwd), (semaphore) => semaphore.withPermits(1)(effect));
274​
275 const isGitCheckpointable = (cwd: string) =>
276 checkpointStore.isGitRepository(cwd).pipe(Effect.orElseSucceed(() => false));
277​
278 const ensureScope: CheckpointServiceV2Shape["ensureScope"] = (scope) => Effect.succeed(scope);
279​
280 const captureBaseline: CheckpointServiceV2Shape["captureBaseline"] = (input) =>
281 withWorkspaceLock(
282 input.scope.cwd,
283 Effect.gen(function* () {
284 if (!(yield* isGitCheckpointable(input.scope.cwd))) {
285 return;
286 }
287​
288 const checkpointRef = checkpointRefForScopeOrdinal({
289 scopeId: input.scope.id,
290 ordinalWithinScope: input.ordinalWithinScope,
291 });
292 const exists = yield* checkpointStore.hasCheckpointRef({
293 cwd: input.scope.cwd,
294 checkpointRef,
295 });
296 if (exists) {
297 return;
298 }
299​
300 yield* checkpointStore.captureCheckpoint({
301 cwd: input.scope.cwd,
302 checkpointRef,
303 });
304 }),
305 ).pipe(
306 Effect.mapError(
307 (cause) =>
308 new CheckpointBaselineCaptureError({
309 scopeId: input.scope.id,
310 ordinalWithinScope: input.ordinalWithinScope,
311 cause,
312 }),
313 ),
314 );
315​
316 const materializeBaselineCheckpoint: CheckpointServiceV2Shape["materializeBaselineCheckpoint"] =
317 (input) =>
318 withWorkspaceLock(
319 input.scope.cwd,
320 Effect.gen(function* () {
321 const ordinalWithinScope = 0;
322 const checkpointRef = checkpointRefForScopeOrdinal({
323 scopeId: input.scope.id,
324 ordinalWithinScope,
325 });
326 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
327 scopeId: input.scope.id,
328 ordinalWithinScope,
329 });
330 const checkpointable = yield* isGitCheckpointable(input.scope.cwd);
331 const available = checkpointable
332 ? yield* checkpointStore.hasCheckpointRef({
333 cwd: input.scope.cwd,
334 checkpointRef,
335 })
336 : false;
337 return makeCheckpoint({
338 id: checkpointId,
339 scope: input.scope,
340 runId: null,
341 nodeId: input.scope.nodeId,
342 parentCheckpointId: null,
343 ordinalWithinScope,
344 appRunOrdinal: null,
345 ref: checkpointRef,
346 status: available ? "ready" : "missing",
347 files: [],
348 capturedAt: input.scope.createdAt,
349 });
350 }),
351 ).pipe(
352 Effect.mapError(
353 (cause) =>
354 new CheckpointCaptureError({
355 scopeId: input.scope.id,
356 cause,
357 }),
358 ),
359 );
360​
361 const capture: CheckpointServiceV2Shape["capture"] = (input) =>
362 withWorkspaceLock(
363 input.scope.cwd,
364 Effect.gen(function* () {
365 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
366 scopeId: input.scope.id,
367 ordinalWithinScope: input.ordinalWithinScope,
368 });
369 const parentCheckpointId =
370 input.ordinalWithinScope > 0
371 ? yield* checkpointIdForScopeOrdinal(idAllocator, {
372 scopeId: input.scope.id,
373 ordinalWithinScope: input.ordinalWithinScope - 1,
374 })
375 : null;
376 const checkpointRef = checkpointRefForScopeOrdinal({
377 scopeId: input.scope.id,
378 ordinalWithinScope: input.ordinalWithinScope,
379 });
380 const previousCheckpointRef = checkpointRefForScopeOrdinal({
381 scopeId: input.scope.id,
382 ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1),
383 });
384​
385 if (!(yield* isGitCheckpointable(input.scope.cwd))) {
386 return makeCheckpoint({
387 id: checkpointId,
388 scope: input.scope,
389 runId: input.runId,
390 nodeId: input.nodeId,
391 parentCheckpointId,
392 ordinalWithinScope: input.ordinalWithinScope,
393 appRunOrdinal: input.appRunOrdinal,
394 ref: checkpointRef,
395 status: "missing",
396 files: [],
397 capturedAt: input.capturedAt,
398 });
399 }
400​
401 const captured = yield* checkpointStore
402 .captureCheckpoint({
403 cwd: input.scope.cwd,
404 checkpointRef,
405 })
406 .pipe(
407 Effect.as(true),
408 Effect.catch((cause) =>
409 Effect.logWarning("orchestration V2 checkpoint capture failed", {
410 scopeId: input.scope.id,
411 checkpointRef,
412 cause: String(cause),
413 }).pipe(Effect.as(false)),
414 ),
415 );
416​
417 if (!captured) {
418 return makeCheckpoint({
419 id: checkpointId,
420 scope: input.scope,
421 runId: input.runId,
422 nodeId: input.nodeId,
423 parentCheckpointId,
424 ordinalWithinScope: input.ordinalWithinScope,
425 appRunOrdinal: input.appRunOrdinal,
426 ref: checkpointRef,
427 status: "error",
428 files: [],
429 capturedAt: input.capturedAt,
430 });
431 }
432​
433 const previousExists = yield* checkpointStore.hasCheckpointRef({
434 cwd: input.scope.cwd,
435 checkpointRef: previousCheckpointRef,
436 });
437 const files = previousExists
438 ? yield* checkpointStore
439 .diffCheckpoints({
440 cwd: input.scope.cwd,
441 fromCheckpointRef: previousCheckpointRef,
442 toCheckpointRef: checkpointRef,
443 fallbackFromToHead: false,
444 ignoreWhitespace: false,
445 })
446 .pipe(
447 Effect.map((diff) =>
448 parseTurnDiffFilesFromUnifiedDiff(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);