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