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.TaggedErrorClass<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 }) => Effect.Effect<void, CheckpointRollbackExecutionError>;
60}
61
62export class CheckpointRollbackServiceV2 extends Context.Service<
63 CheckpointRollbackServiceV2,
64 CheckpointRollbackServiceV2Shape
65>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}
66
67export const layer: Layer.Layer<
68 CheckpointRollbackServiceV2,
69 never,
70 | CheckpointServiceV2
71 | EventSinkV2
72 | IdAllocatorV2
73 | ProjectionStoreV2
74 | ProviderSessionManagerV2
75 | RuntimePolicyV2
76> = Layer.effect(
77 CheckpointRollbackServiceV2,
78 Effect.gen(function* () {
79 const checkpoints = yield* CheckpointServiceV2;
80 const eventSink = yield* EventSinkV2;
81 const ids = yield* IdAllocatorV2;
82 const projections = yield* ProjectionStoreV2;
83 const sessions = yield* ProviderSessionManagerV2;
84 const runtimePolicy = yield* RuntimePolicyV2;
85
86 const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
87 readonly threadId: ThreadId;
88 readonly providerThreadId: ProviderThreadId;
89 readonly checkpointId: CheckpointId;
90 readonly scopeId: CheckpointScopeId;
91 }) {
92 const projection = yield* projections.getThreadProjection(input.threadId);
93 const providerThread = projection.providerThreads.find(
94 (candidate) => candidate.id === input.providerThreadId,
95 );
96 const checkpoint = projection.checkpoints.find(
97 (candidate) => candidate.id === input.checkpointId,
98 );
99 const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
100 if (
101 providerThread === undefined ||
102 providerThread.providerSessionId === null ||
103 checkpoint === undefined ||
104 scope === undefined ||
105 checkpoint.scopeId !== scope.id ||
106 checkpoint.status !== "ready"
107 ) {
108 return yield* new CheckpointRollbackExecutionError({
109 reason: "rollback-target-invalid",
110 threadId: input.threadId,
111 providerThreadId: input.providerThreadId,
112 checkpointId: input.checkpointId,
113 });
114 }
115 if (
116 providerThread.id !== projection.thread.activeProviderThreadId ||
117 providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId
118 ) {
119 return yield* new CheckpointRollbackExecutionError({
120 reason: "active-provider-changed",
121 threadId: input.threadId,
122 providerThreadId: input.providerThreadId,
123 checkpointId: input.checkpointId,
124 });
125 }
126
127 const modelSelection = projection.thread.modelSelection;
128 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
129 thread: projection.thread,
130 modelSelection,
131 });
132 const existingSession = projection.providerSessions.find(
133 (candidate) => candidate.id === providerThread.providerSessionId,
134 );
135 const session = yield* sessions.open({
136 threadId: input.threadId,
137 providerSessionId: providerThread.providerSessionId,
138 modelSelection,
139 runtimePolicy: resolvedRuntimePolicy,
140 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
141 });
142
143 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
144 const runsToRollback = projection.runs.filter(
145 (run) => run.ordinal > targetOrdinal && run.status === "completed",
146 );
147 const providerThreadTurns = projection.providerTurns.filter(
148 (turn) => turn.providerThreadId === providerThread.id,
149 );
150 const rollbackTarget: ProviderAdapterV2RollbackTarget =
151 targetOrdinal === 0
152 ? {
153 type: "thread_start",
154 checkpointId: checkpoint.id,
155 appRunOrdinal: 0,
156 }
157 : yield* Effect.gen(function* () {
158 const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
159 const targetAttempt = projection.attempts.find(
160 (attempt) => attempt.id === targetRun?.activeAttemptId,
161 );
162 const targetTurn = projection.providerTurns.find(
163 (turn) =>
164 turn.id === targetAttempt?.providerTurnId ||
165 turn.runAttemptId === targetAttempt?.id,
166 );
167 if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
168 return yield* new CheckpointRollbackExecutionError({
169 reason: "provider-turn-unavailable",
170 threadId: input.threadId,
171 providerThreadId: input.providerThreadId,
172 checkpointId: input.checkpointId,
173 });
174 }
175 return {
176 type: "provider_turn" as const,
177 checkpointId: checkpoint.id,
178 appRunOrdinal: targetOrdinal,
179 providerTurn: targetTurn,
180 };
181 });
182
183 yield* checkpoints.restore({ scope, checkpoint });
184 const snapshot =
185 runsToRollback.length === 0
186 ? { providerThread }
187 : yield* session.rollbackThread({
188 providerThread,
189 target: rollbackTarget,
190 providerThreadTurns,
191 });
192 const staleCheckpoints = projection.checkpoints.filter(
193 (candidate) =>
194 candidate.scopeId === scope.id &&
195 candidate.appRunOrdinal !== null &&
196 candidate.appRunOrdinal > targetOrdinal &&
197 candidate.status === "ready",
198 );
199 if (staleCheckpoints.length > 0) {
200 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
201 }
202
203 const now = yield* DateTime.now;
204 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
205 Effect.map(
206 ids.allocate.event({ threadId: event.threadId }),
207 (id) =>
208 ({
209 ...event,
210 id,
211 }) as Event,
212 );
213 const events: Array<OrchestrationV2DomainEvent> = [];
214 events.push(
215 yield* makeEvent({
216 type: "provider-thread.updated",
217 threadId: input.threadId,
218 driver: providerThread.driver,
219 providerInstanceId: providerThread.providerInstanceId,
220 occurredAt: now,
221 payload: {
222 ...snapshot.providerThread,
223 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
224 updatedAt: now,
225 },
226 }),
227 );
228 for (const staleCheckpoint of staleCheckpoints) {
229 events.push(
230 yield* makeEvent({
231 type: "checkpoint.captured",
232 threadId: input.threadId,
233 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
234 nodeId: staleCheckpoint.nodeId,
235 providerInstanceId: providerThread.providerInstanceId,
236 occurredAt: now,
237 payload: { ...staleCheckpoint, status: "stale" },
238 }),
239 );
240 }
241 for (const run of runsToRollback) {
242 const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
243 events.push(
244 yield* makeEvent({
245 type: "run.updated",
246 threadId: input.threadId,
247 runId: run.id,
248 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
249 providerInstanceId: run.providerInstanceId,
250 occurredAt: now,
251 payload: { ...run, status: "rolled_back", completedAt: now },
252 }),
253 );
254 if (rootNode !== undefined) {
255 events.push(
256 yield* makeEvent({
257 type: "node.updated",
258 threadId: input.threadId,
259 runId: run.id,
260 nodeId: rootNode.id,
261 providerInstanceId: run.providerInstanceId,
262 occurredAt: now,
263 payload: { ...rootNode, status: "rolled_back", completedAt: now },
264 }),
265 );
266 }
267 }
268 yield* eventSink.write({ events });
269 });
270
271 return CheckpointRollbackServiceV2.of({
272 execute: (input) =>
273 execute(input).pipe(
274 Effect.mapError((cause) =>
275 isCheckpointRollbackExecutionError(cause)
276 ? cause
277 : new CheckpointRollbackExecutionError({
278 reason: "unexpected-failure",
279 threadId: input.threadId,
280 providerThreadId: input.providerThreadId,
281 checkpointId: input.checkpointId,
282 cause,
283 }),
284 ),
285 ),
286 });
287 }),
288);