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

CheckpointRollbackService.ts

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