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

CheckpointRollbackService.ts

362 lines13.3 KB

1import {
2 CheckpointId,
3 CheckpointScopeId,
4 type OrchestrationV2DomainEvent,
5 ProviderThreadId,
6 ThreadId,
7} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as DateTime from "effect/DateTime";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Schema from "effect/Schema";
15​
16import {
17 isCheckpointRestoreIsolated,
18 SHARED_WORKSPACE_RESTORE_MESSAGE,
19} from "./CheckpointRestoreSafety.ts";
20import { CheckpointServiceV2 } from "./CheckpointService.ts";
21import { EventSinkV2 } from "./EventSink.ts";
22import { IdAllocatorV2 } from "./IdAllocator.ts";
23import { ProjectionStoreV2 } from "./ProjectionStore.ts";
24import * as ProjectStore from "./ProjectStore.ts";
25import type { ProviderAdapterV2RollbackTarget } from "./ProviderAdapter.ts";
26import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
27import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
28​
29export const ROLLBACK_FAILED_MESSAGE =
30 "The provider could not roll back this conversation. Try again; if it keeps failing, check the provider and server logs.";
31​
32export class CheckpointRollbackExecutionError extends Schema.TaggedError<CheckpointRollbackExecutionError>()(
33 "CheckpointRollbackExecutionError",
34 {
35 reason: Schema.Literals([
36 "rollback-target-invalid",
37 "active-provider-changed",
38 "provider-turn-unavailable",
39 "unexpected-failure",
40 "shared-workspace",
41 ]),
42 threadId: ThreadId,
43 providerThreadId: ProviderThreadId,
44 checkpointId: CheckpointId,
45 cause: Schema.optional(Schema.Defect()),
46 },
47) {
48 override get message(): string {
49 switch (this.reason) {
50 case "rollback-target-invalid":
51 return `Rollback target ${this.checkpointId} for provider thread ${this.providerThreadId} on thread ${this.threadId} is incomplete or invalid.`;
52 case "active-provider-changed":
53 return `Active provider changed before rollback target ${this.checkpointId} could execute on thread ${this.threadId}.`;
54 case "provider-turn-unavailable":
55 return `Provider turn for rollback target ${this.checkpointId} is unavailable on provider thread ${this.providerThreadId}.`;
56 case "shared-workspace":
57 return SHARED_WORKSPACE_RESTORE_MESSAGE;
58 case "unexpected-failure":
59 return ROLLBACK_FAILED_MESSAGE;
60 }
61 }
63​
64const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError);
65​
66export interface CheckpointRollbackServiceV2Shape {
67 readonly execute: (input: {
68 readonly threadId: ThreadId;
69 readonly providerThreadId: ProviderThreadId;
70 readonly checkpointId: CheckpointId;
71 readonly scopeId: CheckpointScopeId;
72 readonly restoreFiles?: boolean;
73 }) => Effect.Effect<void, CheckpointRollbackExecutionError>;
75​
76export class CheckpointRollbackServiceV2 extends Context.Service<
77 CheckpointRollbackServiceV2,
78 CheckpointRollbackServiceV2Shape
79>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}
80​
81export const layer: Layer.Layer<
82 CheckpointRollbackServiceV2,
83 never,
84 | CheckpointServiceV2
85 | EventSinkV2
86 | IdAllocatorV2
87 | ProjectionStoreV2
88 | ProviderSessionManagerV2
89 | RuntimePolicyV2
90 | FileSystem.FileSystem
91 | Path.Path
92 | ProjectStore.ProjectStoreV2
93> = Layer.effect(
94 CheckpointRollbackServiceV2,
95 Effect.gen(function* () {
96 const checkpoints = yield* CheckpointServiceV2;
97 const eventSink = yield* EventSinkV2;
98 const ids = yield* IdAllocatorV2;
99 const projections = yield* ProjectionStoreV2;
100 const sessions = yield* ProviderSessionManagerV2;
101 const runtimePolicy = yield* RuntimePolicyV2;
102 const fileSystem = yield* FileSystem.FileSystem;
103 const projects = yield* ProjectStore.ProjectStoreV2;
104 const path = yield* Path.Path;
105​
106 const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
107 readonly threadId: ThreadId;
108 readonly providerThreadId: ProviderThreadId;
109 readonly checkpointId: CheckpointId;
110 readonly scopeId: CheckpointScopeId;
111 readonly restoreFiles?: boolean;
112 }) {
113 const projection = yield* projections.getThreadRecords(input.threadId, [
114 "providerThreads",
115 "providerSessions",
116 "checkpoints",
117 "checkpointScopes",
118 "runs",
119 "attempts",
120 "nodes",
121 "providerTurns",
122 ]);
123 const providerThread = projection.providerThreads.find(
124 (candidate) => candidate.id === input.providerThreadId,
125 );
126 const checkpoint = projection.checkpoints.find(
127 (candidate) => candidate.id === input.checkpointId,
128 );
129 const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
130 if (
131 providerThread === undefined ||
132 providerThread.providerSessionId === null ||
133 checkpoint === undefined ||
134 scope === undefined ||
135 checkpoint.scopeId !== scope.id ||
136 checkpoint.status !== "ready"
137 ) {
138 return yield* new CheckpointRollbackExecutionError({
139 reason: "rollback-target-invalid",
140 threadId: input.threadId,
141 providerThreadId: input.providerThreadId,
142 checkpointId: input.checkpointId,
143 });
144 }
145 if (
146 providerThread.id !== projection.thread.activeProviderThreadId ||
147 providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId
148 ) {
149 return yield* new CheckpointRollbackExecutionError({
150 reason: "active-provider-changed",
151 threadId: input.threadId,
152 providerThreadId: input.providerThreadId,
153 checkpointId: input.checkpointId,
154 });
155 }
156​
157 if (
158 input.restoreFiles !== false &&
159 !(yield* isCheckpointRestoreIsolated(projection.thread, scope, {
160 fileSystem,
161 projections,
162 projects,
163 path,
164 }))
165 ) {
166 return yield* new CheckpointRollbackExecutionError({
167 reason: "shared-workspace",
168 threadId: input.threadId,
169 providerThreadId: input.providerThreadId,
170 checkpointId: input.checkpointId,
171 });
172 }
173​
174 const modelSelection = projection.thread.modelSelection;
175 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
176 thread: projection.thread,
177 modelSelection,
178 });
179 const existingSession = projection.providerSessions.find(
180 (candidate) => candidate.id === providerThread.providerSessionId,
181 );
182 const session = yield* sessions.open({
183 threadId: input.threadId,
184 providerSessionId: providerThread.providerSessionId,
185 modelSelection,
186 runtimePolicy: resolvedRuntimePolicy,
187 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
188 ...(providerThread.nativeThreadRef?.nativeId == null
189 ? {}
190 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
191 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
192 ? {}
193 : {
194 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
195 }),
196 });
197​
198 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
199 // Stopped and failed runs after the target leave the provider
200 // conversation too, so they must not stay visible.
201 const runsToRollback = projection.runs.filter(
202 (run) =>
203 run.ordinal > targetOrdinal &&
204 (run.status === "completed" ||
205 run.status === "interrupted" ||
206 run.status === "failed" ||
207 run.status === "cancelled"),
208 );
209 // Rolled-back turns stay in the audit history, but no longer exist in
210 // the provider conversation and must not be counted by a later rewind.
211 const rolledBackRunIds = new Set(
212 projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
213 );
214 const rolledBackAttemptIds = new Set(
215 projection.attempts
216 .filter((attempt) => rolledBackRunIds.has(attempt.runId))
217 .map((attempt) => attempt.id),
218 );
219 const providerThreadTurns = projection.providerTurns.filter(
220 (turn) =>
221 turn.providerThreadId === providerThread.id &&
222 (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
223 );
224 const rollbackTarget: ProviderAdapterV2RollbackTarget =
225 targetOrdinal === 0
226 ? {
227 type: "thread_start",
228 checkpointId: checkpoint.id,
229 appRunOrdinal: 0,
230 }
231 : yield* Effect.gen(function* () {
232 const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
233 const targetAttempt = projection.attempts.find(
234 (attempt) => attempt.id === targetRun?.activeAttemptId,
235 );
236 const targetTurn = projection.providerTurns.find(
237 (turn) =>
238 turn.id === targetAttempt?.providerTurnId ||
239 turn.runAttemptId === targetAttempt?.id,
240 );
241 if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
242 return yield* new CheckpointRollbackExecutionError({
243 reason: "provider-turn-unavailable",
244 threadId: input.threadId,
245 providerThreadId: input.providerThreadId,
246 checkpointId: input.checkpointId,
247 });
248 }
249 return {
250 type: "provider_turn" as const,
251 checkpointId: checkpoint.id,
252 appRunOrdinal: targetOrdinal,
253 providerTurn: targetTurn,
254 };
255 });
256​
257 const snapshot =
258 runsToRollback.length === 0
259 ? { providerThread }
260 : yield* session.rollbackThread({
261 providerThread,
262 target: rollbackTarget,
263 providerThreadTurns,
264 });
265 if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint });
266 const staleCheckpoints = projection.checkpoints.filter(
267 (candidate) =>
268 candidate.scopeId === scope.id &&
269 candidate.appRunOrdinal !== null &&
270 candidate.appRunOrdinal > targetOrdinal &&
271 candidate.status === "ready",
272 );
273 if (staleCheckpoints.length > 0) {
274 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
275 }
276​
277 const now = yield* DateTime.now;
278 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
279 Effect.map(
280 ids.allocate.event({ threadId: event.threadId }),
281 (id) =>
282 ({
283 ...event,
284 id,
285 }) as Event,
286 );
287 const events: Array<OrchestrationV2DomainEvent> = [];
288 events.push(
289 yield* makeEvent({
290 type: "provider-thread.updated",
291 threadId: input.threadId,
292 driver: providerThread.driver,
293 providerInstanceId: providerThread.providerInstanceId,
294 occurredAt: now,
295 payload: {
296 ...snapshot.providerThread,
297 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
298 updatedAt: now,
299 },
300 }),
301 );
302 for (const staleCheckpoint of staleCheckpoints) {
303 events.push(
304 yield* makeEvent({
305 type: "checkpoint.captured",
306 threadId: input.threadId,
307 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
308 nodeId: staleCheckpoint.nodeId,
309 providerInstanceId: providerThread.providerInstanceId,
310 occurredAt: now,
311 payload: { ...staleCheckpoint, status: "stale" },
312 }),
313 );
314 }
315 for (const run of runsToRollback) {
316 const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
317 events.push(
318 yield* makeEvent({
319 type: "run.updated",
320 threadId: input.threadId,
321 runId: run.id,
322 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
323 providerInstanceId: run.providerInstanceId,
324 occurredAt: now,
325 payload: { ...run, status: "rolled_back", completedAt: now },
326 }),
327 );
328 if (rootNode !== undefined) {
329 events.push(
330 yield* makeEvent({
331 type: "node.updated",
332 threadId: input.threadId,
333 runId: run.id,
334 nodeId: rootNode.id,
335 providerInstanceId: run.providerInstanceId,
336 occurredAt: now,
337 payload: { ...rootNode, status: "rolled_back", completedAt: now },
338 }),
339 );
340 }
341 }
342 yield* eventSink.write({ events });
343 });
344​
345 return CheckpointRollbackServiceV2.of({
346 execute: (input) =>
347 execute(input).pipe(
348 Effect.mapError((cause) =>
349 isCheckpointRollbackExecutionError(cause)
350 ? cause
351 : new CheckpointRollbackExecutionError({
352 reason: "unexpected-failure",
353 threadId: input.threadId,
354 providerThreadId: input.providerThreadId,
355 checkpointId: input.checkpointId,
356 cause,
357 }),
358 ),
359 ),
360 });
361 }),
362);