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

EffectWorker.test.ts

844 lines31.3 KB

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