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

CheckpointRollbackService.ts

572 lines23.5 KB

1import {
2 CheckpointId,
3 CheckpointScopeId,
4 type CommandId,
5 latestProviderTurnForAttempt,
6 type OrchestrationV2DomainEvent,
7 ProviderThreadId,
8 repositoryRewindCheckpoint,
9 ThreadId,
10 VcsProcessExitError,
11} from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as Schema from "effect/Schema";
21​
22import * as GitWorkflowService from "../git/GitWorkflowService.ts";
23import type * as ServerConfig from "../config.ts";
24import type * as ServerSettings from "../serverSettings.ts";
25import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
26import * as TaskFolders from "../workspace/TaskFolders.ts";
27import {
28 withCheckpointRestoreReservation,
29 withWorkspaceLease,
30} from "../workspace/workspaceLease.ts";
31import {
32 isCheckpointRestoreIsolated,
33 SHARED_WORKSPACE_RESTORE_MESSAGE,
34} from "./CheckpointRestoreSafety.ts";
35import { CheckpointRestoreError, CheckpointServiceV2 } from "./CheckpointService.ts";
36import { EventSinkV2 } from "./EventSink.ts";
37import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38import { ProjectionStoreV2 } from "./ProjectionStore.ts";
39import { GIT_INDEX_LOCKED_DETAIL } from "../vcs/VcsProcess.ts";
40import * as ProjectStore from "./ProjectStore.ts";
41import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
42import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
43import { RuntimePolicyAboveCeilingError, RuntimePolicyV2 } from "./RuntimePolicy.ts";
44import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
45​
46export const ROLLBACK_FAILED_MESSAGE =
47 "The provider could not roll back this conversation. Try again; if it keeps failing, check the provider and server logs.";
48​
49export class CheckpointRollbackExecutionError extends Schema.TaggedError<CheckpointRollbackExecutionError>()(
50 "CheckpointRollbackExecutionError",
51 {
52 reason: Schema.Literals([
53 "rollback-target-invalid",
54 "active-provider-changed",
55 "provider-turn-unavailable",
56 "unexpected-failure",
57 "shared-workspace",
58 ]),
59 threadId: ThreadId,
60 providerThreadId: ProviderThreadId,
61 checkpointId: CheckpointId,
62 cause: Schema.optional(Schema.Defect()),
63 },
64) {
65 override get message(): string {
66 switch (this.reason) {
67 case "rollback-target-invalid":
68 return `Rollback target ${this.checkpointId} for provider thread ${this.providerThreadId} on thread ${this.threadId} is incomplete or invalid.`;
69 case "active-provider-changed":
70 return `Active provider changed before rollback target ${this.checkpointId} could execute on thread ${this.threadId}.`;
71 case "provider-turn-unavailable":
72 return `Provider turn for rollback target ${this.checkpointId} is unavailable on provider thread ${this.providerThreadId}.`;
73 case "shared-workspace":
74 return SHARED_WORKSPACE_RESTORE_MESSAGE;
75 case "unexpected-failure":
76 return ROLLBACK_FAILED_MESSAGE;
77 }
78 }
80​
81const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError);
82const isVcsProcessExitError = Schema.is(VcsProcessExitError);
83const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);
84const isRuntimePolicyAboveCeilingError = Schema.is(RuntimePolicyAboveCeilingError);
85​
86/**
87 * The message clients see when a rollback fails. Only a held Git index lock
88 * gets its own explanation; other reasons carry internal ids or raw Git
89 * output, so they fall back to the generic message.
90 */
91export function rollbackFailureClientMessage(error: CheckpointRollbackExecutionError): string {
92 if (isRuntimePolicyAboveCeilingError(error.cause)) return error.cause.message;
93 const restoreCause = isCheckpointRestoreError(error.cause) ? error.cause.cause : undefined;
94 return isVcsProcessExitError(restoreCause) && restoreCause.detail === GIT_INDEX_LOCKED_DETAIL
95 ? GIT_INDEX_LOCKED_DETAIL
96 : ROLLBACK_FAILED_MESSAGE;
98​
99export interface CheckpointRollbackServiceV2Shape {
100 readonly execute: (input: {
101 readonly threadId: ThreadId;
102 readonly providerThreadId: ProviderThreadId;
103 readonly checkpointId: CheckpointId;
104 readonly scopeId: CheckpointScopeId;
105 readonly restoreFiles?: boolean;
106 /** The rewind command: names the request when repositories are reported as left unrestored. */
107 readonly requestId?: CommandId;
108 }) => Effect.Effect<void, CheckpointRollbackExecutionError>;
110​
111export class CheckpointRollbackServiceV2 extends Context.Service<
112 CheckpointRollbackServiceV2,
113 CheckpointRollbackServiceV2Shape
114>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}
115​
116export const layer: Layer.Layer<
117 CheckpointRollbackServiceV2,
118 never,
119 | CheckpointServiceV2
120 | GitWorkflowService.GitWorkflowService
121 | EventSinkV2
122 | IdAllocator.IdAllocatorV2
123 | ProjectionStoreV2
124 | ProviderSessionManagerV2
125 | RuntimePolicyV2
126 | FileSystem.FileSystem
127 | Path.Path
128 | ProjectStore.ProjectStoreV2
129 | ServerConfig.ServerConfig
130 | ServerSettings.ServerSettingsService
131 | TaskFolders.TaskFolders
132 | ThreadCommandExecutor.ThreadCommandExecutor
133> = Layer.effect(
134 CheckpointRollbackServiceV2,
135 Effect.gen(function* () {
136 const checkpoints = yield* CheckpointServiceV2;
137 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
138 const eventSink = yield* EventSinkV2;
139 const ids = yield* IdAllocator.IdAllocatorV2;
140 const projections = yield* ProjectionStoreV2;
141 const sessions = yield* ProviderSessionManagerV2;
142 const runtimePolicy = yield* RuntimePolicyV2;
143 const fileSystem = yield* FileSystem.FileSystem;
144 const projects = yield* ProjectStore.ProjectStoreV2;
145 const path = yield* Path.Path;
146 const taskFolders = yield* TaskFolders.TaskFolders;
147 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
148 const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
149​
150 const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
151 readonly threadId: ThreadId;
152 readonly providerThreadId: ProviderThreadId;
153 readonly checkpointId: CheckpointId;
154 readonly scopeId: CheckpointScopeId;
155 readonly restoreFiles?: boolean;
156 readonly requestId?: CommandId;
157 }) {
158 const context = yield* projections.getCheckpointRollbackContext(input.threadId, input);
159 const { providerThread, checkpoint, scope, targetAttempt, runsToRollback, staleCheckpoints } =
160 context;
161 const restoreFiles = input.restoreFiles !== false;
162 const { worktreePath, branch } = context.thread;
163 const taskFolder = worktreePath === null ? null : yield* taskFolders.find(worktreePath);
164 // A linked project folder is not a repository: it has no snapshot, by design.
165 const linkedProjectFolder = taskFolder !== null && !taskFolder.projectIsWorktree;
166 const invalidTarget = () =>
167 new CheckpointRollbackExecutionError({
168 reason: "rollback-target-invalid",
169 threadId: input.threadId,
170 providerThreadId: input.providerThreadId,
171 checkpointId: input.checkpointId,
172 });
173 if (
174 providerThread === undefined ||
175 providerThread.providerSessionId === null ||
176 checkpoint === undefined ||
177 scope === undefined ||
178 // A repository's checkpoints follow the thread's; they are not a place to rewind to.
179 typeof scope.repositoryPath === "string" ||
180 checkpoint.scopeId !== scope.id ||
181 // Missing or failed snapshots support conversation rewind; missing ones also restoring a
182 // task folder's repositories.
183 (checkpoint.status !== "ready" &&
184 !(checkpoint.status === "error" && !restoreFiles) &&
185 !(checkpoint.status === "missing" && (!restoreFiles || linkedProjectFolder)))
186 ) {
187 return yield* invalidTarget();
188 }
189 if (
190 providerThread.id !== context.thread.activeProviderThreadId ||
191 providerThread.providerInstanceId !== context.thread.modelSelection.instanceId
192 ) {
193 return yield* new CheckpointRollbackExecutionError({
194 reason: "active-provider-changed",
195 threadId: input.threadId,
196 providerThreadId: input.providerThreadId,
197 checkpointId: input.checkpointId,
198 });
199 }
200​
201 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
202 const rollbackTarget: ProviderAdapter.ProviderAdapterV2RollbackTarget =
203 targetOrdinal === 0
204 ? {
205 type: "thread_start",
206 checkpointId: checkpoint.id,
207 appRunOrdinal: 0,
208 }
209 : yield* Effect.gen(function* () {
210 const targetTurn =
211 latestProviderTurnForAttempt(context.providerTurns, targetAttempt?.id) ??
212 context.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
213 if (
214 targetAttempt === undefined ||
215 targetTurn === undefined ||
216 targetTurn.providerThreadId !== providerThread.id
217 ) {
218 return yield* new CheckpointRollbackExecutionError({
219 reason: "provider-turn-unavailable",
220 threadId: input.threadId,
221 providerThreadId: input.providerThreadId,
222 checkpointId: input.checkpointId,
223 });
224 }
225 const { attempt } = yield* projections.getProviderControlContext(input.threadId, {
226 providerThreadId: providerThread.id,
227 providerTurnId: targetTurn.id,
228 attemptId: targetAttempt.id,
229 });
230 const message =
231 attempt === undefined
232 ? undefined
233 : yield* projections.getRunMessage(input.threadId, attempt.runId);
234 return {
235 type: "provider_turn" as const,
236 checkpointId: checkpoint.id,
237 appRunOrdinal: targetOrdinal,
238 providerTurn: targetTurn,
239 ...(message === undefined ? {} : { message }),
240 };
241 });
242​
243 const isolated = isCheckpointRestoreIsolated(context.thread, scope, taskFolder, {
244 fileSystem,
245 projections,
246 projects,
247 path,
248 });
249 const sharedWorkspace = () =>
250 new CheckpointRollbackExecutionError({
251 reason: "shared-workspace",
252 threadId: input.threadId,
253 providerThreadId: input.providerThreadId,
254 checkpointId: input.checkpointId,
255 });
256​
257 if (taskFolder !== null && branch != null) {
258 // Cleanup can remove any of the folder's checkouts; the linked project folder has none.
259 yield* taskFolders.restore({
260 taskFolder,
261 branch,
262 recreate: (checkout) =>
263 gitWorkflow.pruneWorktrees({ cwd: checkout.repositoryPath }).pipe(
264 Effect.andThen(
265 gitWorkflow.createWorktree({
266 cwd: checkout.repositoryPath,
267 refName: branch,
268 path: checkout.worktreePath,
269 }),
270 ),
271 ),
272 });
273 } else if (worktreePath != null && branch != null) {
274 // Recreated only where the server would have made it, as turn start does.
275 // A failed removal can leave the folder without its checkout; only a file restore replaces it.
276 const leftover =
277 restoreFiles &&
278 (yield* fileSystem.exists(worktreePath)) &&
279 !(yield* fileSystem.exists(path.join(worktreePath, ".git")));
280 if (
281 (leftover || !(yield* fileSystem.exists(worktreePath))) &&
282 (yield* isManagedWorktreePath(worktreePath))
283 ) {
284 const project = yield* projects.get(context.thread.projectId);
285 if (Option.isSome(project)) {
286 const recreate = gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot }).pipe(
287 Effect.andThen(
288 gitWorkflow.createWorktree({
289 cwd: project.value.workspaceRoot,
290 refName: branch,
291 path: worktreePath,
292 }),
293 ),
294 );
295 if (leftover) {
296 if (!(yield* isolated)) return yield* sharedWorkspace();
297 // Set aside, not removed: a checkout that fails puts the folder and its files back.
298 yield* Effect.acquireUseRelease(
299 Effect.gen(function* () {
300 const aside = yield* fileSystem.makeTempDirectory({
301 directory: path.dirname(worktreePath),
302 prefix: ".t3-replaced-",
303 });
304 yield* fileSystem.rename(worktreePath, path.join(aside, "folder"));
305 return aside;
306 }),
307 () => recreate,
308 (aside, exit) =>
309 (Exit.isSuccess(exit)
310 ? Effect.void
311 : fileSystem
312 .remove(worktreePath, { recursive: true, force: true })
313 .pipe(
314 Effect.andThen(
315 fileSystem.rename(path.join(aside, "folder"), worktreePath),
316 ),
317 )
318 ).pipe(
319 Effect.andThen(fileSystem.remove(aside, { recursive: true, force: true })),
320 Effect.catchCause((cause) =>
321 Effect.logWarning("Edit from here left a worktree folder set aside", {
322 worktreePath,
323 setAside: path.join(aside, "folder"),
324 cause,
325 }),
326 ),
327 ),
328 );
329 } else {
330 yield* recreate;
331 }
332 }
333 }
334 }
335​
336 if (restoreFiles && !(yield* isolated)) return yield* sharedWorkspace();
337​
338 // Before the provider conversation changes: a rewind with nothing to restore is refused.
339 const readable =
340 restoreFiles && taskFolder !== null
341 ? yield* checkpoints.repositoryScopesIfReadable({
342 rootScope: scope,
343 projectId: context.thread.projectId,
344 worktreePath,
345 })
346 : [];
347 // Unknown repositories are not "none": the rewind would leave their changes unmentioned.
348 if (readable === null) {
349 return yield* new CheckpointRollbackExecutionError({
350 reason: "unexpected-failure",
351 threadId: input.threadId,
352 providerThreadId: input.providerThreadId,
353 checkpointId: input.checkpointId,
354 cause: new Error("The thread's repositories could not be read."),
355 });
356 }
357 const repositories = readable;
358 const recorded =
359 repositories.length === 0
360 ? []
361 : (yield* projections.getCheckpointContext(input.threadId)).checkpoints;
362 const repositoryTargets = repositories.flatMap((repository) => {
363 const target = repositoryRewindCheckpoint(
364 recorded.filter((candidate) => candidate.scopeId === repository.id),
365 targetOrdinal,
366 );
367 return target === null ? [] : [{ scope: repository, checkpoint: target }];
368 });
369 // Changed by a discarded run, with no snapshot of how it was before: left as it is.
370 const unrestorable = repositories.filter(
371 (repository) =>
372 !repositoryTargets.some((target) => target.scope.id === repository.id) &&
373 recorded.some(
374 (candidate) =>
375 candidate.scopeId === repository.id &&
376 candidate.ordinalWithinScope > targetOrdinal &&
377 (candidate.status === "ready" || candidate.runId !== null),
378 ),
379 );
380 if (unrestorable.length > 0) {
381 yield* Effect.logWarning("Edit from here cannot restore repositories without a snapshot", {
382 threadId: input.threadId,
383 repositories: unrestorable.map((repository) => repository.cwd),
384 });
385 }
386 const restoreTargets = [
387 ...(checkpoint.status === "ready" ? [{ scope, checkpoint }] : []),
388 ...repositoryTargets,
389 ];
390 if (restoreFiles && restoreTargets.length === 0) return yield* invalidTarget();
391​
392 const modelSelection = context.thread.modelSelection;
393 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
394 thread: context.thread,
395 modelSelection,
396 });
397 const existingSession = context.providerSession;
398 const session = yield* sessions.open({
399 threadId: input.threadId,
400 providerSessionId: providerThread.providerSessionId,
401 modelSelection,
402 runtimePolicy: resolvedRuntimePolicy,
403 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
404 ...(providerThread.nativeThreadRef?.nativeId == null
405 ? {}
406 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
407 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
408 ? {}
409 : {
410 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
411 }),
412 });
413​
414 // Rolled-back turns remain in audit history but no longer exist in the provider conversation.
415 const rolledBackAttemptIds = new Set(context.rolledBackAttemptIds);
416 const providerThreadTurns = context.providerTurns.filter(
417 (turn) =>
418 turn.providerThreadId === providerThread.id &&
419 (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
420 );
421​
422 const snapshot =
423 runsToRollback.length === 0
424 ? { providerThread }
425 : yield* session.rollbackThread({
426 providerThread,
427 target: rollbackTarget,
428 providerThreadTurns,
429 });
430 if (restoreFiles) {
431 yield* checkpoints.restore({ targets: restoreTargets, scopes: [scope, ...repositories] });
432 }
433 const staleScopeCheckpoints = staleCheckpoints.filter((stale) => stale.scopeId === scope.id);
434 if (staleScopeCheckpoints.length > 0) {
435 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleScopeCheckpoints });
436 }
437 yield* checkpoints.discardRepositorySnapshots({
438 rootScope: scope,
439 thread: context.thread,
440 ordinals: runsToRollback.map((run) => run.ordinal),
441 });
442​
443 // Lock against full-row thread writes that could restore the old native session after rollback.
444 yield* threadCommands.withLock(
445 input.threadId,
446 Effect.gen(function* () {
447 const now = yield* DateTime.now;
448 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
449 Effect.map(
450 ids.allocate.event({ threadId: event.threadId }),
451 (id) =>
452 ({
453 ...event,
454 id,
455 }) as Event,
456 );
457 const events: Array<OrchestrationV2DomainEvent> = [];
458 // First, so a client that sees the runs rolled back already knows what was left.
459 if (input.requestId !== undefined && unrestorable.length > 0) {
460 const thread = yield* projections.getThread(input.threadId);
461 events.push(
462 yield* makeEvent({
463 type: "thread.metadata-updated",
464 threadId: input.threadId,
465 providerInstanceId: thread.providerInstanceId,
466 occurredAt: now,
467 payload: {
468 ...thread,
469 rollbackUnrestored: {
470 requestId: input.requestId,
471 repositories: unrestorable.map(
472 (repository) => repository.label ?? path.basename(repository.cwd),
473 ),
474 },
475 updatedAt: now,
476 },
477 }),
478 );
479 }
480 events.push(
481 yield* makeEvent({
482 type: "provider-thread.updated",
483 threadId: input.threadId,
484 driver: providerThread.driver,
485 providerInstanceId: providerThread.providerInstanceId,
486 occurredAt: now,
487 payload: {
488 ...snapshot.providerThread,
489 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
490 updatedAt: now,
491 },
492 }),
493 );
494 for (const staleCheckpoint of staleCheckpoints) {
495 events.push(
496 yield* makeEvent({
497 type: "checkpoint.captured",
498 threadId: input.threadId,
499 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
500 nodeId: staleCheckpoint.nodeId,
501 providerInstanceId: providerThread.providerInstanceId,
502 occurredAt: now,
503 payload: { ...staleCheckpoint, status: "stale" },
504 }),
505 );
506 }
507 for (const run of runsToRollback) {
508 const rootNode = context.rootNodes.find((candidate) => candidate.id === run.rootNodeId);
509 events.push(
510 yield* makeEvent({
511 type: "run.updated",
512 threadId: input.threadId,
513 runId: run.id,
514 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
515 providerInstanceId: run.providerInstanceId,
516 occurredAt: now,
517 payload: { ...run, status: "rolled_back", completedAt: now },
518 }),
519 );
520 if (rootNode !== undefined) {
521 events.push(
522 yield* makeEvent({
523 type: "node.updated",
524 threadId: input.threadId,
525 runId: run.id,
526 nodeId: rootNode.id,
527 providerInstanceId: run.providerInstanceId,
528 occurredAt: now,
529 payload: { ...rootNode, status: "rolled_back", completedAt: now },
530 }),
531 );
532 }
533 }
534 yield* eventSink.write({ events });
535 }),
536 );
537 });
538​
539 return CheckpointRollbackServiceV2.of({
540 // The inner execute owns the rollback span; this wrapper selects the workspace lease.
541 execute: Effect.fnUntraced(
542 function* (input) {
543 // Storage cleanup removes worktrees under the same lease.
544 const thread = yield* projections.getThread(input.threadId);
545 if (thread.worktreePath === null) return yield* execute(input);
546 const worktreePath = path.resolve(thread.worktreePath);
547 const rollback = withWorkspaceLease(worktreePath, execute(input));
548 // Shared-workspace restores are rejected and conversation-only rewinds
549 // touch no files; reserving for them would stall turn starts on the
550 // slow provider rollback for nothing.
551 yield* input.restoreFiles === false
552 ? rollback
553 : withCheckpointRestoreReservation(fileSystem, path, worktreePath, rollback);
554 },
555 (effect, input) =>
556 effect.pipe(
557 Effect.mapError((cause) =>
558 isCheckpointRollbackExecutionError(cause)
559 ? cause
560 : new CheckpointRollbackExecutionError({
561 reason: "unexpected-failure",
562 threadId: input.threadId,
563 providerThreadId: input.providerThreadId,
564 checkpointId: input.checkpointId,
565 cause,
566 }),
567 ),
568 ),
569 ),
570 });
571 }),
572);