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

CheckpointDiffQuery.ts

266 lines8.7 KB

1/**
2 * CheckpointDiffQuery - Query interface for computed checkpoint diffs.
3 *
4 * Provides read-only diff operations across checkpoint snapshots used by
5 * orchestration APIs.
6 *
7 * @module CheckpointDiffQuery
8 */
9import {
10 OrchestrationGetTurnDiffResult,
11 type OrchestrationGetFullThreadDiffInput,
12 type OrchestrationGetFullThreadDiffResult,
13 type OrchestrationGetTurnDiffInput,
14 type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
15 type ThreadId,
16} from "@t3tools/contracts";
17import * as Context from "effect/Context";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Schema from "effect/Schema";
21​
22import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts";
23import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
24import {
25 CheckpointDiffResultInvalidError,
26 CheckpointRefUnavailableError,
27 CheckpointThreadNotFoundError,
28 CheckpointTurnRangeUnavailableError,
29 CheckpointWorkspacePathMissingError,
30 type CheckpointServiceError,
31} from "./Errors.ts";
32import { checkpointStartRef } from "./Utils.ts";
33import * as CheckpointStore from "./CheckpointStore.ts";
34​
35/** Service tag for checkpoint diff queries. */
36export class CheckpointDiffQuery extends Context.Service<
37 CheckpointDiffQuery,
38 {
39 /**
40 * Read the patch diff for a single turn checkpoint transition.
41 *
42 * Verifies checkpoint availability in both projection state and filesystem.
43 */
44 readonly getTurnDiff: (
45 input: OrchestrationGetTurnDiffInput,
46 ) => Effect.Effect<OrchestrationGetTurnDiffResultType, CheckpointServiceError>;
47​
48 /**
49 * Read the full patch diff across a thread range of checkpoints.
50 *
51 * Uses turn-diff semantics with `fromTurnCount = 0`.
52 */
53 readonly getFullThreadDiff: (
54 input: OrchestrationGetFullThreadDiffInput,
55 ) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
56 }
57>()("t3/checkpointing/CheckpointDiffQuery") {}
58​
59const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
60​
61function buildTurnDiffResult(
62 input: {
63 readonly threadId: ThreadId;
64 readonly fromTurnCount: number;
65 readonly toTurnCount: number;
66 },
67 diff: string,
68): OrchestrationGetTurnDiffResultType {
69 return {
70 threadId: input.threadId,
71 fromTurnCount: input.fromTurnCount,
72 toTurnCount: input.toTurnCount,
73 diff,
74 };
76​
77/** @public Service construction is part of the canonical Effect module API. */
78export const make = Effect.gen(function* () {
79 const threads = yield* ThreadManagement.ThreadManagementService;
80 const checkpointStore = yield* CheckpointStore.CheckpointStore;
81​
82 const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
83 function* (input) {
84 const operation = "CheckpointDiffQuery.getTurnDiff";
85 const ignoreWhitespace = input.ignoreWhitespace ?? true;
86 yield* Effect.annotateCurrentSpan({
87 "checkpoint.thread_id": input.threadId,
88 "checkpoint.from_turn_count": input.fromTurnCount,
89 "checkpoint.to_turn_count": input.toTurnCount,
90 "checkpoint.ignore_whitespace": ignoreWhitespace,
91 });
92​
93 if (input.fromTurnCount === input.toTurnCount) {
94 const emptyDiff = buildTurnDiffResult(input, "");
95 if (!isTurnDiffResult(emptyDiff)) {
96 return yield* new CheckpointDiffResultInvalidError({
97 operation,
98 threadId: input.threadId,
99 });
100 }
101 return emptyDiff;
102 }
103​
104 const projection = yield* threads.getCheckpointContext(input.threadId).pipe(
105 Effect.mapError(
106 () =>
107 new CheckpointThreadNotFoundError({
108 operation,
109 threadId: input.threadId,
110 }),
111 ),
112 Effect.withSpan("checkpoint.turnDiff.lookupContext"),
113 );
114 const completedRunIds = new Set(
115 projection.runs.filter((run) => run.status === "completed").map((run) => run.id),
116 );
117 const readyCheckpoints = projection.checkpoints.filter(
118 (checkpoint) =>
119 checkpoint.status === "ready" &&
120 checkpoint.appRunOrdinal !== null &&
121 checkpoint.runId !== null &&
122 completedRunIds.has(checkpoint.runId),
123 );
124 const maxTurnCount = readyCheckpoints.reduce(
125 (max, checkpoint) => Math.max(max, checkpoint.appRunOrdinal ?? 0),
126 0,
127 );
128 if (input.toTurnCount > maxTurnCount) {
129 return yield* new CheckpointTurnRangeUnavailableError({
130 operation,
131 threadId: input.threadId,
132 requestedTurnCount: input.toTurnCount,
133 availableTurnCount: maxTurnCount,
134 });
135 }
136​
137 const toCheckpoint = readyCheckpoints.find(
138 (checkpoint) => checkpoint.appRunOrdinal === input.toTurnCount,
139 );
140 if (toCheckpoint === undefined) {
141 return yield* new CheckpointRefUnavailableError({
142 operation,
143 threadId: input.threadId,
144 turnCount: input.toTurnCount,
145 checkpoint: "to",
146 });
147 }
148​
149 const toScope = projection.checkpointScopes.find(
150 (scope) => scope.id === toCheckpoint.scopeId,
151 );
152 if (toScope === undefined) {
153 return yield* new CheckpointWorkspacePathMissingError({
154 operation,
155 threadId: input.threadId,
156 });
157 }
158​
159 const fromCheckpointRef =
160 input.fromTurnCount === 0
161 ? (() => {
162 // The root scope is shared by every run in this thread. Its
163 // runId tracks the latest owner, while ordinal zero stays the baseline.
164 const firstScope = projection.checkpointScopes.find(
165 (scope) => scope.kind === "root_run",
166 );
167 return firstScope === undefined
168 ? undefined
169 : checkpointRefForScopeOrdinal({
170 scopeId: firstScope.id,
171 ordinalWithinScope: 0,
172 });
173 })()
174 : readyCheckpoints.find((checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount)
175 ?.ref;
176 if (fromCheckpointRef === undefined) {
177 return yield* new CheckpointRefUnavailableError({
178 operation,
179 threadId: input.threadId,
180 turnCount: input.fromTurnCount,
181 checkpoint: "from",
182 });
183 }
184​
185 const startRef = checkpointStartRef(toCheckpoint.ref);
186 const turnBaselineRef =
187 input.toTurnCount === input.fromTurnCount + 1 &&
188 (yield* checkpointStore.hasCheckpointRef({ cwd: toScope.cwd, checkpointRef: startRef }))
189 ? startRef
190 : fromCheckpointRef;
191 const diff = yield* checkpointStore
192 .diffCheckpoints({
193 cwd: toScope.cwd,
194 fromCheckpointRef: turnBaselineRef,
195 toCheckpointRef: toCheckpoint.ref,
196 fallbackFromToHead: false,
197 ignoreWhitespace,
198 })
199 .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
200​
201 const turnDiff = buildTurnDiffResult(input, diff);
202 if (!isTurnDiffResult(turnDiff)) {
203 return yield* new CheckpointDiffResultInvalidError({
204 operation,
205 threadId: input.threadId,
206 });
207 }
208​
209 return turnDiff;
210 },
211 );
212​
213 const getFullThreadDiff: CheckpointDiffQuery["Service"]["getFullThreadDiff"] = Effect.fn(
214 "CheckpointDiffQuery.getFullThreadDiff",
215 )(function* (input) {
216 const operation = "CheckpointDiffQuery.getFullThreadDiff";
217 const ignoreWhitespace = input.ignoreWhitespace ?? true;
218 yield* Effect.annotateCurrentSpan({
219 "checkpoint.thread_id": input.threadId,
220 "checkpoint.from_turn_count": 0,
221 "checkpoint.to_turn_count": input.toTurnCount,
222 "checkpoint.ignore_whitespace": ignoreWhitespace,
223 "checkpoint.diff_kind": "full-thread",
224 });
225​
226 if (input.toTurnCount === 0) {
227 const emptyDiff = buildTurnDiffResult(
228 {
229 threadId: input.threadId,
230 fromTurnCount: 0,
231 toTurnCount: 0,
232 },
233 "",
234 );
235 if (!isTurnDiffResult(emptyDiff)) {
236 return yield* new CheckpointDiffResultInvalidError({
237 operation,
238 threadId: input.threadId,
239 });
240 }
241 return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
242 }
243​
244 const turnDiff = yield* getTurnDiff({
245 threadId: input.threadId,
246 fromTurnCount: 0,
247 toTurnCount: input.toTurnCount,
248 ignoreWhitespace,
249 });
250 if (!isTurnDiffResult(turnDiff)) {
251 return yield* new CheckpointDiffResultInvalidError({
252 operation,
253 threadId: input.threadId,
254 });
255 }
256​
257 return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
258 });
259​
260 return CheckpointDiffQuery.of({
261 getTurnDiff,
262 getFullThreadDiff,
263 });
264});
265​
266export const layer = Layer.effect(CheckpointDiffQuery, make);