Open History to see the last commit
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 * as 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;
84}
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("continues a live turn whose session the adapter never marked running", () => {
125 const projection = makeProjection();
126 // Codex, Claude, Cursor and ACP sessions stay "ready" for their whole life.
127 const withSessionStatus = (status: string) =>
128 ({
129 ...projection,
130 providerSessions: [{ ...projection.providerSessions[0]!, status }],
131 }) as OrchestrationV2ThreadProjection;
132 for (const status of ["starting", "ready", "running", "waiting"])
133 assert.equal(restartContinuationRun(withSessionStatus(status))?.id, runId, status);
134 for (const status of ["stopped", "error"])
135 assert.isUndefined(restartContinuationRun(withSessionStatus(status)), status);
136});
137
138it("recovers an admitted continuation after another crash before provider start", () => {
139 const projection = makeProjection();
140 const starting = {
141 ...projection,
142 runs: [
143 {
144 ...projection.runs[0]!,
145 status: "starting" as const,
146 restartContinuationOfRunId: RunId.make("run:previous-crash"),
147 },
148 ],
149 providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }],
150 providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }],
151 providerTurns: [],
152 };
153 assert.equal(restartContinuationRun(starting)?.id, runId);
154});
155
156it("continues a settled root run only when the restart cancelled its background work", () => {
157 const projection = makeProjection();
158 const settled = {
159 ...projection,
160 runs: [{ ...projection.runs[0]!, status: "completed" as const }],
161 providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }],
162 providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }],
163 providerTurns: [],
164 };
165 const lostWork = new Set([providerThreadId]);
166 assert.isUndefined(restartContinuationRun(settled));
167 assert.equal(restartContinuationRun(settled, lostWork)?.id, runId);
168 // Work an older provider thread launched (before a provider switch) is not
169 // this run's: its provider was never told about it and cannot continue it.
170 assert.isUndefined(
171 restartContinuationRun(settled, new Set([ProviderThreadId.make("provider-thread:claude")])),
172 );
173 for (const invalid of [
174 { ...settled, thread: { ...settled.thread, archivedAt: {} } },
175 { ...settled, thread: { ...settled.thread, deletedAt: {} } },
176 { ...settled, runs: [{ ...settled.runs[0]!, status: "failed" as const }] },
177 {
178 ...settled,
179 providerThreads: [{ ...settled.providerThreads[0]!, nativeThreadRef: null }],
180 },
181 ])
182 assert.isUndefined(
183 restartContinuationRun(invalid as OrchestrationV2ThreadProjection, lostWork),
184 );
185});
186
187it.effect("prompts a settled thread's continuation with the note of its lost work", () =>
188 Effect.gen(function* () {
189 const base = makeProjection();
190 const work = [{ kind: "shell" as const, label: "sleep 25 && echo DONE" }];
191 const projection = {
192 ...base,
193 runs: [{ ...base.runs[0]!, status: "completed", restartCancelledBackgroundWork: work }],
194 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
195 } as unknown as OrchestrationV2ThreadProjection;
196 const commands: Parameters<
197 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
198 >[0][] = [];
199 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
200 Effect.provide(
201 Layer.merge(
202 Layer.mock(ThreadManagementService.ThreadManagementService)({
203 getThreadRecords: () => Effect.succeed(projection),
204 dispatch: (command) => {
205 commands.push(command);
206 return Effect.succeed({} as never);
207 },
208 }),
209 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
210 ),
211 ),
212 );
213 assert.lengthOf(commands, 1);
214 const command = commands[0]!;
215 assert.equal(
216 command.type === "message.dispatch" ? command.restartContinuationOfRunId : null,
217 runId,
218 );
219 assert.include(
220 command.type === "message.dispatch" ? command.text : "",
221 "sleep 25 && echo DONE",
222 );
223 assert.notInclude(command.type === "message.dispatch" ? command.text : "", "Continue where");
224 }),
225);
226
227it.effect("does not continue a failed run that lost background work", () =>
228 Effect.gen(function* () {
229 const base = makeProjection();
230 const projection = {
231 ...base,
232 runs: [
233 {
234 ...base.runs[0]!,
235 status: "failed",
236 restartCancelledBackgroundWork: [{ kind: "shell" as const, label: "sleep 25" }],
237 },
238 ],
239 providerTurns: [{ ...base.providerTurns[0]!, status: "failed" }],
240 } as unknown as OrchestrationV2ThreadProjection;
241 const commands: Parameters<
242 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
243 >[0][] = [];
244 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
245 Effect.provide(
246 Layer.merge(
247 Layer.mock(ThreadManagementService.ThreadManagementService)({
248 getThreadRecords: () => Effect.succeed(projection),
249 dispatch: (command) => {
250 commands.push(command);
251 return Effect.succeed({} as never);
252 },
253 }),
254 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
255 ),
256 ),
257 );
258 assert.lengthOf(commands, 0);
259 }),
260);
261
262for (const [enabled, projectOverride] of [
263 [false, undefined],
264 [true, undefined],
265 [false, true],
266 [true, false],
267] as const) {
268 it.effect(
269 `atomically records restart intent with cancellation when opt-in is ${enabled} and project override is ${projectOverride}`,
270 () =>
271 Effect.gen(function* () {
272 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
273 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
274 Effect.provide(
275 Layer.mergeAll(
276 ServerSettings.layerTest({
277 continueThreadsAfterServerUpdate: enabled,
278 projectSettingsOverrides:
279 projectOverride === undefined
280 ? {}
281 : {
282 [ProjectId.make("restart-project")]: {
283 continueThreadsAfterServerUpdate: projectOverride,
284 },
285 },
286 }),
287 Layer.mock(ProjectionStore.ProjectionStoreV2)({
288 getRecoveryThreadIds: () => Effect.succeed([threadId]),
289 getRuntimeRecoveryProjection: () => Effect.succeed(makeProjection()),
290 }),
291 Layer.mock(EventSink.EventSinkV2)({
292 commitCommand: (input) => {
293 committed = input;
294 return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
295 },
296 }),
297 IdAllocator.layer,
298 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
299 runRecoveryOnce: Effect.succeed(false),
300 }),
301 Layer.mock(EffectOutbox.EffectOutboxV2)({
302 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
303 }),
304 ),
305 ),
306 );
307 yield* recovery.reconcile("startup");
308 assert.isDefined(committed);
309 assert.isTrue(
310 committed!.events.some(
311 (event) => event.type === "run.updated" && event.payload.status === "cancelled",
312 ),
313 );
314 assert.lengthOf(committed!.effects, (projectOverride ?? enabled) ? 1 : 0);
315 if (projectOverride ?? enabled)
316 assert.deepEqual(committed!.effects[0]?.request, {
317 type: "provider-runtime.continue",
318 sourceRunId: runId,
319 });
320 }),
321 );
322}
323
324it.effect("does not duplicate delivery and yields to newer user work or opt-out", () =>
325 Effect.gen(function* () {
326 let projection = makeProjection();
327 projection = { ...projection, runs: [{ ...projection.runs[0]!, status: "cancelled" }] };
328 const commands: Parameters<
329 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
330 >[0][] = [];
331 const threads = Layer.mock(ThreadManagementService.ThreadManagementService)({
332 getThreadRecords: () => Effect.succeed(projection),
333 dispatch: (command) => {
334 commands.push(command);
335 if (command.type === "message.dispatch")
336 projection = { ...projection, messages: [{ id: command.messageId } as never] };
337 return Effect.succeed({} as never);
338 },
339 });
340 const enabled = Layer.merge(
341 threads,
342 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
343 );
344 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(Effect.provide(enabled));
345 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(Effect.provide(enabled));
346 assert.lengthOf(commands, 1);
347 assert.match(String(commands[0]!.commandId), /run:restart$/);
348 if (commands[0]!.type === "message.dispatch")
349 assert.equal(commands[0]!.restartContinuationOfRunId, runId);
350 projection = {
351 ...projection,
352 messages: [],
353 runs: [
354 ...projection.runs,
355 {
356 ...projection.runs[0]!,
357 id: RunId.make("run:user-newer"),
358 ordinal: 2,
359 status: "completed",
360 },
361 ],
362 };
363 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(Effect.provide(enabled));
364 assert.lengthOf(commands, 1);
365 projection = { ...projection, runs: [projection.runs[0]!] };
366 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
367 Effect.provide(
368 Layer.merge(threads, ServerSettings.layerTest({ continueThreadsAfterServerUpdate: false })),
369 ),
370 );
371 assert.lengthOf(commands, 1);
372 }),
373);
374
375it.effect("prepares no continuation for background work another provider thread launched", () =>
376 Effect.gen(function* () {
377 const base = makeProjection();
378 const claudeThreadId = ProviderThreadId.make("provider-thread:claude");
379 // A Claude turn left a background subagent open, then the thread switched
380 // to Codex and its turn settled. Recovery would cancel Claude's work.
381 const projection = {
382 ...base,
383 runs: [{ ...base.runs[0]!, status: "completed" }],
384 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
385 turnItems: [
386 {
387 id: "turn-item:claude-subagent",
388 runId: RunId.make("run:claude"),
389 providerThreadId: claudeThreadId,
390 type: "subagent",
391 status: "running",
392 },
393 ],
394 } as unknown as OrchestrationV2ThreadProjection;
395 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
396 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
397 Effect.provide(
398 Layer.mergeAll(
399 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
400 Layer.mock(ProjectionStore.ProjectionStoreV2)({
401 getRecoveryThreadIds: () => Effect.succeed([threadId]),
402 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
403 }),
404 Layer.mock(EventSink.EventSinkV2)({
405 writeWithEffects: (input) =>
406 Effect.sync(() => {
407 writes.push(input);
408 return [];
409 }),
410 }),
411 IdAllocator.layer,
412 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
413 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
414 ),
415 ),
416 );
417 yield* recovery.prepareForShutdown;
418 assert.lengthOf(writes, 0);
419 // The same work on the Codex run's own provider thread is continued.
420 const ownWork = {
421 ...projection,
422 turnItems: [{ ...projection.turnItems[0]!, providerThreadId }],
423 } as OrchestrationV2ThreadProjection;
424 const ownRecovery = yield* ProviderRuntimeRecovery.make.pipe(
425 Effect.provide(
426 Layer.mergeAll(
427 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
428 Layer.mock(ProjectionStore.ProjectionStoreV2)({
429 getRecoveryThreadIds: () => Effect.succeed([threadId]),
430 getRuntimeRecoveryProjection: () => Effect.succeed(ownWork),
431 }),
432 Layer.mock(EventSink.EventSinkV2)({
433 writeWithEffects: (input) =>
434 Effect.sync(() => {
435 writes.push(input);
436 return [];
437 }),
438 }),
439 IdAllocator.layer,
440 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
441 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
442 ),
443 ),
444 );
445 yield* ownRecovery.prepareForShutdown;
446 assert.deepEqual(
447 writes.map((write) => write.effects[0]?.request),
448 [{ type: "provider-runtime.continue", sourceRunId: runId }],
449 );
450 }),
451);
452
453it.effect("does not cancel or resume a run that completes while shutdown intent commits", () =>
454 Effect.gen(function* () {
455 let projection = makeProjection();
456 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
457 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
458 Effect.provide(
459 Layer.mergeAll(
460 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
461 Layer.mock(ProjectionStore.ProjectionStoreV2)({
462 getRecoveryThreadIds: () => Effect.succeed([threadId]),
463 getRuntimeRecoveryProjection: () => Effect.sync(() => projection),
464 }),
465 Layer.mock(EventSink.EventSinkV2)({
466 writeWithEffects: (input) =>
467 Effect.sync(() => {
468 assert.lengthOf(input.events, 0);
469 assert.equal(input.effects[0]?.request.type, "provider-runtime.continue");
470 projection = {
471 ...projection,
472 runs: [{ ...projection.runs[0]!, status: "completed" }],
473 };
474 return [];
475 }),
476 commitCommand: (input) =>
477 Effect.sync(() => {
478 commits.push(input);
479 return { committed: true, cancelledEffectCount: 0 } as never;
480 }),
481 }),
482 IdAllocator.layer,
483 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
484 runRecoveryOnce: Effect.succeed(false),
485 }),
486 Layer.mock(EffectOutbox.EffectOutboxV2)({
487 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
488 }),
489 ),
490 ),
491 );
492 yield* recovery.prepareForShutdown;
493 yield* recovery.reconcile("shutdown");
494 assert.isFalse(
495 commits.some((commit) => commit.events.some((event) => event.type === "run.updated")),
496 );
497 let dispatched = false;
498 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
499 Effect.provide(
500 Layer.mergeAll(
501 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
502 Layer.mock(ThreadManagementService.ThreadManagementService)({
503 getThreadRecords: () => Effect.succeed(projection),
504 dispatch: () =>
505 Effect.sync(() => {
506 dispatched = true;
507 return {} as never;
508 }),
509 }),
510 ),
511 ),
512 );
513 assert.isFalse(dispatched);
514 }),
515);