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 // Missing snapshots support conversation rewind only.
156 (checkpoint.status !== "ready" &&
157 !(input.restoreFiles === false && checkpoint.status === "missing"))
158 ) {
159 return yield* new CheckpointRollbackExecutionError({
160 reason: "rollback-target-invalid",
161 threadId: input.threadId,
162 providerThreadId: input.providerThreadId,
163 checkpointId: input.checkpointId,
164 });
165 }
166 if (
167 providerThread.id !== context.thread.activeProviderThreadId ||
168 providerThread.providerInstanceId !== context.thread.modelSelection.instanceId
169 ) {
170 return yield* new CheckpointRollbackExecutionError({
171 reason: "active-provider-changed",
172 threadId: input.threadId,
173 providerThreadId: input.providerThreadId,
174 checkpointId: input.checkpointId,
175 });
176 }
177
178 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
179 const rollbackTarget: ProviderAdapter.ProviderAdapterV2RollbackTarget =
180 targetOrdinal === 0
181 ? {
182 type: "thread_start",
183 checkpointId: checkpoint.id,
184 appRunOrdinal: 0,
185 }
186 : yield* Effect.gen(function* () {
187 const targetTurn =
188 latestProviderTurnForAttempt(context.providerTurns, targetAttempt?.id) ??
189 context.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
190 if (
191 targetAttempt === undefined ||
192 targetTurn === undefined ||
193 targetTurn.providerThreadId !== providerThread.id
194 ) {
195 return yield* new CheckpointRollbackExecutionError({
196 reason: "provider-turn-unavailable",
197 threadId: input.threadId,
198 providerThreadId: input.providerThreadId,
199 checkpointId: input.checkpointId,
200 });
201 }
202 const { attempt } = yield* projections.getProviderControlContext(input.threadId, {
203 providerThreadId: providerThread.id,
204 providerTurnId: targetTurn.id,
205 attemptId: targetAttempt.id,
206 });
207 const message =
208 attempt === undefined
209 ? undefined
210 : yield* projections.getRunMessage(input.threadId, attempt.runId);
211 return {
212 type: "provider_turn" as const,
213 checkpointId: checkpoint.id,
214 appRunOrdinal: targetOrdinal,
215 providerTurn: targetTurn,
216 ...(message === undefined ? {} : { message }),
217 };
218 });
219
220 const { worktreePath, branch } = context.thread;
221 // Recreated only where the server would have made it, as turn start does.
222 if (
223 worktreePath != null &&
224 branch != null &&
225 !(yield* fileSystem.exists(worktreePath)) &&
226 (yield* isManagedWorktreePath(worktreePath))
227 ) {
228 const project = yield* projects.get(context.thread.projectId);
229 if (Option.isSome(project)) {
230 yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot });
231 yield* gitWorkflow.createWorktree({
232 cwd: project.value.workspaceRoot,
233 refName: branch,
234 path: worktreePath,
235 });
236 }
237 }
238
239 if (
240 input.restoreFiles !== false &&
241 !(yield* isCheckpointRestoreIsolated(context.thread, scope, {
242 fileSystem,
243 projections,
244 projects,
245 path,
246 }))
247 ) {
248 return yield* new CheckpointRollbackExecutionError({
249 reason: "shared-workspace",
250 threadId: input.threadId,
251 providerThreadId: input.providerThreadId,
252 checkpointId: input.checkpointId,
253 });
254 }
255
256 const modelSelection = context.thread.modelSelection;
257 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
258 thread: context.thread,
259 modelSelection,
260 });
261 const existingSession = context.providerSession;
262 const session = yield* sessions.open({
263 threadId: input.threadId,
264 providerSessionId: providerThread.providerSessionId,
265 modelSelection,
266 runtimePolicy: resolvedRuntimePolicy,
267 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
268 ...(providerThread.nativeThreadRef?.nativeId == null
269 ? {}
270 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
271 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
272 ? {}
273 : {
274 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
275 }),
276 });
277
278 // Rolled-back turns remain in audit history but no longer exist in the provider conversation.
279 const rolledBackAttemptIds = new Set(context.rolledBackAttemptIds);
280 const providerThreadTurns = context.providerTurns.filter(
281 (turn) =>
282 turn.providerThreadId === providerThread.id &&
283 (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
284 );
285
286 const snapshot =
287 runsToRollback.length === 0
288 ? { providerThread }
289 : yield* session.rollbackThread({
290 providerThread,
291 target: rollbackTarget,
292 providerThreadTurns,
293 });
294 if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint });
295 if (staleCheckpoints.length > 0) {
296 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
297 }
298
299 // Lock against full-row thread writes that could restore the old native session after rollback.
300 yield* threadCommands.withLock(
301 input.threadId,
302 Effect.gen(function* () {
303 const now = yield* DateTime.now;
304 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
305 Effect.map(
306 ids.allocate.event({ threadId: event.threadId }),
307 (id) =>
308 ({
309 ...event,
310 id,
311 }) as Event,
312 );
313 const events: Array<OrchestrationV2DomainEvent> = [];
314 events.push(
315 yield* makeEvent({
316 type: "provider-thread.updated",
317 threadId: input.threadId,
318 driver: providerThread.driver,
319 providerInstanceId: providerThread.providerInstanceId,
320 occurredAt: now,
321 payload: {
322 ...snapshot.providerThread,
323 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
324 updatedAt: now,
325 },
326 }),
327 );
328 for (const staleCheckpoint of staleCheckpoints) {
329 events.push(
330 yield* makeEvent({
331 type: "checkpoint.captured",
332 threadId: input.threadId,
333 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
334 nodeId: staleCheckpoint.nodeId,
335 providerInstanceId: providerThread.providerInstanceId,
336 occurredAt: now,
337 payload: { ...staleCheckpoint, status: "stale" },
338 }),
339 );
340 }
341 for (const run of runsToRollback) {
342 const rootNode = context.rootNodes.find((candidate) => candidate.id === run.rootNodeId);
343 events.push(
344 yield* makeEvent({
345 type: "run.updated",
346 threadId: input.threadId,
347 runId: run.id,
348 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
349 providerInstanceId: run.providerInstanceId,
350 occurredAt: now,
351 payload: { ...run, status: "rolled_back", completedAt: now },
352 }),
353 );
354 if (rootNode !== undefined) {
355 events.push(
356 yield* makeEvent({
357 type: "node.updated",
358 threadId: input.threadId,
359 runId: run.id,
360 nodeId: rootNode.id,
361 providerInstanceId: run.providerInstanceId,
362 occurredAt: now,
363 payload: { ...rootNode, status: "rolled_back", completedAt: now },
364 }),
365 );
366 }
367 }
368 yield* eventSink.write({ events });
369 }),
370 );
371 });
372
373 return CheckpointRollbackServiceV2.of({
374 // The inner execute owns the rollback span; this wrapper selects the workspace lease.
375 execute: Effect.fnUntraced(
376 function* (input) {
377 // Storage cleanup removes worktrees under the same lease.
378 const thread = yield* projections.getThread(input.threadId);
379 yield* thread.worktreePath === null
380 ? execute(input)
381 : withWorkspaceLease(path.resolve(thread.worktreePath), execute(input));
382 },
383 (effect, input) =>
384 effect.pipe(
385 Effect.mapError((cause) =>
386 isCheckpointRollbackExecutionError(cause)
387 ? cause
388 : new CheckpointRollbackExecutionError({
389 reason: "unexpected-failure",
390 threadId: input.threadId,
391 providerThreadId: input.providerThreadId,
392 checkpointId: input.checkpointId,
393 cause,
394 }),
395 ),
396 ),
397 ),
398 });
399 }),
400);