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

CheckpointRollbackService.ts

296 lines11.1 KB

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 }
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>;
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 ...(providerThread.nativeThreadRef?.nativeId == null
142 ? {}
143 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
144 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
145 ? {}
146 : {
147 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
148 }),
149 });
150​
151 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
152 const runsToRollback = projection.runs.filter(
153 (run) => run.ordinal > targetOrdinal && run.status === "completed",
154 );
155 const providerThreadTurns = projection.providerTurns.filter(
156 (turn) => turn.providerThreadId === providerThread.id,
157 );
158 const rollbackTarget: ProviderAdapterV2RollbackTarget =
159 targetOrdinal === 0
160 ? {
161 type: "thread_start",
162 checkpointId: checkpoint.id,
163 appRunOrdinal: 0,
164 }
165 : yield* Effect.gen(function* () {
166 const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
167 const targetAttempt = projection.attempts.find(
168 (attempt) => attempt.id === targetRun?.activeAttemptId,
169 );
170 const targetTurn = projection.providerTurns.find(
171 (turn) =>
172 turn.id === targetAttempt?.providerTurnId ||
173 turn.runAttemptId === targetAttempt?.id,
174 );
175 if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
176 return yield* new CheckpointRollbackExecutionError({
177 reason: "provider-turn-unavailable",
178 threadId: input.threadId,
179 providerThreadId: input.providerThreadId,
180 checkpointId: input.checkpointId,
181 });
182 }
183 return {
184 type: "provider_turn" as const,
185 checkpointId: checkpoint.id,
186 appRunOrdinal: targetOrdinal,
187 providerTurn: targetTurn,
188 };
189 });
190​
191 yield* checkpoints.restore({ scope, checkpoint });
192 const snapshot =
193 runsToRollback.length === 0
194 ? { providerThread }
195 : yield* session.rollbackThread({
196 providerThread,
197 target: rollbackTarget,
198 providerThreadTurns,
199 });
200 const staleCheckpoints = projection.checkpoints.filter(
201 (candidate) =>
202 candidate.scopeId === scope.id &&
203 candidate.appRunOrdinal !== null &&
204 candidate.appRunOrdinal > targetOrdinal &&
205 candidate.status === "ready",
206 );
207 if (staleCheckpoints.length > 0) {
208 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
209 }
210​
211 const now = yield* DateTime.now;
212 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
213 Effect.map(
214 ids.allocate.event({ threadId: event.threadId }),
215 (id) =>
216 ({
217 ...event,
218 id,
219 }) as Event,
220 );
221 const events: Array<OrchestrationV2DomainEvent> = [];
222 events.push(
223 yield* makeEvent({
224 type: "provider-thread.updated",
225 threadId: input.threadId,
226 driver: providerThread.driver,
227 providerInstanceId: providerThread.providerInstanceId,
228 occurredAt: now,
229 payload: {
230 ...snapshot.providerThread,
231 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
232 updatedAt: now,
233 },
234 }),
235 );
236 for (const staleCheckpoint of staleCheckpoints) {
237 events.push(
238 yield* makeEvent({
239 type: "checkpoint.captured",
240 threadId: input.threadId,
241 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
242 nodeId: staleCheckpoint.nodeId,
243 providerInstanceId: providerThread.providerInstanceId,
244 occurredAt: now,
245 payload: { ...staleCheckpoint, status: "stale" },
246 }),
247 );
248 }
249 for (const run of runsToRollback) {
250 const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
251 events.push(
252 yield* makeEvent({
253 type: "run.updated",
254 threadId: input.threadId,
255 runId: run.id,
256 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
257 providerInstanceId: run.providerInstanceId,
258 occurredAt: now,
259 payload: { ...run, status: "rolled_back", completedAt: now },
260 }),
261 );
262 if (rootNode !== undefined) {
263 events.push(
264 yield* makeEvent({
265 type: "node.updated",
266 threadId: input.threadId,
267 runId: run.id,
268 nodeId: rootNode.id,
269 providerInstanceId: run.providerInstanceId,
270 occurredAt: now,
271 payload: { ...rootNode, status: "rolled_back", completedAt: now },
272 }),
273 );
274 }
275 }
276 yield* eventSink.write({ events });
277 });
278​
279 return CheckpointRollbackServiceV2.of({
280 execute: (input) =>
281 execute(input).pipe(
282 Effect.mapError((cause) =>
283 isCheckpointRollbackExecutionError(cause)
284 ? cause
285 : new CheckpointRollbackExecutionError({
286 reason: "unexpected-failure",
287 threadId: input.threadId,
288 providerThreadId: input.providerThreadId,
289 checkpointId: input.checkpointId,
290 cause,
291 }),
292 ),
293 ),
294 });
295 }),
296);