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