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

CheckpointRollbackService.ts

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