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