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

CheckpointDiffQuery.ts

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