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

CheckpointRollbackService.ts

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