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

CheckpointRollbackService.ts

407 lines15.7 KB

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