Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CheckpointId,
4 CheckpointScopeId,
5 CommandId,
6 NodeId,
7 ProviderSessionId,
8 ProviderThreadId,
9 ProviderTurnId,
10 RunAttemptId,
11 RunId,
12 ThreadId,
13 VcsProcessExitError,
14} from "@t3tools/contracts";
15import * as Cause from "effect/Cause";
16import * as DateTime from "effect/DateTime";
17import * as Deferred from "effect/Deferred";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Ref from "effect/Ref";
23
24import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
25import * as CheckpointService from "./CheckpointService.ts";
26import * as EffectOutbox from "./EffectOutbox.ts";
27import * as EffectWorker from "./EffectWorker.ts";
28import * as RunFinalizationService from "./RunFinalizationService.ts";
29import * as ProviderSessionManager from "./ProviderSessionManager.ts";
30import * as ProviderTurnControlService from "./ProviderTurnControlService.ts";
31import * as ProviderTurnStartService from "./ProviderTurnStartService.ts";
32import * as RuntimeRequestService from "./RuntimeRequestService.ts";
33import * as ThreadTitleRegenerationService from "./ThreadTitleRegenerationService.ts";
34import * as ThreadManagementService from "./ThreadManagementService.ts";
35import * as ServerSettings from "../serverSettings.ts";
36
37const threadId = ThreadId.make("thread:effect-worker-restart");
38const oldSessionId = ProviderSessionId.make("provider-session:effect-worker-restart:old");
39const providerThreadId = ProviderThreadId.make("provider-thread:effect-worker-restart");
40const providerTurnId = ProviderTurnId.make("provider-turn:effect-worker-restart");
41const attemptId = RunAttemptId.make("run-attempt:effect-worker-restart");
42const runId = RunId.make("run:effect-worker-restart");
43
44function restartEffect(
45 now: DateTime.Utc,
46 sessionTransition: NonNullable<
47 Extract<
48 EffectOutbox.OrchestrationEffectV2["request"],
49 { readonly type: "provider-turn.restart" }
50 >["sessionTransition"]
51 >,
52): EffectOutbox.OrchestrationEffectV2 {
53 const timestamp = DateTime.formatIso(now);
54 return {
55 id: `effect:restart:${sessionTransition.type}`,
56 commandId: CommandId.make(`command:restart:${sessionTransition.type}`),
57 threadId,
58 request: {
59 type: "provider-turn.restart",
60 providerSessionId: oldSessionId,
61 providerThreadId,
62 providerTurnId,
63 interruptedAttemptId: attemptId,
64 runId,
65 sessionTransition,
66 },
67 status: "running",
68 attemptCount: 1,
69 availableAt: timestamp,
70 leaseOwner: "test-worker",
71 leaseExpiresAt: timestamp,
72 createdAt: timestamp,
73 updatedAt: timestamp,
74 completedAt: null,
75 lastError: null,
76 };
77}
78
79function layerExecutorFor(input: {
80 readonly events: Ref.Ref<ReadonlyArray<string>>;
81 readonly failFirstStart?: Ref.Ref<boolean>;
82 readonly threads?: Partial<ThreadManagementService.ThreadManagementService["Service"]>;
83 readonly continueAfterRestart?: boolean;
84 readonly interrupt?: ProviderTurnControlService.ProviderTurnControlServiceV2Shape["interrupt"];
85 readonly rollback?: CheckpointRollbackService.CheckpointRollbackServiceV2Shape["execute"];
86}) {
87 const record = (event: string) => Ref.update(input.events, (events) => [...events, event]);
88 const layerDependencies = Layer.mergeAll(
89 Layer.succeed(
90 ProviderTurnControlService.ProviderTurnControlServiceV2,
91 ProviderTurnControlService.ProviderTurnControlServiceV2.of({
92 interrupt: input.interrupt ?? (() => Effect.void),
93 steer: () => Effect.void,
94 interruptAndAwaitTerminal: (request) =>
95 record(
96 request.replacementProviderSessionId === undefined
97 ? "interrupt"
98 : `interrupt:${request.replacementProviderSessionId}`,
99 ),
100 }),
101 ),
102 Layer.succeed(
103 ProviderSessionManager.ProviderSessionManagerV2,
104 ProviderSessionManager.ProviderSessionManagerV2.of({
105 shutdown: Effect.void,
106 open: () => Effect.die("unused open"),
107 get: () => Effect.succeed(Option.none()),
108 isLive: () => Effect.succeed(false),
109 close: () => Effect.void,
110 closeInstance: () => Effect.void,
111 release: () => record("release"),
112 detach: () => record("detach"),
113 }),
114 ),
115 Layer.succeed(
116 ProviderTurnStartService.ProviderTurnStartServiceV2,
117 ProviderTurnStartService.ProviderTurnStartServiceV2.of({
118 start: () =>
119 Effect.gen(function* () {
120 yield* record("start");
121 if (
122 input.failFirstStart !== undefined &&
123 (yield* Ref.getAndSet(input.failFirstStart, false))
124 ) {
125 return yield* new ProviderTurnStartService.ProviderTurnStartError({
126 runId,
127 cause: "simulated first start failure",
128 });
129 }
130 }),
131 }),
132 ),
133 Layer.succeed(
134 RunFinalizationService.RunFinalizationService,
135 RunFinalizationService.RunFinalizationService.of({ finalize: () => Effect.void }),
136 ),
137 Layer.succeed(
138 CheckpointRollbackService.CheckpointRollbackServiceV2,
139 CheckpointRollbackService.CheckpointRollbackServiceV2.of({
140 execute: input.rollback ?? (() => Effect.void),
141 }),
142 ),
143 Layer.succeed(
144 RuntimeRequestService.RuntimeRequestServiceV2,
145 RuntimeRequestService.RuntimeRequestServiceV2.of({ respond: () => Effect.void }),
146 ),
147 Layer.succeed(
148 ThreadTitleRegenerationService.ThreadTitleRegenerationService,
149 ThreadTitleRegenerationService.ThreadTitleRegenerationService.of({
150 execute: () => Effect.void,
151 }),
152 ),
153 );
154 return EffectWorker.layerExecutor.pipe(
155 Layer.provide(
156 Layer.mergeAll(
157 layerDependencies,
158 Layer.mock(ThreadManagementService.ThreadManagementService)(input.threads ?? {}),
159 ServerSettings.layerTest(
160 input.continueAfterRestart === true ? { continueThreadsAfterServerUpdate: true } : {},
161 ),
162 ),
163 ),
164 );
165}
166
167it.effect("settles a stopped run when its adapter has already lost the native turn", () =>
168 Effect.gen(function* () {
169 const now = yield* DateTime.now;
170 const events = yield* Ref.make<ReadonlyArray<string>>([]);
171 const layer = layerExecutorFor({
172 events,
173 interrupt: () =>
174 new ProviderTurnControlService.ProviderTurnControlError({
175 threadId,
176 operation: "interrupt",
177 providerTurnId,
178 cause: "Provider turn is not active.",
179 }),
180 threads: {
181 dispatch: (command) =>
182 Ref.update(events, (current) => [...current, command.type]).pipe(
183 Effect.as({ sequence: 1, storedEvents: [] }),
184 ),
185 },
186 });
187 yield* Effect.gen(function* () {
188 const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
189 yield* executor.execute({
190 ...restartEffect(now, { type: "detach" }),
191 request: {
192 type: "provider-turn.interrupt",
193 providerSessionId: oldSessionId,
194 providerThreadId,
195 providerTurnId,
196 },
197 });
198 }).pipe(Effect.provide(layer));
199 assert.deepEqual(yield* Ref.get(events), ["thread.background-work.settle"]);
200 }),
201);
202
203const lockedIndexMessage =
204 "Git's index is locked. Wait for other Git operations to finish, then try again.";
205const rollbackCheckpointId = CheckpointId.make("checkpoint:effect-worker-rollback");
206const rollbackScopeId = CheckpointScopeId.make("checkpoint-scope:effect-worker-rollback");
207const restoreFailure = (detail: string) =>
208 new CheckpointRollbackService.CheckpointRollbackExecutionError({
209 reason: "unexpected-failure",
210 threadId,
211 providerThreadId,
212 checkpointId: rollbackCheckpointId,
213 cause: new CheckpointService.CheckpointRestoreError({
214 scopeId: rollbackScopeId,
215 checkpointId: rollbackCheckpointId,
216 cause: new VcsProcessExitError({
217 operation: "GitVcsDriverCore.restoreCheckpoint",
218 command: "git",
219 cwd: "/private/repo",
220 exitCode: 128,
221 detail,
222 failureKind: "command-failed",
223 }),
224 }),
225 });
226
227it.effect.each([
228 {
229 name: "a held Git index lock",
230 failure: restoreFailure(lockedIndexMessage),
231 message: lockedIndexMessage,
232 },
233 {
234 name: "raw Git output",
235 failure: restoreFailure("error: could not clean /private/repo/secret.txt"),
236 message: CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE,
237 },
238])("reports a rollback blocked by $name only after the last attempt", ({ failure, message }) =>
239 Effect.gen(function* () {
240 const now = yield* DateTime.now;
241 const failures = yield* Ref.make<ReadonlyArray<string>>([]);
242 const layer = layerExecutorFor({
243 events: yield* Ref.make<ReadonlyArray<string>>([]),
244 rollback: () => Effect.fail(failure),
245 threads: {
246 dispatch: (command) =>
247 Ref.update(failures, (current) =>
248 command.type === "checkpoint.rollback.fail" ? [...current, command.message] : current,
249 ).pipe(Effect.as({ sequence: 1, storedEvents: [] })),
250 },
251 });
252 yield* Effect.gen(function* () {
253 const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
254 const rollback: EffectOutbox.OrchestrationEffectV2 = {
255 ...restartEffect(now, { type: "detach" }),
256 request: {
257 type: "provider-thread.rollback",
258 providerThreadId,
259 checkpointId: rollbackCheckpointId,
260 scopeId: rollbackScopeId,
261 restoreFiles: true,
262 },
263 };
264 yield* Effect.flip(executor.execute(rollback, { willRetry: true }));
265 assert.deepEqual(yield* Ref.get(failures), []);
266 yield* Effect.flip(executor.execute(rollback, { willRetry: false }));
267 }).pipe(Effect.provide(layer));
268 assert.deepEqual(yield* Ref.get(failures), [message]);
269 }),
270);
271
272it.effect("requeues a claim when a pre-execution worker check fails", () =>
273 Effect.gen(function* () {
274 const now = DateTime.formatIso(yield* DateTime.now);
275 const effectId = "effect:worker-pre-execution-failure";
276 const workerId = "worker-pre-execution-failure";
277 const claimedEffect: EffectOutbox.OrchestrationEffectV2 = {
278 id: effectId,
279 commandId: CommandId.make("command:worker-pre-execution-failure"),
280 threadId: ThreadId.make("thread:worker-pre-execution-failure"),
281 request: { type: "terminal.cleanup" },
282 status: "running",
283 attemptCount: 1,
284 availableAt: now,
285 leaseOwner: workerId,
286 leaseExpiresAt: now,
287 createdAt: now,
288 updatedAt: now,
289 completedAt: null,
290 lastError: null,
291 };
292 const retries = yield* Ref.make<
293 ReadonlyArray<{
294 readonly effectId: string;
295 readonly workerId: string;
296 readonly error: string;
297 readonly delayMs: number;
298 }>
299 >([]);
300 const executionCount = yield* Ref.make(0);
301 const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({
302 claimNext: () => Effect.succeed(Option.some(claimedEffect)),
303 get: () =>
304 Effect.fail(
305 new EffectOutbox.EffectOutboxError({
306 operation: "get",
307 effectId,
308 cause: "simulated cancellation-state read failure",
309 }),
310 ),
311 retry: (input) =>
312 Ref.update(retries, (existing) => [...existing, input]).pipe(Effect.as(true)),
313 });
314 const layerExecutor = Layer.succeed(
315 EffectWorker.OrchestrationEffectExecutorV2,
316 EffectWorker.OrchestrationEffectExecutorV2.of({
317 execute: () => Ref.update(executionCount, (count) => count + 1),
318 }),
319 );
320 const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe(
321 Layer.provide(Layer.merge(layerOutbox, layerExecutor)),
322 );
323
324 const exit = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe(
325 Effect.flatMap((worker) => worker.runOnce),
326 Effect.provide(layerWorker),
327 Effect.exit,
328 );
329
330 assert.isTrue(Exit.isFailure(exit));
331 if (Exit.isFailure(exit)) {
332 assert.include(Cause.pretty(exit.cause), "simulated cancellation-state read failure");
333 }
334 assert.equal(yield* Ref.get(executionCount), 0);
335 const retry = (yield* Ref.get(retries))[0];
336 assert.isDefined(retry);
337 assert.equal(retry.effectId, effectId);
338 assert.equal(retry.workerId, workerId);
339 assert.equal(retry.delayMs, 0);
340 assert.include(retry.error, "simulated cancellation-state read failure");
341 }),
342);
343
344it.effect("arms cancellation before the durable pre-execution check", () =>
345 Effect.gen(function* () {
346 const now = DateTime.formatIso(yield* DateTime.now);
347 const effectId = "effect:worker-cancellation-registration-race";
348 const workerId = "worker-cancellation-registration-race";
349 const claimedEffect: EffectOutbox.OrchestrationEffectV2 = {
350 id: effectId,
351 commandId: CommandId.make("command:worker-cancellation-registration-race"),
352 threadId: ThreadId.make("thread:worker-cancellation-registration-race"),
353 request: { type: "terminal.cleanup" },
354 status: "running",
355 attemptCount: 1,
356 availableAt: now,
357 leaseOwner: workerId,
358 leaseExpiresAt: now,
359 createdAt: now,
360 updatedAt: now,
361 completedAt: null,
362 lastError: null,
363 };
364 const signal = yield* Deferred.make<void>();
365 let cancellationArmed = false;
366 const executionCount = yield* Ref.make(0);
367 const settlementCount = yield* Ref.make(0);
368 const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({
369 claimNext: () => Effect.succeed(Option.some(claimedEffect)),
370 awaitCancellation: () => {
371 cancellationArmed = true;
372 return Deferred.await(signal);
373 },
374 get: () =>
375 Effect.gen(function* () {
376 if (cancellationArmed) {
377 yield* Deferred.succeed(signal, undefined);
378 }
379 return Option.some(claimedEffect);
380 }),
381 clearCancellation: () => Effect.void,
382 succeed: () => Ref.update(settlementCount, (count) => count + 1).pipe(Effect.as(true)),
383 });
384 const layerExecutor = Layer.succeed(
385 EffectWorker.OrchestrationEffectExecutorV2,
386 EffectWorker.OrchestrationEffectExecutorV2.of({
387 execute: () =>
388 Effect.yieldNow.pipe(Effect.andThen(Ref.update(executionCount, (count) => count + 1))),
389 }),
390 );
391 const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe(
392 Layer.provide(Layer.merge(layerOutbox, layerExecutor)),
393 );
394
395 const exit = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe(
396 Effect.flatMap((worker) => worker.runOnce),
397 Effect.provide(layerWorker),
398 Effect.exit,
399 );
400
401 if (Exit.isFailure(exit)) {
402 assert.fail(Cause.pretty(exit.cause));
403 }
404 assert.equal(yield* Ref.get(executionCount), 0);
405 assert.equal(yield* Ref.get(settlementCount), 0);
406 }),
407);
408
409it.effect("terminalizes a process-bound claim when success settlement fails", () =>
410 Effect.gen(function* () {
411 const now = DateTime.formatIso(yield* DateTime.now);
412 const effectId = "effect:worker-process-bound-settlement-failure";
413 const workerId = "worker-process-bound-settlement-failure";
414 const claimedEffect: EffectOutbox.OrchestrationEffectV2 = {
415 id: effectId,
416 commandId: CommandId.make("command:worker-process-bound-settlement-failure"),
417 threadId: ThreadId.make("thread:worker-process-bound-settlement-failure"),
418 request: {
419 type: "provider-turn.start",
420 runId: RunId.make("run:worker-process-bound-settlement-failure"),
421 },
422 status: "running",
423 attemptCount: 1,
424 availableAt: now,
425 leaseOwner: workerId,
426 leaseExpiresAt: now,
427 createdAt: now,
428 updatedAt: now,
429 completedAt: null,
430 lastError: null,
431 };
432 const retries = yield* Ref.make(0);
433 const terminalErrors = yield* Ref.make<ReadonlyArray<string>>([]);
434 const executionCount = yield* Ref.make(0);
435 const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({
436 claimNext: () => Effect.succeed(Option.some(claimedEffect)),
437 get: () => Effect.succeed(Option.some(claimedEffect)),
438 awaitCancellation: () => Effect.never,
439 clearCancellation: () => Effect.void,
440 succeed: () =>
441 Effect.fail(
442 new EffectOutbox.EffectOutboxError({
443 operation: "succeed",
444 effectId,
445 cause: "simulated success settlement failure",
446 }),
447 ),
448 retry: () => Ref.update(retries, (count) => count + 1).pipe(Effect.as(true)),
449 fail: ({ error }) =>
450 Ref.update(terminalErrors, (existing) => [...existing, error]).pipe(Effect.as(true)),
451 });
452 const layerExecutor = Layer.succeed(
453 EffectWorker.OrchestrationEffectExecutorV2,
454 EffectWorker.OrchestrationEffectExecutorV2.of({
455 execute: () => Ref.update(executionCount, (count) => count + 1),
456 }),
457 );
458 const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe(
459 Layer.provide(Layer.merge(layerOutbox, layerExecutor)),
460 );
461
462 const exit = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe(
463 Effect.flatMap((worker) => worker.runOnce),
464 Effect.provide(layerWorker),
465 Effect.exit,
466 );
467
468 assert.isTrue(Exit.isFailure(exit));
469 assert.equal(yield* Ref.get(executionCount), 1);
470 assert.equal(yield* Ref.get(retries), 0);
471 const terminalError = (yield* Ref.get(terminalErrors))[0];
472 assert.isDefined(terminalError);
473 assert.include(terminalError, "after execution started");
474 assert.include(terminalError, "simulated success settlement failure");
475 }),
476);
477
478it.effect("settles a delegated child once its restart continuation fails for good", () =>
479 Effect.gen(function* () {
480 const timestamp = DateTime.formatIso(yield* DateTime.now);
481 const events = yield* Ref.make<ReadonlyArray<string>>([]);
482 const recovered = yield* Ref.make<ReadonlyArray<ThreadId>>([]);
483 const layer = layerExecutorFor({
484 events,
485 continueAfterRestart: true,
486 threads: {
487 getThreadRecords: () => Effect.fail(new Error("provider instance removed") as never),
488 recoverDelegatedTask: (childThreadId) =>
489 Ref.update(recovered, (ids) => [...ids, childThreadId]),
490 },
491 });
492 const effect: EffectOutbox.OrchestrationEffectV2 = {
493 id: `effect:restart-continuation:${runId}`,
494 commandId: CommandId.make("command:restart-continuation-failure"),
495 threadId,
496 request: { type: "provider-runtime.continue", sourceRunId: runId },
497 status: "running",
498 attemptCount: 1,
499 availableAt: timestamp,
500 leaseOwner: "test-worker",
501 leaseExpiresAt: timestamp,
502 createdAt: timestamp,
503 updatedAt: timestamp,
504 completedAt: null,
505 lastError: null,
506 };
507 yield* Effect.gen(function* () {
508 const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
509 assert.isTrue(
510 Exit.isFailure(yield* Effect.exit(executor.execute(effect, { willRetry: true }))),
511 );
512 assert.deepEqual(yield* Ref.get(recovered), []);
513 assert.isTrue(
514 Exit.isFailure(yield* Effect.exit(executor.execute(effect, { willRetry: false }))),
515 );
516 assert.deepEqual(yield* Ref.get(recovered), [threadId]);
517 }).pipe(Effect.provide(layer));
518 }),
519);
520
521it.effect.each(["confirmed", "unconfirmed", "failed"] as const)(
522 "a native subagent stop only repairs %s provider evidence",
523 (outcome) =>
524 Effect.gen(function* () {
525 const now = yield* DateTime.now;
526 const events = yield* Ref.make<ReadonlyArray<string>>([]);
527 const layer = layerExecutorFor({
528 events,
529 interrupt: (input) => {
530 assert.equal(input.subagent?.nativeTaskId, "native-task");
531 return Ref.update(events, (current) => [...current, "stop-child"]).pipe(
532 Effect.andThen(
533 outcome === "failed"
534 ? new ProviderTurnControlService.ProviderTurnControlError({
535 threadId,
536 providerTurnId,
537 operation: "interrupt",
538 cause: "SDK stop failed",
539 })
540 : Effect.succeed(
541 outcome === "confirmed"
542 ? {
543 status: "cancelled" as const,
544 completedAt: now,
545 result: "Stopped by Claude",
546 }
547 : undefined,
548 ),
549 ),
550 );
551 },
552 threads: {
553 dispatch: (command) => {
554 assert.equal(command.type, "thread.background-work.settle");
555 if (command.type === "thread.background-work.settle") {
556 assert.equal(command.subagent?.id, "subagent");
557 assert.deepEqual(command.subagent?.outcome, {
558 status: "cancelled",
559 completedAt: now,
560 result: "Stopped by Claude",
561 });
562 }
563 return Ref.update(events, (current) => [...current, "settle-child"]).pipe(
564 Effect.as({ sequence: 1, storedEvents: [] }),
565 );
566 },
567 },
568 });
569 const execution = yield* Effect.gen(function* () {
570 const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
571 yield* executor.execute({
572 ...restartEffect(now, { type: "detach" }),
573 request: {
574 type: "provider-turn.interrupt",
575 providerSessionId: oldSessionId,
576 providerThreadId,
577 providerTurnId,
578 subagent: { id: NodeId.make("subagent"), nativeTaskId: "native-task" },
579 },
580 });
581 }).pipe(Effect.provide(layer), Effect.exit);
582 assert.equal(Exit.isFailure(execution), outcome === "failed");
583 assert.deepEqual(
584 yield* Ref.get(events),
585 outcome === "confirmed" ? ["stop-child", "settle-child"] : ["stop-child"],
586 );
587 }),
588);