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

CheckpointRollbackService.ts

423 lines16.5 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 projection = yield* projections.getThreadRecords(input.threadId, [
145 "providerThreads",
146 "providerSessions",
147 "checkpoints",
148 "checkpointScopes",
149 "runs",
150 "attempts",
151 "nodes",
152 "providerTurns",
153 ]);
154 const providerThread = projection.providerThreads.find(
155 (candidate) => candidate.id === input.providerThreadId,
156 );
157 const checkpoint = projection.checkpoints.find(
158 (candidate) => candidate.id === input.checkpointId,
159 );
160 const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
161 if (
162 providerThread === undefined ||
163 providerThread.providerSessionId === null ||
164 checkpoint === undefined ||
165 scope === undefined ||
166 checkpoint.scopeId !== scope.id ||
167 checkpoint.status !== "ready"
168 ) {
169 return yield* new CheckpointRollbackExecutionError({
170 reason: "rollback-target-invalid",
171 threadId: input.threadId,
172 providerThreadId: input.providerThreadId,
173 checkpointId: input.checkpointId,
174 });
175 }
176 if (
177 providerThread.id !== projection.thread.activeProviderThreadId ||
178 providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId
179 ) {
180 return yield* new CheckpointRollbackExecutionError({
181 reason: "active-provider-changed",
182 threadId: input.threadId,
183 providerThreadId: input.providerThreadId,
184 checkpointId: input.checkpointId,
185 });
186 }
187​
188 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
189 const rollbackTarget: ProviderAdapter.ProviderAdapterV2RollbackTarget =
190 targetOrdinal === 0
191 ? {
192 type: "thread_start",
193 checkpointId: checkpoint.id,
194 appRunOrdinal: 0,
195 }
196 : yield* Effect.gen(function* () {
197 const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
198 const targetAttempt = projection.attempts.find(
199 (attempt) => attempt.id === targetRun?.activeAttemptId,
200 );
201 const targetTurn =
202 latestProviderTurnForAttempt(projection.providerTurns, targetAttempt?.id) ??
203 projection.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
204 if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
205 return yield* new CheckpointRollbackExecutionError({
206 reason: "provider-turn-unavailable",
207 threadId: input.threadId,
208 providerThreadId: input.providerThreadId,
209 checkpointId: input.checkpointId,
210 });
211 }
212 return {
213 type: "provider_turn" as const,
214 checkpointId: checkpoint.id,
215 appRunOrdinal: targetOrdinal,
216 providerTurn: targetTurn,
217 };
218 });
219​
220 const { worktreePath, branch } = projection.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(projection.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(projection.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 = projection.thread.modelSelection;
257 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
258 thread: projection.thread,
259 modelSelection,
260 });
261 const existingSession = projection.providerSessions.find(
262 (candidate) => candidate.id === providerThread.providerSessionId,
263 );
264 const session = yield* sessions.open({
265 threadId: input.threadId,
266 providerSessionId: providerThread.providerSessionId,
267 modelSelection,
268 runtimePolicy: resolvedRuntimePolicy,
269 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
270 ...(providerThread.nativeThreadRef?.nativeId == null
271 ? {}
272 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
273 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
274 ? {}
275 : {
276 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
277 }),
278 });
279​
280 const runsToRollback = projection.runs.filter(
281 (run) =>
282 run.ordinal > targetOrdinal &&
283 (run.status === "completed" ||
284 run.status === "interrupted" ||
285 run.status === "failed" ||
286 run.status === "cancelled"),
287 );
288 // Rolled-back turns stay in the audit history, but no longer exist in
289 // the provider conversation and must not be counted by a later rewind.
290 const rolledBackRunIds = new Set(
291 projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
292 );
293 const rolledBackAttemptIds = new Set(
294 projection.attempts
295 .filter((attempt) => rolledBackRunIds.has(attempt.runId))
296 .map((attempt) => attempt.id),
297 );
298 const providerThreadTurns = projection.providerTurns.filter(
299 (turn) =>
300 turn.providerThreadId === providerThread.id &&
301 (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
302 );
303​
304 const snapshot =
305 runsToRollback.length === 0
306 ? { providerThread }
307 : yield* session.rollbackThread({
308 providerThread,
309 target: rollbackTarget,
310 providerThreadTurns,
311 });
312 if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint });
313 const staleCheckpoints = projection.checkpoints.filter(
314 (candidate) =>
315 candidate.scopeId === scope.id &&
316 candidate.appRunOrdinal !== null &&
317 candidate.appRunOrdinal > targetOrdinal &&
318 candidate.status === "ready",
319 );
320 if (staleCheckpoints.length > 0) {
321 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
322 }
323​
324 // Thread commands write full provider thread rows under this lock. Without
325 // it, a message sent during the rollback can plan against the old native
326 // session and commit after this, undoing the provider's fork.
327 yield* threadCommands.withLock(
328 input.threadId,
329 Effect.gen(function* () {
330 const now = yield* DateTime.now;
331 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
332 Effect.map(
333 ids.allocate.event({ threadId: event.threadId }),
334 (id) =>
335 ({
336 ...event,
337 id,
338 }) as Event,
339 );
340 const events: Array<OrchestrationV2DomainEvent> = [];
341 events.push(
342 yield* makeEvent({
343 type: "provider-thread.updated",
344 threadId: input.threadId,
345 driver: providerThread.driver,
346 providerInstanceId: providerThread.providerInstanceId,
347 occurredAt: now,
348 payload: {
349 ...snapshot.providerThread,
350 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
351 updatedAt: now,
352 },
353 }),
354 );
355 for (const staleCheckpoint of staleCheckpoints) {
356 events.push(
357 yield* makeEvent({
358 type: "checkpoint.captured",
359 threadId: input.threadId,
360 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
361 nodeId: staleCheckpoint.nodeId,
362 providerInstanceId: providerThread.providerInstanceId,
363 occurredAt: now,
364 payload: { ...staleCheckpoint, status: "stale" },
365 }),
366 );
367 }
368 for (const run of runsToRollback) {
369 const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
370 events.push(
371 yield* makeEvent({
372 type: "run.updated",
373 threadId: input.threadId,
374 runId: run.id,
375 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
376 providerInstanceId: run.providerInstanceId,
377 occurredAt: now,
378 payload: { ...run, status: "rolled_back", completedAt: now },
379 }),
380 );
381 if (rootNode !== undefined) {
382 events.push(
383 yield* makeEvent({
384 type: "node.updated",
385 threadId: input.threadId,
386 runId: run.id,
387 nodeId: rootNode.id,
388 providerInstanceId: run.providerInstanceId,
389 occurredAt: now,
390 payload: { ...rootNode, status: "rolled_back", completedAt: now },
391 }),
392 );
393 }
394 }
395 yield* eventSink.write({ events });
396 }),
397 );
398 });
399​
400 return CheckpointRollbackServiceV2.of({
401 execute: (input) =>
402 Effect.gen(function* () {
403 // Storage cleanup removes worktrees under the same lease.
404 const { thread } = yield* projections.getThreadRecords(input.threadId, []);
405 yield* thread.worktreePath === null
406 ? execute(input)
407 : withWorkspaceLease(path.resolve(thread.worktreePath), execute(input));
408 }).pipe(
409 Effect.mapError((cause) =>
410 isCheckpointRollbackExecutionError(cause)
411 ? cause
412 : new CheckpointRollbackExecutionError({
413 reason: "unexpected-failure",
414 threadId: input.threadId,
415 providerThreadId: input.providerThreadId,
416 checkpointId: input.checkpointId,
417 cause,
418 }),
419 ),
420 ),
421 });
422 }),
423);