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

RestartContinuation.test.ts

315 lines11.0 KB

1import { assert, it } from "@effect/vitest";
2import {
3 ProjectId,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 ProviderSessionId,
7 ProviderThreadId,
8 ProviderTurnId,
9 RunAttemptId,
10 RunId,
11 ThreadId,
12 type OrchestrationV2ThreadProjection,
13} from "@t3tools/contracts";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as ServerSettings from "../serverSettings.ts";
17import { restartContinuationRun, continueRestartedRun } from "./RestartContinuation.ts";
18import { ThreadManagementService } from "./ThreadManagementService.ts";
19import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
20import * as ProjectionStore from "./ProjectionStore.ts";
21import * as EventSink from "./EventSink.ts";
22import * as IdAllocator from "./IdAllocator.ts";
23import * as EffectWorker from "./EffectWorker.ts";
24import * as EffectOutbox from "./EffectOutbox.ts";
25​
26const threadId = ThreadId.make("thread:restart");
27const runId = RunId.make("run:restart");
28const instanceId = ProviderInstanceId.make("codex");
29const driver = ProviderDriverKind.make("codex");
30const providerThreadId = ProviderThreadId.make("provider-thread:restart");
31const sessionId = ProviderSessionId.make("session:restart");
32const attemptId = RunAttemptId.make("attempt:restart");
33​
34function makeProjection() {
35 return {
36 thread: {
37 id: threadId,
38 projectId: ProjectId.make("restart-project"),
39 providerInstanceId: instanceId,
40 archivedAt: null,
41 deletedAt: null,
42 },
43 runs: [
44 {
45 id: runId,
46 ordinal: 1,
47 providerInstanceId: instanceId,
48 modelSelection: { instanceId, model: "gpt-6" },
49 providerThreadId,
50 activeAttemptId: attemptId,
51 status: "running",
52 },
53 ],
54 providerThreads: [
55 {
56 id: providerThreadId,
57 appThreadId: threadId,
58 ownerNodeId: null,
59 driver,
60 providerInstanceId: instanceId,
61 providerSessionId: sessionId,
62 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
63 status: "active",
64 },
65 ],
66 providerSessions: [
67 { id: sessionId, driver, providerInstanceId: instanceId, status: "running" },
68 ],
69 providerTurns: [
70 {
71 id: ProviderTurnId.make("turn:restart"),
72 providerThreadId,
73 runAttemptId: attemptId,
74 status: "running",
75 },
76 ],
77 runtimeRequests: [],
78 attempts: [],
79 nodes: [],
80 subagents: [],
81 messages: [],
82 turnItems: [],
83 } as unknown as OrchestrationV2ThreadProjection;
85​
86it("requires matching saved native state for an unfinished root run", () => {
87 const projection = makeProjection();
88 assert.equal(restartContinuationRun(projection)?.id, runId);
89 for (const invalid of [
90 { ...projection, thread: { ...projection.thread, archivedAt: {} } },
91 { ...projection, thread: { ...projection.thread, deletedAt: {} } },
92 {
93 ...projection,
94 thread: { ...projection.thread, providerInstanceId: ProviderInstanceId.make("other") },
95 },
96 {
97 ...projection,
98 providerThreads: [{ ...projection.providerThreads[0]!, nativeThreadRef: null }],
99 },
100 {
101 ...projection,
102 providerSessions: [
103 {
104 ...projection.providerSessions[0]!,
105 providerInstanceId: ProviderInstanceId.make("other"),
106 },
107 ],
108 },
109 { ...projection, providerTurns: [] },
110 ...[
111 "queued",
112 "preparing",
113 "starting",
114 "waiting",
115 "completed",
116 "cancelled",
117 "failed",
118 "interrupted",
119 ].map((status) => ({ ...projection, runs: [{ ...projection.runs[0]!, status }] })),
120 ])
121 assert.isUndefined(restartContinuationRun(invalid as OrchestrationV2ThreadProjection));
122});
123​
124it("recovers an admitted continuation after another crash before provider start", () => {
125 const projection = makeProjection();
126 const starting = {
127 ...projection,
128 runs: [
129 {
130 ...projection.runs[0]!,
131 status: "starting" as const,
132 restartContinuationOfRunId: RunId.make("run:previous-crash"),
133 },
134 ],
135 providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }],
136 providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }],
137 providerTurns: [],
138 };
139 assert.equal(restartContinuationRun(starting)?.id, runId);
140});
141​
142for (const [enabled, projectOverride] of [
143 [false, undefined],
144 [true, undefined],
145 [false, true],
146 [true, false],
147] as const) {
148 it.effect(
149 `atomically records restart intent with cancellation when opt-in is ${enabled} and project override is ${projectOverride}`,
150 () =>
151 Effect.gen(function* () {
152 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
153 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
154 Effect.provide(
155 Layer.mergeAll(
156 ServerSettings.layerTest({
157 continueThreadsAfterServerUpdate: enabled,
158 projectSettingsOverrides:
159 projectOverride === undefined
160 ? {}
161 : {
162 [ProjectId.make("restart-project")]: {
163 continueThreadsAfterServerUpdate: projectOverride,
164 },
165 },
166 }),
167 Layer.mock(ProjectionStore.ProjectionStoreV2)({
168 getRecoveryThreadIds: () => Effect.succeed([threadId]),
169 getRuntimeRecoveryProjection: () => Effect.succeed(makeProjection()),
170 }),
171 Layer.mock(EventSink.EventSinkV2)({
172 commitCommand: (input) => {
173 committed = input;
174 return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
175 },
176 }),
177 IdAllocator.layer,
178 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
179 runRecoveryOnce: Effect.succeed(false),
180 }),
181 Layer.mock(EffectOutbox.EffectOutboxV2)({
182 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
183 }),
184 ),
185 ),
186 );
187 yield* recovery.reconcile("startup");
188 assert.isDefined(committed);
189 assert.isTrue(
190 committed!.events.some(
191 (event) => event.type === "run.updated" && event.payload.status === "cancelled",
192 ),
193 );
194 assert.lengthOf(committed!.effects, (projectOverride ?? enabled) ? 1 : 0);
195 if (projectOverride ?? enabled)
196 assert.deepEqual(committed!.effects[0]?.request, {
197 type: "provider-runtime.continue",
198 sourceRunId: runId,
199 });
200 }),
201 );
203​
204it.effect("does not duplicate delivery and yields to newer user work or opt-out", () =>
205 Effect.gen(function* () {
206 let projection = makeProjection();
207 projection = { ...projection, runs: [{ ...projection.runs[0]!, status: "cancelled" }] };
208 const commands: Parameters<ThreadManagementService["Service"]["dispatch"]>[0][] = [];
209 const threads = Layer.mock(ThreadManagementService)({
210 getThreadProjection: () => Effect.succeed(projection),
211 dispatch: (command) => {
212 commands.push(command);
213 if (command.type === "message.dispatch")
214 projection = { ...projection, messages: [{ id: command.messageId } as never] };
215 return Effect.succeed({} as never);
216 },
217 });
218 const enabled = Layer.merge(
219 threads,
220 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
221 );
222 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(Effect.provide(enabled));
223 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(Effect.provide(enabled));
224 assert.lengthOf(commands, 1);
225 assert.match(String(commands[0]!.commandId), /run:restart$/);
226 if (commands[0]!.type === "message.dispatch")
227 assert.equal(commands[0]!.restartContinuationOfRunId, runId);
228 projection = {
229 ...projection,
230 messages: [],
231 runs: [
232 ...projection.runs,
233 {
234 ...projection.runs[0]!,
235 id: RunId.make("run:user-newer"),
236 ordinal: 2,
237 status: "completed",
238 },
239 ],
240 };
241 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(Effect.provide(enabled));
242 assert.lengthOf(commands, 1);
243 projection = { ...projection, runs: [projection.runs[0]!] };
244 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
245 Effect.provide(
246 Layer.merge(threads, ServerSettings.layerTest({ continueThreadsAfterServerUpdate: false })),
247 ),
248 );
249 assert.lengthOf(commands, 1);
250 }),
251);
252​
253it.effect("does not cancel or resume a run that completes while shutdown intent commits", () =>
254 Effect.gen(function* () {
255 let projection = makeProjection();
256 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
257 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
258 Effect.provide(
259 Layer.mergeAll(
260 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
261 Layer.mock(ProjectionStore.ProjectionStoreV2)({
262 getRecoveryThreadIds: () => Effect.succeed([threadId]),
263 getRuntimeRecoveryProjection: () => Effect.sync(() => projection),
264 }),
265 Layer.mock(EventSink.EventSinkV2)({
266 writeWithEffects: (input) =>
267 Effect.sync(() => {
268 assert.lengthOf(input.events, 0);
269 assert.equal(input.effects[0]?.request.type, "provider-runtime.continue");
270 projection = {
271 ...projection,
272 runs: [{ ...projection.runs[0]!, status: "completed" }],
273 };
274 return [];
275 }),
276 commitCommand: (input) =>
277 Effect.sync(() => {
278 commits.push(input);
279 return { committed: true, cancelledEffectCount: 0 } as never;
280 }),
281 }),
282 IdAllocator.layer,
283 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
284 runRecoveryOnce: Effect.succeed(false),
285 }),
286 Layer.mock(EffectOutbox.EffectOutboxV2)({
287 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
288 }),
289 ),
290 ),
291 );
292 yield* recovery.prepareForShutdown;
293 yield* recovery.reconcile("shutdown");
294 assert.isFalse(
295 commits.some((commit) => commit.events.some((event) => event.type === "run.updated")),
296 );
297 let dispatched = false;
298 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
299 Effect.provide(
300 Layer.mergeAll(
301 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
302 Layer.mock(ThreadManagementService)({
303 getThreadProjection: () => Effect.succeed(projection),
304 dispatch: () =>
305 Effect.sync(() => {
306 dispatched = true;
307 return {} as never;
308 }),
309 }),
310 ),
311 ),
312 );
313 assert.isFalse(dispatched);
314 }),
315);