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

CheckpointRollbackService.ts

362 lines13.4 KB

1import {
2 CheckpointId,
3 CheckpointScopeId,
4 latestProviderTurnForAttempt,
5 type OrchestrationV2DomainEvent,
6 ProviderThreadId,
7 ThreadId,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16​
17import {
18 isCheckpointRestoreIsolated,
19 SHARED_WORKSPACE_RESTORE_MESSAGE,
20} from "./CheckpointRestoreSafety.ts";
21import { CheckpointServiceV2 } from "./CheckpointService.ts";
22import { EventSinkV2 } from "./EventSink.ts";
23import { IdAllocatorV2 } from "./IdAllocator.ts";
24import { ProjectionStoreV2 } from "./ProjectionStore.ts";
25import * as ProjectStore from "./ProjectStore.ts";
26import type { ProviderAdapterV2RollbackTarget } from "./ProviderAdapter.ts";
27import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
28import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
29​
30export const ROLLBACK_FAILED_MESSAGE =
31 "The provider could not roll back this conversation. Try again; if it keeps failing, check the provider and server logs.";
32​
33export class CheckpointRollbackExecutionError extends Schema.TaggedError<CheckpointRollbackExecutionError>()(
34 "CheckpointRollbackExecutionError",
35 {
36 reason: Schema.Literals([
37 "rollback-target-invalid",
38 "active-provider-changed",
39 "provider-turn-unavailable",
40 "unexpected-failure",
41 "shared-workspace",
42 ]),
43 threadId: ThreadId,
44 providerThreadId: ProviderThreadId,
45 checkpointId: CheckpointId,
46 cause: Schema.optional(Schema.Defect()),
47 },
48) {
49 override get message(): string {
50 switch (this.reason) {
51 case "rollback-target-invalid":
52 return `Rollback target ${this.checkpointId} for provider thread ${this.providerThreadId} on thread ${this.threadId} is incomplete or invalid.`;
53 case "active-provider-changed":
54 return `Active provider changed before rollback target ${this.checkpointId} could execute on thread ${this.threadId}.`;
55 case "provider-turn-unavailable":
56 return `Provider turn for rollback target ${this.checkpointId} is unavailable on provider thread ${this.providerThreadId}.`;
57 case "shared-workspace":
58 return SHARED_WORKSPACE_RESTORE_MESSAGE;
59 case "unexpected-failure":
60 return ROLLBACK_FAILED_MESSAGE;
61 }
62 }
64​
65const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError);
66​
67export interface CheckpointRollbackServiceV2Shape {
68 readonly execute: (input: {
69 readonly threadId: ThreadId;
70 readonly providerThreadId: ProviderThreadId;
71 readonly checkpointId: CheckpointId;
72 readonly scopeId: CheckpointScopeId;
73 readonly restoreFiles?: boolean;
74 }) => Effect.Effect<void, CheckpointRollbackExecutionError>;
76​
77export class CheckpointRollbackServiceV2 extends Context.Service<
78 CheckpointRollbackServiceV2,
79 CheckpointRollbackServiceV2Shape
80>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}
81​
82export const layer: Layer.Layer<
83 CheckpointRollbackServiceV2,
84 never,
85 | CheckpointServiceV2
86 | EventSinkV2
87 | IdAllocatorV2
88 | ProjectionStoreV2
89 | ProviderSessionManagerV2
90 | RuntimePolicyV2
91 | FileSystem.FileSystem
92 | Path.Path
93 | ProjectStore.ProjectStoreV2
94> = Layer.effect(
95 CheckpointRollbackServiceV2,
96 Effect.gen(function* () {
97 const checkpoints = yield* CheckpointServiceV2;
98 const eventSink = yield* EventSinkV2;
99 const ids = yield* IdAllocatorV2;
100 const projections = yield* ProjectionStoreV2;
101 const sessions = yield* ProviderSessionManagerV2;
102 const runtimePolicy = yield* RuntimePolicyV2;
103 const fileSystem = yield* FileSystem.FileSystem;
104 const projects = yield* ProjectStore.ProjectStoreV2;
105 const path = yield* Path.Path;
106​
107 const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
108 readonly threadId: ThreadId;
109 readonly providerThreadId: ProviderThreadId;
110 readonly checkpointId: CheckpointId;
111 readonly scopeId: CheckpointScopeId;
112 readonly restoreFiles?: boolean;
113 }) {
114 const projection = yield* projections.getThreadRecords(input.threadId, [
115 "providerThreads",
116 "providerSessions",
117 "checkpoints",
118 "checkpointScopes",
119 "runs",
120 "attempts",
121 "nodes",
122 "providerTurns",
123 ]);
124 const providerThread = projection.providerThreads.find(
125 (candidate) => candidate.id === input.providerThreadId,
126 );
127 const checkpoint = projection.checkpoints.find(
128 (candidate) => candidate.id === input.checkpointId,
129 );
130 const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
131 if (
132 providerThread === undefined ||
133 providerThread.providerSessionId === null ||
134 checkpoint === undefined ||
135 scope === undefined ||
136 checkpoint.scopeId !== scope.id ||
137 checkpoint.status !== "ready"
138 ) {
139 return yield* new CheckpointRollbackExecutionError({
140 reason: "rollback-target-invalid",
141 threadId: input.threadId,
142 providerThreadId: input.providerThreadId,
143 checkpointId: input.checkpointId,
144 });
145 }
146 if (
147 providerThread.id !== projection.thread.activeProviderThreadId ||
148 providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId
149 ) {
150 return yield* new CheckpointRollbackExecutionError({
151 reason: "active-provider-changed",
152 threadId: input.threadId,
153 providerThreadId: input.providerThreadId,
154 checkpointId: input.checkpointId,
155 });
156 }
157​
158 if (
159 input.restoreFiles !== false &&
160 !(yield* isCheckpointRestoreIsolated(projection.thread, scope, {
161 fileSystem,
162 projections,
163 projects,
164 path,
165 }))
166 ) {
167 return yield* new CheckpointRollbackExecutionError({
168 reason: "shared-workspace",
169 threadId: input.threadId,
170 providerThreadId: input.providerThreadId,
171 checkpointId: input.checkpointId,
172 });
173 }
174​
175 const modelSelection = projection.thread.modelSelection;
176 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
177 thread: projection.thread,
178 modelSelection,
179 });
180 const existingSession = projection.providerSessions.find(
181 (candidate) => candidate.id === providerThread.providerSessionId,
182 );
183 const session = yield* sessions.open({
184 threadId: input.threadId,
185 providerSessionId: providerThread.providerSessionId,
186 modelSelection,
187 runtimePolicy: resolvedRuntimePolicy,
188 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
189 ...(providerThread.nativeThreadRef?.nativeId == null
190 ? {}
191 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
192 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
193 ? {}
194 : {
195 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
196 }),
197 });
198​
199 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
200 // Stopped and failed runs after the target leave the provider
201 // conversation too, so they must not stay visible.
202 const runsToRollback = projection.runs.filter(
203 (run) =>
204 run.ordinal > targetOrdinal &&
205 (run.status === "completed" ||
206 run.status === "interrupted" ||
207 run.status === "failed" ||
208 run.status === "cancelled"),
209 );
210 // Rolled-back turns stay in the audit history, but no longer exist in
211 // the provider conversation and must not be counted by a later rewind.
212 const rolledBackRunIds = new Set(
213 projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
214 );
215 const rolledBackAttemptIds = new Set(
216 projection.attempts
217 .filter((attempt) => rolledBackRunIds.has(attempt.runId))
218 .map((attempt) => attempt.id),
219 );
220 const providerThreadTurns = projection.providerTurns.filter(
221 (turn) =>
222 turn.providerThreadId === providerThread.id &&
223 (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
224 );
225 const rollbackTarget: ProviderAdapterV2RollbackTarget =
226 targetOrdinal === 0
227 ? {
228 type: "thread_start",
229 checkpointId: checkpoint.id,
230 appRunOrdinal: 0,
231 }
232 : yield* Effect.gen(function* () {
233 const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
234 const targetAttempt = projection.attempts.find(
235 (attempt) => attempt.id === targetRun?.activeAttemptId,
236 );
237 // A goal run can span several native turns; roll back to its last.
238 const targetTurn =
239 latestProviderTurnForAttempt(projection.providerTurns, targetAttempt?.id) ??
240 projection.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
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);