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

CheckpointRollbackService.ts

320 lines11.9 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.getThreadProjection(input.threadId);
105 const providerThread = projection.providerThreads.find(
106 (candidate) => candidate.id === input.providerThreadId,
107 );
108 const checkpoint = projection.checkpoints.find(
109 (candidate) => candidate.id === input.checkpointId,
110 );
111 const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
112 if (
113 providerThread === undefined ||
114 providerThread.providerSessionId === null ||
115 checkpoint === undefined ||
116 scope === undefined ||
117 checkpoint.scopeId !== scope.id ||
118 checkpoint.status !== "ready"
119 ) {
120 return yield* new CheckpointRollbackExecutionError({
121 reason: "rollback-target-invalid",
122 threadId: input.threadId,
123 providerThreadId: input.providerThreadId,
124 checkpointId: input.checkpointId,
125 });
126 }
127 if (
128 providerThread.id !== projection.thread.activeProviderThreadId ||
129 providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId
130 ) {
131 return yield* new CheckpointRollbackExecutionError({
132 reason: "active-provider-changed",
133 threadId: input.threadId,
134 providerThreadId: input.providerThreadId,
135 checkpointId: input.checkpointId,
136 });
137 }
138​
139 if (
140 input.restoreFiles !== false &&
141 !(yield* isCheckpointRestoreIsolated(projection.thread, scope, { fileSystem, projections }))
142 ) {
143 return yield* new CheckpointRollbackExecutionError({
144 reason: "shared-workspace",
145 threadId: input.threadId,
146 providerThreadId: input.providerThreadId,
147 checkpointId: input.checkpointId,
148 });
149 }
150​
151 const modelSelection = projection.thread.modelSelection;
152 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
153 thread: projection.thread,
154 modelSelection,
155 });
156 const existingSession = projection.providerSessions.find(
157 (candidate) => candidate.id === providerThread.providerSessionId,
158 );
159 const session = yield* sessions.open({
160 threadId: input.threadId,
161 providerSessionId: providerThread.providerSessionId,
162 modelSelection,
163 runtimePolicy: resolvedRuntimePolicy,
164 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
165 ...(providerThread.nativeThreadRef?.nativeId == null
166 ? {}
167 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
168 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
169 ? {}
170 : {
171 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
172 }),
173 });
174​
175 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
176 const runsToRollback = projection.runs.filter(
177 (run) => run.ordinal > targetOrdinal && run.status === "completed",
178 );
179 const providerThreadTurns = projection.providerTurns.filter(
180 (turn) => turn.providerThreadId === providerThread.id,
181 );
182 const rollbackTarget: ProviderAdapterV2RollbackTarget =
183 targetOrdinal === 0
184 ? {
185 type: "thread_start",
186 checkpointId: checkpoint.id,
187 appRunOrdinal: 0,
188 }
189 : yield* Effect.gen(function* () {
190 const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
191 const targetAttempt = projection.attempts.find(
192 (attempt) => attempt.id === targetRun?.activeAttemptId,
193 );
194 const targetTurn = projection.providerTurns.find(
195 (turn) =>
196 turn.id === targetAttempt?.providerTurnId ||
197 turn.runAttemptId === targetAttempt?.id,
198 );
199 if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
200 return yield* new CheckpointRollbackExecutionError({
201 reason: "provider-turn-unavailable",
202 threadId: input.threadId,
203 providerThreadId: input.providerThreadId,
204 checkpointId: input.checkpointId,
205 });
206 }
207 return {
208 type: "provider_turn" as const,
209 checkpointId: checkpoint.id,
210 appRunOrdinal: targetOrdinal,
211 providerTurn: targetTurn,
212 };
213 });
214​
215 const snapshot =
216 runsToRollback.length === 0
217 ? { providerThread }
218 : yield* session.rollbackThread({
219 providerThread,
220 target: rollbackTarget,
221 providerThreadTurns,
222 });
223 if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint });
224 const staleCheckpoints = projection.checkpoints.filter(
225 (candidate) =>
226 candidate.scopeId === scope.id &&
227 candidate.appRunOrdinal !== null &&
228 candidate.appRunOrdinal > targetOrdinal &&
229 candidate.status === "ready",
230 );
231 if (staleCheckpoints.length > 0) {
232 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
233 }
234​
235 const now = yield* DateTime.now;
236 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
237 Effect.map(
238 ids.allocate.event({ threadId: event.threadId }),
239 (id) =>
240 ({
241 ...event,
242 id,
243 }) as Event,
244 );
245 const events: Array<OrchestrationV2DomainEvent> = [];
246 events.push(
247 yield* makeEvent({
248 type: "provider-thread.updated",
249 threadId: input.threadId,
250 driver: providerThread.driver,
251 providerInstanceId: providerThread.providerInstanceId,
252 occurredAt: now,
253 payload: {
254 ...snapshot.providerThread,
255 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
256 updatedAt: now,
257 },
258 }),
259 );
260 for (const staleCheckpoint of staleCheckpoints) {
261 events.push(
262 yield* makeEvent({
263 type: "checkpoint.captured",
264 threadId: input.threadId,
265 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
266 nodeId: staleCheckpoint.nodeId,
267 providerInstanceId: providerThread.providerInstanceId,
268 occurredAt: now,
269 payload: { ...staleCheckpoint, status: "stale" },
270 }),
271 );
272 }
273 for (const run of runsToRollback) {
274 const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
275 events.push(
276 yield* makeEvent({
277 type: "run.updated",
278 threadId: input.threadId,
279 runId: run.id,
280 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
281 providerInstanceId: run.providerInstanceId,
282 occurredAt: now,
283 payload: { ...run, status: "rolled_back", completedAt: now },
284 }),
285 );
286 if (rootNode !== undefined) {
287 events.push(
288 yield* makeEvent({
289 type: "node.updated",
290 threadId: input.threadId,
291 runId: run.id,
292 nodeId: rootNode.id,
293 providerInstanceId: run.providerInstanceId,
294 occurredAt: now,
295 payload: { ...rootNode, status: "rolled_back", completedAt: now },
296 }),
297 );
298 }
299 }
300 yield* eventSink.write({ events });
301 });
302​
303 return CheckpointRollbackServiceV2.of({
304 execute: (input) =>
305 execute(input).pipe(
306 Effect.mapError((cause) =>
307 isCheckpointRollbackExecutionError(cause)
308 ? cause
309 : new CheckpointRollbackExecutionError({
310 reason: "unexpected-failure",
311 threadId: input.threadId,
312 providerThreadId: input.providerThreadId,
313 checkpointId: input.checkpointId,
314 cause,
315 }),
316 ),
317 ),
318 });
319 }),
320);