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

CheckpointService.ts

565 lines18.4 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 { 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.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 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>;
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 );
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 });
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 });
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 };
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.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: input.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 format: "numstat",
446 })
447 .pipe(
448 Effect.map((diff) =>
449 parseTurnDiffFilesFromNumstat(diff).map((file) => ({
450 path: file.path,
451 kind: "modified",
452 additions: file.additions,
453 deletions: file.deletions,
454 })),
455 ),
456 Effect.catch((cause) =>
457 Effect.logWarning("orchestration V2 checkpoint diff summary failed", {
458 scopeId: input.scope.id,
459 checkpointRef,
460 cause: String(cause),
461 }).pipe(Effect.as([])),
462 ),
463 )
464 : [];
465​
466 return makeCheckpoint({
467 id: checkpointId,
468 scope: input.scope,
469 runId: input.runId,
470 nodeId: input.nodeId,
471 parentCheckpointId,
472 ordinalWithinScope: input.ordinalWithinScope,
473 appRunOrdinal: input.appRunOrdinal,
474 ref: checkpointRef,
475 status: "ready",
476 files,
477 capturedAt: input.capturedAt,
478 });
479 }),
480 ).pipe(
481 Effect.mapError(
482 (cause) =>
483 new CheckpointCaptureError({
484 scopeId: input.scope.id,
485 cause,
486 }),
487 ),
488 );
489​
490 const restore: CheckpointServiceV2Shape["restore"] = (input) =>
491 withWorkspaceLock(
492 input.scope.cwd,
493 Effect.gen(function* () {
494 if (input.checkpoint.status !== "ready") {
495 return yield* new CheckpointRestoreError({
496 scopeId: input.scope.id,
497 checkpointId: input.checkpoint.id,
498 cause: `Checkpoint status is ${input.checkpoint.status}.`,
499 });
500 }
501​
502 const restored = yield* checkpointStore.restoreCheckpoint({
503 cwd: input.scope.cwd,
504 checkpointRef: input.checkpoint.ref,
505 fallbackToHead: false,
506 });
507 if (!restored) {
508 return yield* new CheckpointRestoreError({
509 scopeId: input.scope.id,
510 checkpointId: input.checkpoint.id,
511 cause: "Checkpoint ref is unavailable.",
512 });
513 }
514 }),
515 ).pipe(
516 Effect.mapError((cause) =>
517 isCheckpointRestoreError(cause)
518 ? cause
519 : new CheckpointRestoreError({
520 scopeId: input.scope.id,
521 checkpointId: input.checkpoint.id,
522 cause,
523 }),
524 ),
525 );
526​
527 const deleteStaleRefs: CheckpointServiceV2Shape["deleteStaleRefs"] = (input) =>
528 withWorkspaceLock(
529 input.scope.cwd,
530 checkpointStore.deleteCheckpointRefs({
531 cwd: input.scope.cwd,
532 checkpointRefs: input.checkpoints.map((checkpoint) => checkpoint.ref),
533 }),
534 ).pipe(
535 Effect.mapError(
536 (cause) =>
537 new CheckpointDeleteStaleRefsError({
538 scopeId: input.scope.id,
539 checkpointIds: input.checkpoints.map((checkpoint) => checkpoint.id),
540 cause,
541 }),
542 ),
543 );
544​
545 return CheckpointServiceV2.of({
546 prepareRootRunScope: (input) =>
547 makeRootRunScope({ ...input, idAllocator }).pipe(
548 Effect.mapError(
549 (cause) =>
550 new CheckpointRootScopePrepareError({
551 threadId: input.threadId,
552 runId: input.runId,
553 cause,
554 }),
555 ),
556 ),
557 ensureScope,
558 captureBaseline,
559 materializeBaselineCheckpoint,
560 capture,
561 restore,
562 deleteStaleRefs,
563 } satisfies CheckpointServiceV2Shape);
564 }),
565);