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

CheckpointRollbackService.ts

382 lines14.9 KB

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