Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CheckpointId,
4 CheckpointScopeId,
5 CommandId,
6 NodeId,
7 ProjectId,
8 ProviderInstanceId,
9 ProviderSessionId,
10 ProviderThreadId,
11 ProviderTurnId,
12 RunAttemptId,
13 RunId,
14 RuntimeRequestId,
15 ThreadId,
16 VcsProcessExitError,
17 type OrchestrationV2ThreadProjection,
18} from "@t3tools/contracts";
19import * as Cause from "effect/Cause";
20import * as DateTime from "effect/DateTime";
21import * as Deferred from "effect/Deferred";
22import * as Duration from "effect/Duration";
23import * as Effect from "effect/Effect";
24import * as Exit from "effect/Exit";
25import * as Fiber from "effect/Fiber";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Ref from "effect/Ref";
29import * as SqlError from "effect/sql/SqlError";
30import * as Stream from "effect/Stream";
31import * as TestClock from "effect/testing/TestClock";
32
33import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
34import * as CheckpointService from "./CheckpointService.ts";
35import * as EffectOutbox from "./EffectOutbox.ts";
36import * as EffectWorker from "./EffectWorker.ts";
37import * as ProjectionStore from "./ProjectionStore.ts";
38import * as RunFinalizationService from "./RunFinalizationService.ts";
39import * as ProviderSessionManager from "./ProviderSessionManager.ts";
40import * as ProviderTurnControlService from "./ProviderTurnControlService.ts";
41import * as ProviderTurnStartService from "./ProviderTurnStartService.ts";
42import * as RuntimeRequestService from "./RuntimeRequestService.ts";
43import * as ThreadTitleRegenerationService from "./ThreadTitleRegenerationService.ts";
44import * as ThreadManagementService from "./ThreadManagementService.ts";
45import * as ServerSettings from "../serverSettings.ts";
46
47const threadId = ThreadId.make("thread:effect-worker-restart");
48const oldSessionId = ProviderSessionId.make("provider-session:effect-worker-restart:old");
49const providerThreadId = ProviderThreadId.make("provider-thread:effect-worker-restart");
50const providerTurnId = ProviderTurnId.make("provider-turn:effect-worker-restart");
51const attemptId = RunAttemptId.make("run-attempt:effect-worker-restart");
52const runId = RunId.make("run:effect-worker-restart");
53
54function restartEffect(
55 now: DateTime.Utc,
56 sessionTransition: NonNullable<
57 Extract<
58 EffectOutbox.OrchestrationEffectV2["request"],
59 { readonly type: "provider-turn.restart" }
60 >["sessionTransition"]
61 >,
62): EffectOutbox.OrchestrationEffectV2 {
63 const timestamp = DateTime.formatIso(now);
64 return {
65 id: `effect:restart:${sessionTransition.type}`,
66 commandId: CommandId.make(`command:restart:${sessionTransition.type}`),
67 threadId,
68 request: {
69 type: "provider-turn.restart",
70 providerSessionId: oldSessionId,
71 providerThreadId,
72 providerTurnId,
73 interruptedAttemptId: attemptId,
74 runId,
75 sessionTransition,
76 },
77 status: "running",
78 attemptCount: 1,
79 availableAt: timestamp,
80 leaseOwner: "test-worker",
81 createdAt: timestamp,
82 updatedAt: timestamp,
83 completedAt: null,
84 lastError: null,
85 };
86}
87
88function layerExecutorFor(input: {
89 readonly events: Ref.Ref<ReadonlyArray<string>>;
90 readonly failFirstStart?: Ref.Ref<boolean>;
91 readonly threads?: Partial<ThreadManagementService.ThreadManagementService["Service"]>;
92 readonly continueAfterRestart?: boolean;
93 readonly interrupt?: ProviderTurnControlService.ProviderTurnControlServiceV2Shape["interrupt"];
94 readonly rollback?: CheckpointRollbackService.CheckpointRollbackServiceV2Shape["execute"];
95 readonly respond?: RuntimeRequestService.RuntimeRequestServiceV2["Service"]["respond"];
96}) {
97 const record = (event: string) => Ref.update(input.events, (events) => [...events, event]);
98 const layerDependencies = Layer.mergeAll(
99 Layer.succeed(
100 ProviderTurnControlService.ProviderTurnControlServiceV2,
101 ProviderTurnControlService.ProviderTurnControlServiceV2.of({
102 interrupt: input.interrupt ?? (() => Effect.void),
103 steer: () => Effect.void,
104 applyModelSelection: () => Effect.void,
105 applyThreadTitle: () => Effect.void,
106 interruptAndAwaitTerminal: (request) =>
107 record(
108 request.replacementProviderSessionId === undefined
109 ? "interrupt"
110 : `interrupt:${request.replacementProviderSessionId}`,
111 ),
112 }),
113 ),
114 Layer.succeed(
115 ProviderSessionManager.ProviderSessionManagerV2,
116 ProviderSessionManager.ProviderSessionManagerV2.of({
117 shutdown: Effect.void,
118 open: () => Effect.die("unused open"),
119 get: () => Effect.succeedNone,
120 isLive: () => Effect.succeed(false),
121 close: () => Effect.void,
122 closeInstance: () => Effect.void,
123 release: () => record("release"),
124 detach: () => record("detach"),
125 otherWorkingThreads: () => Effect.succeed([]),
126 releaseUnlessBusy: () => Effect.succeed(true),
127 subscribePromptSuggestion: () => Stream.empty,
128 }),
129 ),
130 Layer.succeed(
131 ProviderTurnStartService.ProviderTurnStartServiceV2,
132 ProviderTurnStartService.ProviderTurnStartServiceV2.of({
133 failStartingRun: () => Effect.void,
134 start: () =>
135 Effect.gen(function* () {
136 yield* record("start");
137 if (
138 input.failFirstStart !== undefined &&
139 (yield* Ref.getAndSet(input.failFirstStart, false))
140 ) {
141 return yield* new ProviderTurnStartService.ProviderTurnStartError({
142 runId,
143 cause: "simulated first start failure",
144 });
145 }
146 }),
147 }),
148 ),
149 Layer.succeed(
150 RunFinalizationService.RunFinalizationService,
151 RunFinalizationService.RunFinalizationService.of({ finalize: () => Effect.void }),
152 ),
153 Layer.succeed(
154 CheckpointRollbackService.CheckpointRollbackServiceV2,
155 CheckpointRollbackService.CheckpointRollbackServiceV2.of({
156 execute: input.rollback ?? (() => Effect.void),
157 }),
158 ),
159 Layer.succeed(
160 RuntimeRequestService.RuntimeRequestServiceV2,
161 RuntimeRequestService.RuntimeRequestServiceV2.of({
162 respond: input.respond ?? (() => Effect.void),
163 }),
164 ),
165 Layer.succeed(
166 ThreadTitleRegenerationService.ThreadTitleRegenerationService,
167 ThreadTitleRegenerationService.ThreadTitleRegenerationService.of({
168 execute: () => Effect.void,
169 }),
170 ),
171 );
172 return EffectWorker.layerExecutor.pipe(
173 Layer.provide(
174 Layer.mergeAll(
175 layerDependencies,
176 Layer.mock(ThreadManagementService.ThreadManagementService)(input.threads ?? {}),
177 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
178 ServerSettings.layerTest(
179 input.continueAfterRestart === true ? { continueThreadsAfterServerUpdate: true } : {},
180 ),
181 ),
182 ),
183 );
184}
185
186it.effect.each([
187 {
188 name: "settles a stopped run when its adapter has already lost the native turn",
189 unresponsive: false,
190 dispatched: ["thread.background-work.settle"],
191 },
192 {
193 name: "leaves the run running and flags the Stop when the provider never confirms it",
194 unresponsive: true,
195 dispatched: ["thread.interrupt.unresponsive"],
196 },
197])("$name", ({ unresponsive, dispatched }) =>
198 Effect.gen(function* () {
199 const now = yield* DateTime.now;
200 const events = yield* Ref.make<ReadonlyArray<string>>([]);
201 const layer = layerExecutorFor({
202 events,
203 interrupt: () =>
204 new ProviderTurnControlService.ProviderTurnControlError({
205 threadId,
206 operation: "interrupt",
207 providerTurnId,
208 ...(unresponsive ? { unresponsive } : {}),
209 cause: unresponsive ? "Timed out." : "Provider turn is not active.",
210 }),
211 threads: {
212 dispatch: (command) =>
213 Ref.update(events, (current) => [...current, command.type]).pipe(
214 Effect.as({ sequence: 1, storedEvents: [] }),
215 ),
216 },
217 });
218 yield* Effect.gen(function* () {
219 const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
220 yield* executor.execute({
221 ...restartEffect(now, { type: "detach" }),
222 request: {
223 type: "provider-turn.interrupt",
224 providerSessionId: oldSessionId,
225 providerThreadId,
226 providerTurnId,
227 },
228 });
229 }).pipe(Effect.provide(layer));
230 assert.deepEqual(yield* Ref.get(events), dispatched);
231 }),
232);
233
234const lockedIndexMessage =
235 "Git's index is locked. Wait for other Git operations to finish, then try again.";
236const rollbackCheckpointId = CheckpointId.make("checkpoint:effect-worker-rollback");
237const rollbackScopeId = CheckpointScopeId.make("checkpoint-scope:effect-worker-rollback");
238const restoreFailure = (detail: string) =>
239 new CheckpointRollbackService.CheckpointRollbackExecutionError({
240 reason: "unexpected-failure",
241 threadId,
242 providerThreadId,
243 checkpointId: rollbackCheckpointId,
244 cause: new CheckpointService.CheckpointRestoreError({
245 scopeId: rollbackScopeId,
246 checkpointId: rollbackCheckpointId,
247 cause: new VcsProcessExitError({
248 operation: "GitVcsDriverCore.restoreCheckpoint",
249 command: "git",
250 cwd: "/private/repo",
251 exitCode: 128,
252 detail,
253 failureKind: "command-failed",
254 }),
255 }),
256 });
257
258it.effect.each([
259 {
260 name: "a held Git index lock",
261 failure: restoreFailure(lockedIndexMessage),
262 message: lockedIndexMessage,
263 },
264 {
265 name: "raw Git output",
266 failure: restoreFailure("error: could not clean /private/repo/secret.txt"),
267 message: CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE,
268 },
269])("reports a rollback blocked by $name only after the last attempt", ({ failure, message }) =>
270 Effect.gen(function* () {
271 const now = yield* DateTime.now;
272 const failures = yield* Ref.make<ReadonlyArray<string>>([]);
273 const layer = layerExecutorFor({
274 events: yield* Ref.make<ReadonlyArray<string>>([]),
275 rollback: () => Effect.fail(failure),
276 threads: {
277 dispatch: (command) =>
278 Ref.update(failures, (current) =>
279 command.type === "checkpoint.rollback.fail" ? [...current, command.message] : current,
280 ).pipe(Effect.as({ sequence: 1, storedEvents: [] })),
281 },
282 });
283 yield* Effect.gen(function* () {
284 const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
285 const rollback: EffectOutbox.OrchestrationEffectV2 = {
286 ...restartEffect(now, { type: "detach" }),
287 request: {
288 type: "provider-thread.rollback",
289 providerThreadId,
290 checkpointId: rollbackCheckpointId,
291 scopeId: rollbackScopeId,
292 restoreFiles: true,
293 },
294 };
295 yield* Effect.flip(executor.execute(rollback, { willRetry: true }));
296 assert.deepEqual(yield* Ref.get(failures), []);
297 yield* Effect.flip(executor.execute(rollback, { willRetry: false }));
298 }).pipe(Effect.provide(layer));
299 assert.deepEqual(yield* Ref.get(failures), [message]);
300 }),
301);
302
303it.effect("does not report an answer whose last delivery attempt is interrupted", () =>
304 Effect.gen(function* () {
305 const now = yield* DateTime.now;
306 const reported = yield* Ref.make(0);
307 const layer = layerExecutorFor({
308 events: yield* Ref.make<ReadonlyArray<string>>([]),
309 respond: () => Effect.interrupt,
310 threads: {
311 dispatch: (command) =>
312 Ref.update(reported, (count) =>
313 command.type === "runtime-request.delivery.fail" ? count + 1 : count,
314 ).pipe(Effect.as({ sequence: 1, storedEvents: [] })),
315 },
316 });
317 const exit = yield* Effect.gen(function* () {
318 const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
319 return yield* Effect.exit(
320 executor.execute(
321 {
322 ...restartEffect(now, { type: "detach" }),
323 request: {
324 type: "runtime-request.respond",
325 providerSessionId: oldSessionId,
326 requestId: RuntimeRequestId.make("runtime-request:effect-worker-interrupted"),
327 answers: { next: "Ship it" },
328 },
329 },
330 { willRetry: false },
331 ),
332 );
333 }).pipe(Effect.provide(layer));
334 assert.isTrue(Exit.hasInterrupts(exit));
335 assert.equal(yield* Ref.get(reported), 0);
336 }),
337);
338
339it.effect("requeues a claim when a pre-execution worker check fails", () =>
340 Effect.gen(function* () {
341 const now = DateTime.formatIso(yield* DateTime.now);
342 const effectId = "effect:worker-pre-execution-failure";
343 const workerId = "worker-pre-execution-failure";
344 const claimedEffect: EffectOutbox.OrchestrationEffectV2 = {
345 id: effectId,
346 commandId: CommandId.make("command:worker-pre-execution-failure"),
347 threadId: ThreadId.make("thread:worker-pre-execution-failure"),
348 request: { type: "terminal.cleanup" },
349 status: "running",
350 attemptCount: 1,
351 availableAt: now,
352 leaseOwner: workerId,
353 createdAt: now,
354 updatedAt: now,
355 completedAt: null,
356 lastError: null,
357 };
358 const retries = yield* Ref.make<
359 ReadonlyArray<{
360 readonly effectId: string;
361 readonly workerId: string;
362 readonly error: string;
363 readonly delayMs: number;
364 }>
365 >([]);
366 const executionCount = yield* Ref.make(0);
367 const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({
368 claimNext: () => Effect.succeedSome(claimedEffect),
369 get: () =>
370 Effect.fail(
371 new EffectOutbox.EffectOutboxError({
372 operation: "get",
373 effectId,
374 cause: "simulated cancellation-state read failure",
375 }),
376 ),
377 retry: (input) =>
378 Ref.update(retries, (existing) => [...existing, input]).pipe(Effect.as(true)),
379 });
380 const layerExecutor = Layer.succeed(
381 EffectWorker.OrchestrationEffectExecutorV2,
382 EffectWorker.OrchestrationEffectExecutorV2.of({
383 execute: () => Ref.update(executionCount, (count) => count + 1),
384 }),
385 );
386 const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe(
387 Layer.provide(Layer.merge(layerOutbox, layerExecutor)),
388 );
389
390 const exit = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe(
391 Effect.flatMap((worker) => worker.runOnce()),
392 Effect.provide(layerWorker),
393 Effect.exit,
394 );
395
396 assert.isTrue(Exit.isFailure(exit));
397 if (Exit.isFailure(exit)) {
398 assert.include(Cause.pretty(exit.cause), "simulated cancellation-state read failure");
399 }
400 assert.equal(yield* Ref.get(executionCount), 0);
401 const retry = (yield* Ref.get(retries))[0];
402 assert.isDefined(retry);
403 assert.equal(retry.effectId, effectId);
404 assert.equal(retry.workerId, workerId);
405 assert.equal(retry.delayMs, 0);
406 assert.include(retry.error, "simulated cancellation-state read failure");
407 }),
408);
409
410it.effect("keeps requeueing a failed claim while the database is locked", () =>
411 Effect.gen(function* () {
412 const now = DateTime.formatIso(yield* DateTime.now);
413 const effectId = "effect:worker-requeue-lock-timeout";
414 const workerId = "worker-requeue-lock-timeout";
415 const claimedEffect: EffectOutbox.OrchestrationEffectV2 = {
416 id: effectId,
417 commandId: CommandId.make("command:worker-requeue-lock-timeout"),
418 threadId,
419 request: { type: "provider-runtime.continue", sourceRunId: runId },
420 status: "running",
421 attemptCount: 1,
422 availableAt: now,
423 leaseOwner: workerId,
424 createdAt: now,
425 updatedAt: now,
426 completedAt: null,
427 lastError: null,
428 };
429 const lockedWrites = yield* Ref.make(3);
430 const requeued = yield* Ref.make(false);
431 const firstLockTimeout = yield* Deferred.make<void>();
432 const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({
433 claimNext: () => Effect.succeedSome(claimedEffect),
434 get: () => Effect.succeedSome(claimedEffect),
435 awaitCancellation: () => Effect.never,
436 clearCancellation: () => Effect.void,
437 retry: () =>
438 Effect.gen(function* () {
439 if ((yield* Ref.getAndUpdate(lockedWrites, (count) => count - 1)) > 0) {
440 yield* Deferred.succeed(firstLockTimeout, undefined);
441 return yield* new EffectOutbox.EffectOutboxError({
442 operation: "retry",
443 effectId,
444 cause: new SqlError.SqlError({
445 reason: new SqlError.LockTimeoutError({ cause: null }),
446 }),
447 });
448 }
449 yield* Ref.set(requeued, true);
450 return true;
451 }),
452 });
453 const layerExecutor = Layer.succeed(
454 EffectWorker.OrchestrationEffectExecutorV2,
455 EffectWorker.OrchestrationEffectExecutorV2.of({
456 execute: () =>
457 Effect.fail(
458 new EffectWorker.OrchestrationEffectExecutionError({
459 effectId,
460 effectType: "provider-runtime.continue",
461 cause: "simulated database is locked",
462 }),
463 ),
464 }),
465 );
466 const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe(
467 Layer.provide(Layer.merge(layerOutbox, layerExecutor)),
468 );
469
470 const workerFiber = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe(
471 Effect.flatMap((worker) => worker.runOnce()),
472 Effect.provide(layerWorker),
473 Effect.forkChild,
474 );
475 yield* Deferred.await(firstLockTimeout);
476 yield* TestClock.adjust(Duration.millis(99));
477 assert.isFalse(yield* Ref.get(requeued));
478 yield* TestClock.adjust(Duration.seconds(1));
479 yield* Effect.exit(Fiber.join(workerFiber));
480
481 assert.isTrue(yield* Ref.get(requeued));
482 }),
483);
484
485it.effect.each([
486 { name: "requeue", request: { type: "provider-runtime.continue", sourceRunId: runId } },
487 { name: "terminalize", request: { type: "provider-turn.start", runId } },
488] as const)("interrupts $name settlement retries when the worker shuts down", ({ request }) =>
489 Effect.gen(function* () {
490 const claimedEffect: EffectOutbox.OrchestrationEffectV2 = {
491 ...restartEffect(yield* DateTime.now, { type: "detach" }),
492 request,
493 };
494 const settlementStarted = yield* Deferred.make<void>();
495 const releaseLock = yield* Ref.make(false);
496 const lockedWrite = Effect.gen(function* () {
497 yield* Deferred.succeed(settlementStarted, undefined);
498 // An in-flight database write can finish its own wait before noticing shutdown.
499 yield* Effect.sleep(Duration.millis(1));
500 if (yield* Ref.get(releaseLock)) return true;
501 return yield* new EffectOutbox.EffectOutboxError({
502 operation: "settlement",
503 effectId: claimedEffect.id,
504 cause: new SqlError.SqlError({ reason: new SqlError.LockTimeoutError({ cause: null }) }),
505 });
506 });
507 const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({
508 claimNext: () => Effect.succeedSome(claimedEffect),
509 get: () => Effect.succeedSome(claimedEffect),
510 awaitCancellation: () => Effect.never,
511 clearCancellation: () => Effect.void,
512 succeed: () => Effect.fail(new EffectOutbox.EffectOutboxError({ operation: "succeed" })),
513 retry: () => lockedWrite,
514 fail: () => lockedWrite,
515 });
516 const layerExecutor = Layer.succeed(
517 EffectWorker.OrchestrationEffectExecutorV2,
518 EffectWorker.OrchestrationEffectExecutorV2.of({ execute: () => Effect.void }),
519 );
520 const layerWorker = EffectWorker.layerWithOptions({ workerId: "test-worker" }).pipe(
521 Layer.provide(Layer.merge(layerOutbox, layerExecutor)),
522 );
523
524 const daemon = yield* EffectWorker.runDaemonWithOptions({ concurrency: 1 }).pipe(
525 Effect.provide(layerWorker),
526 Effect.forkChild,
527 );
528 yield* Deferred.await(settlementStarted);
529 const shutdown = yield* Fiber.interrupt(daemon).pipe(
530 Effect.timeoutOption(Duration.millis(100)),
531 Effect.forkChild,
532 );
533 yield* TestClock.adjust(Duration.millis(100));
534 const stopped = yield* Fiber.join(shutdown);
535 yield* Ref.set(releaseLock, true);
536 yield* TestClock.adjust(Duration.seconds(1));
537 yield* Fiber.await(daemon);
538 assert.isTrue(Option.isSome(stopped));
539 }),
540);
541
542it.effect("arms cancellation before the durable pre-execution check", () =>
543 Effect.gen(function* () {
544 const now = DateTime.formatIso(yield* DateTime.now);
545 const effectId = "effect:worker-cancellation-registration-race";
546 const workerId = "worker-cancellation-registration-race";
547 const claimedEffect: EffectOutbox.OrchestrationEffectV2 = {
548 id: effectId,
549 commandId: CommandId.make("command:worker-cancellation-registration-race"),
550 threadId: ThreadId.make("thread:worker-cancellation-registration-race"),
551 request: { type: "terminal.cleanup" },
552 status: "running",
553 attemptCount: 1,
554 availableAt: now,
555 leaseOwner: workerId,
556 createdAt: now,
557 updatedAt: now,
558 completedAt: null,
559 lastError: null,
560 };
561 const signal = yield* Deferred.make<void>();
562 let cancellationArmed = false;
563 const executionCount = yield* Ref.make(0);
564 const settlementCount = yield* Ref.make(0);
565 const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({
566 claimNext: () => Effect.succeedSome(claimedEffect),
567 awaitCancellation: () => {
568 cancellationArmed = true;
569 return Deferred.await(signal);
570 },
571 get: () =>
572 Effect.gen(function* () {
573 if (cancellationArmed) {
574 yield* Deferred.succeed(signal, undefined);
575 }
576 return Option.some(claimedEffect);
577 }),
578 clearCancellation: () => Effect.void,
579 succeed: () => Ref.update(settlementCount, (count) => count + 1).pipe(Effect.as(true)),
580 });
581 const layerExecutor = Layer.succeed(
582 EffectWorker.OrchestrationEffectExecutorV2,
583 EffectWorker.OrchestrationEffectExecutorV2.of({
584 execute: () =>
585 Effect.yieldNow.pipe(Effect.andThen(Ref.update(executionCount, (count) => count + 1))),
586 }),
587 );
588 const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe(
589 Layer.provide(Layer.merge(layerOutbox, layerExecutor)),
590 );
591
592 const exit = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe(
593 Effect.flatMap((worker) => worker.runOnce()),
594 Effect.provide(layerWorker),
595 Effect.exit,
596 );
597
598 if (Exit.isFailure(exit)) {
599 assert.fail(Cause.pretty(exit.cause));
600 }
601 assert.equal(yield* Ref.get(executionCount), 0);
602 assert.equal(yield* Ref.get(settlementCount), 0);
603 }),
604);
605
606it.effect("terminalizes a process-bound claim when success settlement fails", () =>
607 Effect.gen(function* () {
608 const now = DateTime.formatIso(yield* DateTime.now);
609 const effectId = "effect:worker-process-bound-settlement-failure";
610 const workerId = "worker-process-bound-settlement-failure";
611 const claimedEffect: EffectOutbox.OrchestrationEffectV2 = {
612 id: effectId,
613 commandId: CommandId.make("command:worker-process-bound-settlement-failure"),
614 threadId: ThreadId.make("thread:worker-process-bound-settlement-failure"),
615 request: {
616 type: "provider-turn.start",
617 runId: RunId.make("run:worker-process-bound-settlement-failure"),
618 },
619 status: "running",
620 attemptCount: 1,
621 availableAt: now,
622 leaseOwner: workerId,
623 createdAt: now,
624 updatedAt: now,
625 completedAt: null,
626 lastError: null,
627 };
628 const retries = yield* Ref.make(0);
629 const terminalErrors = yield* Ref.make<ReadonlyArray<string>>([]);
630 const executionCount = yield* Ref.make(0);
631 const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({
632 claimNext: () => Effect.succeedSome(claimedEffect),
633 get: () => Effect.succeedSome(claimedEffect),
634 awaitCancellation: () => Effect.never,
635 clearCancellation: () => Effect.void,
636 succeed: () =>
637 Effect.fail(
638 new EffectOutbox.EffectOutboxError({
639 operation: "succeed",
640 effectId,
641 cause: "simulated success settlement failure",
642 }),
643 ),
644 retry: () => Ref.update(retries, (count) => count + 1).pipe(Effect.as(true)),
645 fail: ({ error }) =>
646 Ref.update(terminalErrors, (existing) => [...existing, error]).pipe(Effect.as(true)),
647 });
648 const layerExecutor = Layer.succeed(
649 EffectWorker.OrchestrationEffectExecutorV2,
650 EffectWorker.OrchestrationEffectExecutorV2.of({
651 execute: () => Ref.update(executionCount, (count) => count + 1),
652 }),
653 );
654 const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe(
655 Layer.provide(Layer.merge(layerOutbox, layerExecutor)),
656 );
657
658 const exit = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe(
659 Effect.flatMap((worker) => worker.runOnce()),
660 Effect.provide(layerWorker),
661 Effect.exit,
662 );
663
664 assert.isTrue(Exit.isFailure(exit));
665 assert.equal(yield* Ref.get(executionCount), 1);
666 assert.equal(yield* Ref.get(retries), 0);
667 const terminalError = (yield* Ref.get(terminalErrors))[0];
668 assert.isDefined(terminalError);
669 assert.include(terminalError, "after execution started");
670 assert.include(terminalError, "simulated success settlement failure");
671 }),
672);
673
674it.effect("settles a delegated child once its restart continuation fails for good", () =>
675 Effect.gen(function* () {
676 const timestamp = DateTime.formatIso(yield* DateTime.now);
677 const events = yield* Ref.make<ReadonlyArray<string>>([]);
678 const recovered = yield* Ref.make<ReadonlyArray<ThreadId>>([]);
679 const layer = layerExecutorFor({
680 events,
681 continueAfterRestart: true,
682 threads: {
683 getThreadRecords: () => Effect.fail(new Error("provider instance removed") as never),
684 recoverDelegatedTask: (childThreadId) =>
685 Ref.update(recovered, (ids) => [...ids, childThreadId]),
686 },
687 });
688 const effect: EffectOutbox.OrchestrationEffectV2 = {
689 id: `effect:restart-continuation:${runId}`,
690 commandId: CommandId.make("command:restart-continuation-failure"),
691 threadId,
692 request: { type: "provider-runtime.continue", sourceRunId: runId },
693 status: "running",
694 attemptCount: 1,
695 availableAt: timestamp,
696 leaseOwner: "test-worker",
697 createdAt: timestamp,
698 updatedAt: timestamp,
699 completedAt: null,
700 lastError: null,
701 };
702 yield* Effect.gen(function* () {
703 const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
704 assert.isTrue(
705 Exit.isFailure(yield* Effect.exit(executor.execute(effect, { willRetry: true }))),
706 );
707 assert.deepEqual(yield* Ref.get(recovered), []);
708 assert.isTrue(
709 Exit.isFailure(yield* Effect.exit(executor.execute(effect, { willRetry: false }))),
710 );
711 assert.deepEqual(yield* Ref.get(recovered), [threadId]);
712 }).pipe(Effect.provide(layer));
713 }),
714);
715
716it.effect.each(["confirmed", "unconfirmed", "failed"] as const)(
717 "a native subagent stop only repairs %s provider evidence",
718 (outcome) =>
719 Effect.gen(function* () {
720 const now = yield* DateTime.now;
721 const events = yield* Ref.make<ReadonlyArray<string>>([]);
722 const layer = layerExecutorFor({
723 events,
724 interrupt: (input) => {
725 assert.equal(input.subagent?.nativeTaskId, "native-task");
726 return Ref.update(events, (current) => [...current, "stop-child"]).pipe(
727 Effect.andThen(
728 outcome === "failed"
729 ? new ProviderTurnControlService.ProviderTurnControlError({
730 threadId,
731 providerTurnId,
732 operation: "interrupt",
733 cause: "SDK stop failed",
734 })
735 : Effect.succeed(
736 outcome === "confirmed"
737 ? {
738 status: "cancelled" as const,
739 completedAt: now,
740 result: "Stopped by Claude",
741 }
742 : undefined,
743 ),
744 ),
745 );
746 },
747 threads: {
748 dispatch: (command) => {
749 assert.equal(command.type, "thread.background-work.settle");
750 if (command.type === "thread.background-work.settle") {
751 assert.equal(command.subagent?.id, "subagent");
752 assert.deepEqual(command.subagent?.outcome, {
753 status: "cancelled",
754 completedAt: now,
755 result: "Stopped by Claude",
756 });
757 }
758 return Ref.update(events, (current) => [...current, "settle-child"]).pipe(
759 Effect.as({ sequence: 1, storedEvents: [] }),
760 );
761 },
762 },
763 });
764 const execution = yield* Effect.gen(function* () {
765 const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
766 yield* executor.execute({
767 ...restartEffect(now, { type: "detach" }),
768 request: {
769 type: "provider-turn.interrupt",
770 providerSessionId: oldSessionId,
771 providerThreadId,
772 providerTurnId,
773 subagent: { id: NodeId.make("subagent"), nativeTaskId: "native-task" },
774 },
775 });
776 }).pipe(Effect.provide(layer), Effect.exit);
777 assert.equal(Exit.isFailure(execution), outcome === "failed");
778 assert.deepEqual(
779 yield* Ref.get(events),
780 outcome === "confirmed" ? ["stop-child", "settle-child"] : ["stop-child"],
781 );
782 }),
783);
784
785it.effect.each([3, 4])(
786 "enforces process-loss count %s after 22 minutes through the executor",
787 (processLossCount) =>
788 Effect.gen(function* () {
789 const now = yield* DateTime.now;
790 const instanceId = ProviderInstanceId.make("codex");
791 const events = yield* Ref.make<ReadonlyArray<string>>([]);
792 const layer = layerExecutorFor({
793 events,
794 continueAfterRestart: true,
795 threads: {
796 getThreadRecords: () =>
797 Effect.succeed({
798 thread: {
799 id: threadId,
800 projectId: ProjectId.make("project:executor-recovery"),
801 providerInstanceId: instanceId,
802 archivedAt: null,
803 deletedAt: null,
804 lineage: { parentThreadId: null, relationshipToParent: null },
805 },
806 runs: [
807 {
808 id: runId,
809 providerInstanceId: instanceId,
810 status: "cancelled",
811 requestedAt: DateTime.subtract(now, { minutes: 22 }),
812 completedAt: now,
813 ordinal: 1,
814 },
815 ],
816 messages: [],
817 providerTurns: [],
818 runtimeRequests: [],
819 turnItems: [],
820 attempts: [],
821 } as unknown as OrchestrationV2ThreadProjection),
822 dispatch: () =>
823 Ref.update(events, (entries) => [...entries, "dispatch"]).pipe(Effect.as({} as never)),
824 recoverDelegatedTask: () =>
825 Ref.update(events, (entries) => [...entries, "recover-child"]),
826 },
827 });
828 yield* Effect.gen(function* () {
829 const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
830 yield* executor.execute({
831 ...restartEffect(now, { type: "detach" }),
832 request: { type: "provider-runtime.continue", sourceRunId: runId, processLossCount },
833 });
834 }).pipe(Effect.provide(layer));
835 assert.deepEqual(
836 yield* Ref.get(events),
837 processLossCount > 3 ? ["recover-child"] : ["dispatch", "recover-child"],
838 );
839 }),
840);