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

CheckpointService.ts

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