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

CheckpointService.ts

581 lines19.7 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 Digest from "effect/crypto/Digest";
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 /** The run materializing the baseline: its root node, and when it was requested. */
122 readonly nodeId: NodeId;
123 readonly capturedAt: DateTime.Utc;
124 /** Records a missing checkpoint without touching git, for side chats sharing a parent's worktree. */
125 readonly forceMissing?: boolean;
126 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
127 readonly capture: (input: {
128 readonly scope: OrchestrationV2CheckpointScope;
129 readonly runId: RunId | null;
130 readonly nodeId: NodeId;
131 readonly ordinalWithinScope: number;
132 readonly appRunOrdinal: number | null;
133 readonly capturedAt: DateTime.Utc;
134 readonly forceMissing?: boolean;
135 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
136 readonly restore: (input: {
137 readonly scope: OrchestrationV2CheckpointScope;
138 readonly checkpoint: OrchestrationV2Checkpoint;
139 }) => Effect.Effect<void, CheckpointServiceV2Error>;
140 readonly deleteStaleRefs: (input: {
141 readonly scope: OrchestrationV2CheckpointScope;
142 readonly checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>;
143 }) => Effect.Effect<void, CheckpointServiceV2Error>;
145​
146export class CheckpointServiceV2 extends Context.Service<
147 CheckpointServiceV2,
148 CheckpointServiceV2Shape
149>()("t3/orchestration-v2/CheckpointService/CheckpointServiceV2") {}
150​
151export const checkpointRefForScopeOrdinal = Effect.fn("checkpointRefForScopeOrdinal")(
152 function* (input: { readonly scopeId: CheckpointScopeId; readonly ordinalWithinScope: number }) {
153 const crypto = yield* Digest.Digest;
154 const digest = yield* crypto
155 .digest(Digest.sha256, new TextEncoder().encode(input.scopeId))
156 .pipe(Effect.orDie);
157 const scopeKey = Hex.encode(digest).slice(0, 32);
158 return CheckpointRef.make(
159 `${CHECKPOINT_REFS_PREFIX}/${Base64Url.encode(scopeKey)}/ordinal/${input.ordinalWithinScope}`,
160 );
161 },
162);
163​
164function checkpointIdForScopeOrdinal(
165 idAllocator: IdAllocator.IdAllocatorV2["Service"],
166 input: {
167 readonly scopeId: CheckpointScopeId;
168 readonly ordinalWithinScope: number;
169 },
170) {
171 return idAllocator.allocate.checkpoint({
172 checkpointScopeId: input.scopeId,
173 name: String(input.ordinalWithinScope),
174 });
176​
177const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(function* (input: {
178 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
179 readonly threadId: ThreadId;
180 readonly runId: RunId;
181 readonly rootNodeId: NodeId;
182 readonly providerThreadId: ProviderThreadId;
183 readonly cwd: string;
184 readonly createdAt: DateTime.Utc;
185}) {
186 const scopeId = yield* input.idAllocator.allocate.checkpointScope({
187 threadId: input.threadId,
188 name: ROOT_CHECKPOINT_SCOPE_NAME,
189 });
190 return {
191 id: scopeId,
192 threadId: input.threadId,
193 runId: input.runId,
194 nodeId: input.rootNodeId,
195 parentScopeId: null,
196 providerThreadId: input.providerThreadId,
197 kind: "root_run",
198 ordinalWithinParent: 0,
199 advancesAppRunCount: true,
200 cwd: input.cwd,
201 createdAt: input.createdAt,
202 } satisfies OrchestrationV2CheckpointScope;
203});
204​
205function makeCheckpoint(input: {
206 readonly id: CheckpointId;
207 readonly scope: OrchestrationV2CheckpointScope;
208 readonly runId: RunId | null;
209 readonly nodeId: NodeId;
210 readonly parentCheckpointId: CheckpointId | null;
211 readonly ordinalWithinScope: number;
212 readonly appRunOrdinal: number | null;
213 readonly ref: CheckpointRef;
214 readonly status: OrchestrationV2Checkpoint["status"];
215 readonly files: OrchestrationV2Checkpoint["files"];
216 readonly capturedAt: DateTime.Utc;
217}): OrchestrationV2Checkpoint {
218 return {
219 id: input.id,
220 threadId: input.scope.threadId,
221 scopeId: input.scope.id,
222 runId: input.runId,
223 nodeId: input.nodeId,
224 parentCheckpointId: input.parentCheckpointId,
225 ordinalWithinScope: input.ordinalWithinScope,
226 appRunOrdinal: input.appRunOrdinal,
227 ref: input.ref,
228 status: input.status,
229 files: input.files,
230 capturedAt: input.capturedAt,
231 };
233​
234export const layer: Layer.Layer<
235 CheckpointServiceV2,
236 never,
237 CheckpointStore.CheckpointStore | Digest.Digest | IdAllocator.IdAllocatorV2
238> = Layer.effect(
239 CheckpointServiceV2,
240 Effect.gen(function* () {
241 const checkpointStore = yield* CheckpointStore.CheckpointStore;
242 const crypto = yield* Digest.Digest;
243 const checkpointRefFor = (input: Parameters<typeof checkpointRefForScopeOrdinal>[0]) =>
244 checkpointRefForScopeOrdinal(input).pipe(Effect.provideService(Digest.Digest, crypto));
245 const idAllocator = yield* IdAllocator.IdAllocatorV2;
246 const workspaceLocks = yield* KeyedLock.make<string>();
247 const withWorkspaceLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
248 workspaceLocks.withLock(cwd, effect);
249​
250 const isGitCheckpointable = (cwd: string) =>
251 checkpointStore.isGitRepository(cwd).pipe(Effect.orElseSucceed(() => false));
252​
253 const captureBaseline: CheckpointServiceV2Shape["captureBaseline"] = (input) =>
254 withWorkspaceLock(
255 input.scope.cwd,
256 Effect.gen(function* () {
257 if (!(yield* isGitCheckpointable(input.scope.cwd))) {
258 return;
259 }
260​
261 const checkpointRef = yield* checkpointRefFor({
262 scopeId: input.scope.id,
263 ordinalWithinScope: input.ordinalWithinScope,
264 });
265 const exists = yield* checkpointStore.hasCheckpointRef({
266 cwd: input.scope.cwd,
267 checkpointRef,
268 });
269 if (exists) {
270 return;
271 }
272​
273 yield* checkpointStore
274 .captureCheckpoint({
275 cwd: input.scope.cwd,
276 checkpointRef,
277 })
278 .pipe(
279 Effect.catchTags({
280 VcsUnsupportedOperationError: () => Effect.void,
281 }),
282 );
283 }),
284 ).pipe(
285 Effect.mapError(
286 (cause) =>
287 new CheckpointBaselineCaptureError({
288 scopeId: input.scope.id,
289 ordinalWithinScope: input.ordinalWithinScope,
290 cause,
291 }),
292 ),
293 );
294​
295 const materializeBaselineCheckpoint: CheckpointServiceV2Shape["materializeBaselineCheckpoint"] =
296 (input) =>
297 withWorkspaceLock(
298 input.scope.cwd,
299 Effect.gen(function* () {
300 const checkpointRef = yield* checkpointRefFor({
301 scopeId: input.scope.id,
302 ordinalWithinScope: input.ordinalWithinScope,
303 });
304 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
305 scopeId: input.scope.id,
306 ordinalWithinScope: input.ordinalWithinScope,
307 });
308 const checkpointable =
309 input.forceMissing !== true && (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.nodeId,
331 parentCheckpointId: null,
332 ordinalWithinScope: input.ordinalWithinScope,
333 appRunOrdinal: null,
334 ref: checkpointRef,
335 status: available ? "ready" : "missing",
336 files: [],
337 capturedAt: input.capturedAt,
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 = yield* checkpointRefFor({
366 scopeId: input.scope.id,
367 ordinalWithinScope: input.ordinalWithinScope,
368 });
369 const previousCheckpointRef = yield* checkpointRefFor({
370 scopeId: input.scope.id,
371 ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1),
372 });
373​
374 if (input.forceMissing === true || !(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 captureStatus = yield* checkpointStore
391 .captureCheckpoint({
392 cwd: input.scope.cwd,
393 checkpointRef,
394 })
395 .pipe(
396 Effect.as("ready" as const),
397 Effect.catchTags({
398 VcsUnsupportedOperationError: () => Effect.succeed("missing" as const),
399 }),
400 Effect.catch((cause) =>
401 Effect.logWarning("orchestration V2 checkpoint capture failed", {
402 scopeId: input.scope.id,
403 checkpointRef,
404 cause: String(cause),
405 }).pipe(Effect.as("error" as const)),
406 ),
407 );
408​
409 if (captureStatus !== "ready") {
410 return makeCheckpoint({
411 id: checkpointId,
412 scope: input.scope,
413 runId: input.runId,
414 nodeId: input.nodeId,
415 parentCheckpointId,
416 ordinalWithinScope: input.ordinalWithinScope,
417 appRunOrdinal: input.appRunOrdinal,
418 ref: checkpointRef,
419 status: captureStatus,
420 files: [],
421 capturedAt: input.capturedAt,
422 });
423 }
424​
425 const previousExists = yield* checkpointStore
426 .hasCheckpointRef({
427 cwd: input.scope.cwd,
428 checkpointRef: previousCheckpointRef,
429 })
430 .pipe(
431 Effect.catch((cause) =>
432 Effect.logWarning("orchestration V2 previous checkpoint ref lookup failed", {
433 scopeId: input.scope.id,
434 checkpointRef: previousCheckpointRef,
435 cause: String(cause),
436 }).pipe(Effect.as(false)),
437 ),
438 );
439 const refs = {
440 cwd: input.scope.cwd,
441 fromCheckpointRef: previousCheckpointRef,
442 toCheckpointRef: checkpointRef,
443 };
444 // A pull or rebase can change thousands of files the turn did not write.
445 const files = previousExists
446 ? yield* Effect.all([
447 checkpointStore.diffCheckpoints({
448 ...refs,
449 fallbackFromToHead: false,
450 ignoreWhitespace: false,
451 format: "numstat",
452 }),
453 checkpointStore.listAuthoredPaths(refs).pipe(
454 Effect.catch((cause) =>
455 Effect.logWarning("orchestration V2 checkpoint authored paths failed", {
456 scopeId: input.scope.id,
457 checkpointRef,
458 cause: String(cause),
459 }).pipe(Effect.as(null)),
460 ),
461 ),
462 ]).pipe(
463 Effect.map(([diff, authoredPaths]) =>
464 parseTurnDiffFilesFromNumstat(diff)
465 .filter((file) => !isGitImport(file, authoredPaths))
466 .map((file) => ({
467 path: file.path,
468 kind: "modified",
469 additions: file.additions,
470 deletions: file.deletions,
471 })),
472 ),
473 Effect.catch((cause) =>
474 Effect.logWarning("orchestration V2 checkpoint diff summary failed", {
475 scopeId: input.scope.id,
476 checkpointRef,
477 cause: String(cause),
478 }).pipe(Effect.as([])),
479 ),
480 )
481 : [];
482​
483 return makeCheckpoint({
484 id: checkpointId,
485 scope: input.scope,
486 runId: input.runId,
487 nodeId: input.nodeId,
488 parentCheckpointId,
489 ordinalWithinScope: input.ordinalWithinScope,
490 appRunOrdinal: input.appRunOrdinal,
491 ref: checkpointRef,
492 status: "ready",
493 files,
494 capturedAt: input.capturedAt,
495 });
496 }),
497 ).pipe(
498 Effect.mapError(
499 (cause) =>
500 new CheckpointCaptureError({
501 scopeId: input.scope.id,
502 cause,
503 }),
504 ),
505 );
506​
507 const restore: CheckpointServiceV2Shape["restore"] = (input) =>
508 withWorkspaceLock(
509 input.scope.cwd,
510 Effect.gen(function* () {
511 if (input.checkpoint.status !== "ready") {
512 return yield* new CheckpointRestoreError({
513 scopeId: input.scope.id,
514 checkpointId: input.checkpoint.id,
515 cause: `Checkpoint status is ${input.checkpoint.status}.`,
516 });
517 }
518​
519 const restored = yield* checkpointStore.restoreCheckpoint({
520 cwd: input.scope.cwd,
521 checkpointRef: input.checkpoint.ref,
522 fallbackToHead: false,
523 });
524 if (!restored) {
525 return yield* new CheckpointRestoreError({
526 scopeId: input.scope.id,
527 checkpointId: input.checkpoint.id,
528 cause: "Checkpoint ref is unavailable.",
529 });
530 }
531 }),
532 ).pipe(
533 Effect.mapError((cause) =>
534 isCheckpointRestoreError(cause)
535 ? cause
536 : new CheckpointRestoreError({
537 scopeId: input.scope.id,
538 checkpointId: input.checkpoint.id,
539 cause,
540 }),
541 ),
542 );
543​
544 const deleteStaleRefs: CheckpointServiceV2Shape["deleteStaleRefs"] = (input) =>
545 withWorkspaceLock(
546 input.scope.cwd,
547 checkpointStore.deleteCheckpointRefs({
548 cwd: input.scope.cwd,
549 checkpointRefs: input.checkpoints.map((checkpoint) => checkpoint.ref),
550 }),
551 ).pipe(
552 Effect.mapError(
553 (cause) =>
554 new CheckpointDeleteStaleRefsError({
555 scopeId: input.scope.id,
556 checkpointIds: input.checkpoints.map((checkpoint) => checkpoint.id),
557 cause,
558 }),
559 ),
560 );
561​
562 return CheckpointServiceV2.of({
563 prepareRootRunScope: (input) =>
564 makeRootRunScope({ ...input, idAllocator }).pipe(
565 Effect.mapError(
566 (cause) =>
567 new CheckpointRootScopePrepareError({
568 threadId: input.threadId,
569 runId: input.runId,
570 cause,
571 }),
572 ),
573 ),
574 captureBaseline,
575 materializeBaselineCheckpoint,
576 capture,
577 restore,
578 deleteStaleRefs,
579 } satisfies CheckpointServiceV2Shape);
580 }),
581);