Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointScopeId,
4 type OrchestrationV2DomainEvent,
5 ProviderThreadId,
6 ThreadId,
7} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as DateTime from "effect/DateTime";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Schema from "effect/Schema";
13
14import { CheckpointServiceV2 } from "./CheckpointService.ts";
15import { EventSinkV2 } from "./EventSink.ts";
16import { IdAllocatorV2 } from "./IdAllocator.ts";
17import { ProjectionStoreV2 } from "./ProjectionStore.ts";
18import type { ProviderAdapterV2RollbackTarget } from "./ProviderAdapter.ts";
19import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
20import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
21
22export class CheckpointRollbackExecutionError extends Schema.TaggedError<CheckpointRollbackExecutionError>()(
23 "CheckpointRollbackExecutionError",
24 {
25 reason: Schema.Literals([
26 "rollback-target-invalid",
27 "active-provider-changed",
28 "provider-turn-unavailable",
29 "unexpected-failure",
30 ]),
31 threadId: ThreadId,
32 providerThreadId: ProviderThreadId,
33 checkpointId: CheckpointId,
34 cause: Schema.optional(Schema.Defect()),
35 },
36) {
37 override get message(): string {
38 switch (this.reason) {
39 case "rollback-target-invalid":
40 return `Rollback target ${this.checkpointId} for provider thread ${this.providerThreadId} on thread ${this.threadId} is incomplete or invalid.`;
41 case "active-provider-changed":
42 return `Active provider changed before rollback target ${this.checkpointId} could execute on thread ${this.threadId}.`;
43 case "provider-turn-unavailable":
44 return `Provider turn for rollback target ${this.checkpointId} is unavailable on provider thread ${this.providerThreadId}.`;
45 case "unexpected-failure":
46 return `Failed to execute rollback target ${this.checkpointId} on provider thread ${this.providerThreadId} for thread ${this.threadId}.`;
47 }
48 }
49}
50
51const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError);
52
53export interface CheckpointRollbackServiceV2Shape {
54 readonly execute: (input: {
55 readonly threadId: ThreadId;
56 readonly providerThreadId: ProviderThreadId;
57 readonly checkpointId: CheckpointId;
58 readonly scopeId: CheckpointScopeId;
59 readonly restoreFiles?: boolean;
60 }) => Effect.Effect<void, CheckpointRollbackExecutionError>;
61}
62
63export class CheckpointRollbackServiceV2 extends Context.Service<
64 CheckpointRollbackServiceV2,
65 CheckpointRollbackServiceV2Shape
66>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}
67
68export const layer: Layer.Layer<
69 CheckpointRollbackServiceV2,
70 never,
71 | CheckpointServiceV2
72 | EventSinkV2
73 | IdAllocatorV2
74 | ProjectionStoreV2
75 | ProviderSessionManagerV2
76 | RuntimePolicyV2
77> = Layer.effect(
78 CheckpointRollbackServiceV2,
79 Effect.gen(function* () {
80 const checkpoints = yield* CheckpointServiceV2;
81 const eventSink = yield* EventSinkV2;
82 const ids = yield* IdAllocatorV2;
83 const projections = yield* ProjectionStoreV2;
84 const sessions = yield* ProviderSessionManagerV2;
85 const runtimePolicy = yield* RuntimePolicyV2;
86
87 const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
88 readonly threadId: ThreadId;
89 readonly providerThreadId: ProviderThreadId;
90 readonly checkpointId: CheckpointId;
91 readonly scopeId: CheckpointScopeId;
92 readonly restoreFiles?: boolean;
93 }) {
94 const projection = yield* projections.getThreadProjection(input.threadId);
95 const providerThread = projection.providerThreads.find(
96 (candidate) => candidate.id === input.providerThreadId,
97 );
98 const checkpoint = projection.checkpoints.find(
99 (candidate) => candidate.id === input.checkpointId,
100 );
101 const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
102 if (
103 providerThread === undefined ||
104 providerThread.providerSessionId === null ||
105 checkpoint === undefined ||
106 scope === undefined ||
107 checkpoint.scopeId !== scope.id ||
108 checkpoint.status !== "ready"
109 ) {
110 return yield* new CheckpointRollbackExecutionError({
111 reason: "rollback-target-invalid",
112 threadId: input.threadId,
113 providerThreadId: input.providerThreadId,
114 checkpointId: input.checkpointId,
115 });
116 }
117 if (
118 providerThread.id !== projection.thread.activeProviderThreadId ||
119 providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId
120 ) {
121 return yield* new CheckpointRollbackExecutionError({
122 reason: "active-provider-changed",
123 threadId: input.threadId,
124 providerThreadId: input.providerThreadId,
125 checkpointId: input.checkpointId,
126 });
127 }
128
129 const modelSelection = projection.thread.modelSelection;
130 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
131 thread: projection.thread,
132 modelSelection,
133 });
134 const existingSession = projection.providerSessions.find(
135 (candidate) => candidate.id === providerThread.providerSessionId,
136 );
137 const session = yield* sessions.open({
138 threadId: input.threadId,
139 providerSessionId: providerThread.providerSessionId,
140 modelSelection,
141 runtimePolicy: resolvedRuntimePolicy,
142 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
143 ...(providerThread.nativeThreadRef?.nativeId == null
144 ? {}
145 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
146 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
147 ? {}
148 : {
149 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
150 }),
151 });
152
153 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
154 const runsToRollback = projection.runs.filter(
155 (run) => run.ordinal > targetOrdinal && run.status === "completed",
156 );
157 const providerThreadTurns = projection.providerTurns.filter(
158 (turn) => turn.providerThreadId === providerThread.id,
159 );
160 const rollbackTarget: ProviderAdapterV2RollbackTarget =
161 targetOrdinal === 0
162 ? {
163 type: "thread_start",
164 checkpointId: checkpoint.id,
165 appRunOrdinal: 0,
166 }
167 : yield* Effect.gen(function* () {
168 const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
169 const targetAttempt = projection.attempts.find(
170 (attempt) => attempt.id === targetRun?.activeAttemptId,
171 );
172 const targetTurn = projection.providerTurns.find(
173 (turn) =>
174 turn.id === targetAttempt?.providerTurnId ||
175 turn.runAttemptId === targetAttempt?.id,
176 );
177 if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
178 return yield* new CheckpointRollbackExecutionError({
179 reason: "provider-turn-unavailable",
180 threadId: input.threadId,
181 providerThreadId: input.providerThreadId,
182 checkpointId: input.checkpointId,
183 });
184 }
185 return {
186 type: "provider_turn" as const,
187 checkpointId: checkpoint.id,
188 appRunOrdinal: targetOrdinal,
189 providerTurn: targetTurn,
190 };
191 });
192
193 const snapshot =
194 runsToRollback.length === 0
195 ? { providerThread }
196 : yield* session.rollbackThread({
197 providerThread,
198 target: rollbackTarget,
199 providerThreadTurns,
200 });
201 if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint });
202 const staleCheckpoints = projection.checkpoints.filter(
203 (candidate) =>
204 candidate.scopeId === scope.id &&
205 candidate.appRunOrdinal !== null &&
206 candidate.appRunOrdinal > targetOrdinal &&
207 candidate.status === "ready",
208 );
209 if (staleCheckpoints.length > 0) {
210 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
211 }
212
213 const now = yield* DateTime.now;
214 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
215 Effect.map(
216 ids.allocate.event({ threadId: event.threadId }),
217 (id) =>
218 ({
219 ...event,
220 id,
221 }) as Event,
222 );
223 const events: Array<OrchestrationV2DomainEvent> = [];
224 events.push(
225 yield* makeEvent({
226 type: "provider-thread.updated",
227 threadId: input.threadId,
228 driver: providerThread.driver,
229 providerInstanceId: providerThread.providerInstanceId,
230 occurredAt: now,
231 payload: {
232 ...snapshot.providerThread,
233 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
234 updatedAt: now,
235 },
236 }),
237 );
238 for (const staleCheckpoint of staleCheckpoints) {
239 events.push(
240 yield* makeEvent({
241 type: "checkpoint.captured",
242 threadId: input.threadId,
243 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
244 nodeId: staleCheckpoint.nodeId,
245 providerInstanceId: providerThread.providerInstanceId,
246 occurredAt: now,
247 payload: { ...staleCheckpoint, status: "stale" },
248 }),
249 );
250 }
251 for (const run of runsToRollback) {
252 const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
253 events.push(
254 yield* makeEvent({
255 type: "run.updated",
256 threadId: input.threadId,
257 runId: run.id,
258 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
259 providerInstanceId: run.providerInstanceId,
260 occurredAt: now,
261 payload: { ...run, status: "rolled_back", completedAt: now },
262 }),
263 );
264 if (rootNode !== undefined) {
265 events.push(
266 yield* makeEvent({
267 type: "node.updated",
268 threadId: input.threadId,
269 runId: run.id,
270 nodeId: rootNode.id,
271 providerInstanceId: run.providerInstanceId,
272 occurredAt: now,
273 payload: { ...rootNode, status: "rolled_back", completedAt: now },
274 }),
275 );
276 }
277 }
278 yield* eventSink.write({ events });
279 });
280
281 return CheckpointRollbackServiceV2.of({
282 execute: (input) =>
283 execute(input).pipe(
284 Effect.mapError((cause) =>
285 isCheckpointRollbackExecutionError(cause)
286 ? cause
287 : new CheckpointRollbackExecutionError({
288 reason: "unexpected-failure",
289 threadId: input.threadId,
290 providerThreadId: input.providerThreadId,
291 checkpointId: input.checkpointId,
292 cause,
293 }),
294 ),
295 ),
296 });
297 }),
298);