Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CheckpointId,
4 CheckpointRef,
5 CheckpointScopeId,
6 CommandId,
7 ContextTransferId,
8 EventId,
9 MessageId,
10 type ModelSelection,
11 NodeId,
12 type OrchestrationV2AppThread,
13 type OrchestrationV2DomainEvent,
14 type OrchestrationV2Run,
15 ProjectId,
16 ProviderDriverKind,
17 ProviderInstanceId,
18 ProviderSessionId,
19 ProviderThreadId,
20 RunAttemptId,
21 RunId,
22 ThreadId,
23 TurnItemId,
24} from "@t3tools/contracts";
25import * as DateTime from "effect/DateTime";
26import * as Deferred from "effect/Deferred";
27import * as Effect from "effect/Effect";
28import * as Fiber from "effect/Fiber";
29import * as Layer from "effect/Layer";
30import * as Option from "effect/Option";
31import * as Ref from "effect/Ref";
32import * as Stream from "effect/Stream";
33import * as SqlClient from "effect/unstable/sql/SqlClient";
34
35import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
36import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
37import { CommandReceiptStoreV2, layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts";
38import { EffectOutboxV2, layer as effectOutboxLayer } from "./EffectOutbox.ts";
39import {
40 layerWithOptions as effectWorkerLayerWithOptions,
41 OrchestrationEffectExecutorV2,
42 OrchestrationEffectWorkerV2,
43 runDaemonWithOptions as runEffectWorkerDaemonWithOptions,
44} from "./EffectWorker.ts";
45import { EventSinkV2, layer as eventSinkLayer } from "./EventSink.ts";
46import { EventStoreV2, layer as eventStoreLayer } from "./EventStore.ts";
47import { layer as idAllocatorLayer } from "./IdAllocator.ts";
48import {
49 ProjectionMaintenanceV2,
50 layer as projectionMaintenanceLayer,
51} from "./ProjectionMaintenance.ts";
52import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts";
53import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
54
55const databaseLayer = SqlitePersistenceMemory;
56const eventStoreProvided = eventStoreLayer.pipe(Layer.provideMerge(databaseLayer));
57const projectionStoreProvided = projectionStoreLayer.pipe(Layer.provideMerge(databaseLayer));
58const storesProvided = Layer.mergeAll(databaseLayer, eventStoreProvided, projectionStoreProvided);
59const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesProvided));
60const effectOutboxProvided = effectOutboxLayer.pipe(Layer.provide(databaseLayer));
61const commandReceiptStoreProvided = commandReceiptStoreLayer.pipe(Layer.provide(databaseLayer));
62const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe(
63 Layer.provide(storesProvided),
64);
65const TestLayer = Layer.mergeAll(
66 storesProvided,
67 eventSinkProvided,
68 effectOutboxProvided,
69 commandReceiptStoreProvided,
70 idAllocatorLayer,
71 projectionMaintenanceProvided,
72);
73
74const providerInstanceId = ProviderInstanceId.make("codex");
75const providerDriver = ProviderDriverKind.make("codex");
76const modelSelection = {
77 instanceId: providerInstanceId,
78 model: "gpt-5.4",
79} satisfies ModelSelection;
80
81function makeThread(threadId: ThreadId, now: DateTime.Utc): OrchestrationV2AppThread {
82 return {
83 createdBy: "user",
84 creationSource: "web",
85 id: threadId,
86 projectId: ProjectId.make(`project:${threadId}`),
87 title: `Thread ${threadId}`,
88 providerInstanceId,
89 modelSelection,
90 runtimeMode: "full-access",
91 interactionMode: "default",
92 branch: null,
93 worktreePath: null,
94 activeProviderThreadId: null,
95 lineage: {
96 parentThreadId: null,
97 relationshipToParent: null,
98 rootThreadId: threadId,
99 },
100 forkedFrom: null,
101 createdAt: now,
102 updatedAt: now,
103 archivedAt: null,
104 deletedAt: null,
105 };
106}
107
108function threadCreatedEvent(input: {
109 readonly id: string;
110 readonly thread: OrchestrationV2AppThread;
111 readonly now: DateTime.Utc;
112}): OrchestrationV2DomainEvent {
113 return {
114 id: EventId.make(input.id),
115 type: "thread.created",
116 threadId: input.thread.id,
117 providerInstanceId,
118 occurredAt: input.now,
119 payload: input.thread,
120 };
121}
122
123it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
124 it.effect("paginates catch-up beyond the event-store read limit", () =>
125 Effect.gen(function* () {
126 const eventSink = yield* EventSinkV2;
127 const now = yield* DateTime.now;
128 const threadId = ThreadId.make("thread:foundation-large-catch-up");
129 const thread = makeThread(threadId, now);
130 const eventCount = 1_005;
131 const events: Array<OrchestrationV2DomainEvent> = [
132 threadCreatedEvent({ id: "event:foundation-catch-up:0", thread, now }),
133 ...Array.from({ length: eventCount - 1 }, (_, index) => ({
134 id: EventId.make(`event:foundation-catch-up:${index + 1}`),
135 type: "thread.metadata-updated" as const,
136 threadId,
137 providerInstanceId,
138 occurredAt: now,
139 payload: {
140 ...thread,
141 title: `Catch-up update ${index + 1}`,
142 },
143 })),
144 ];
145
146 yield* eventSink.write({ events });
147 const replayed = yield* eventSink.stream({ afterSequence: 0 }).pipe(
148 Stream.take(eventCount),
149 Stream.runCollect,
150 Effect.map((events) => Array.from(events)),
151 );
152
153 assert.lengthOf(replayed, eventCount);
154 assert.deepEqual(
155 replayed.map((stored) => stored.sequence),
156 Array.from({ length: eventCount }, (_, index) => index + 1),
157 );
158 }),
159 );
160
161 it.effect("does not lose or duplicate events while transitioning from catch-up to live", () =>
162 Effect.gen(function* () {
163 const eventSink = yield* EventSinkV2;
164 const now = yield* DateTime.now;
165 const threadId = ThreadId.make("thread:foundation-stream-race");
166 const thread = makeThread(threadId, now);
167 const created = yield* eventSink.write({
168 events: [threadCreatedEvent({ id: "event:foundation-stream-race:0", thread, now })],
169 });
170
171 let afterSequence = created[0]!.sequence;
172 for (let index = 1; index <= 32; index += 1) {
173 const nextEvent = {
174 id: EventId.make(`event:foundation-stream-race:${index}`),
175 type: "thread.metadata-updated" as const,
176 threadId,
177 providerInstanceId,
178 occurredAt: now,
179 payload: { ...thread, title: `Race update ${index}` },
180 } satisfies OrchestrationV2DomainEvent;
181 const reader = yield* eventSink
182 .stream({ threadId, afterSequence })
183 .pipe(Stream.runHead, Effect.forkChild);
184 yield* Effect.yieldNow;
185 const written = yield* eventSink.write({ events: [nextEvent] });
186 const received = yield* Fiber.join(reader);
187 if (Option.isNone(received)) {
188 return yield* Effect.die("The event stream ended before delivering the live event.");
189 }
190 assert.equal(received.value.sequence, written[0]?.sequence);
191 assert.equal(received.value.event.id, nextEvent.id);
192 afterSequence = received.value.sequence;
193 }
194 }),
195 );
196
197 it.effect("replays shared provider-session payloads across every bound thread", () =>
198 Effect.gen(function* () {
199 const eventSink = yield* EventSinkV2;
200 const projectionStore = yield* ProjectionStoreV2;
201 const maintenance = yield* ProjectionMaintenanceV2;
202 const now = yield* DateTime.now;
203 const firstThreadId = ThreadId.make("thread:foundation-shared-session:first");
204 const secondThreadId = ThreadId.make("thread:foundation-shared-session:second");
205 const providerSessionId = ProviderSessionId.make("provider-session:foundation:shared");
206 const firstSession = {
207 id: providerSessionId,
208 driver: providerDriver,
209 providerInstanceId,
210 status: "ready" as const,
211 cwd: "/workspace/first",
212 model: modelSelection.model,
213 capabilities: CodexProviderCapabilitiesV2,
214 createdAt: now,
215 updatedAt: now,
216 lastError: null,
217 };
218 const secondSession = { ...firstSession, cwd: "/workspace/second" };
219
220 yield* eventSink.write({
221 events: [
222 threadCreatedEvent({
223 id: "event:foundation-shared-session:first-thread",
224 thread: makeThread(firstThreadId, now),
225 now,
226 }),
227 {
228 id: EventId.make("event:foundation-shared-session:first-attachment"),
229 type: "provider-session.attached",
230 threadId: firstThreadId,
231 driver: providerDriver,
232 providerInstanceId,
233 occurredAt: now,
234 payload: firstSession,
235 },
236 threadCreatedEvent({
237 id: "event:foundation-shared-session:second-thread",
238 thread: makeThread(secondThreadId, now),
239 now,
240 }),
241 {
242 id: EventId.make("event:foundation-shared-session:second-attachment"),
243 type: "provider-session.attached",
244 threadId: secondThreadId,
245 driver: providerDriver,
246 providerInstanceId,
247 occurredAt: now,
248 payload: secondSession,
249 },
250 ],
251 });
252
253 assert.equal(
254 (yield* projectionStore.getThreadProjection(firstThreadId)).providerSessions[0]?.cwd,
255 secondSession.cwd,
256 );
257 assert.isTrue((yield* maintenance.verify).valid);
258 assert.isTrue((yield* maintenance.rebuild).valid);
259 }),
260 );
261
262 it.effect("verifies and rebuilds projections with cross-thread subagent relations", () =>
263 Effect.gen(function* () {
264 const eventSink = yield* EventSinkV2;
265 const projectionStore = yield* ProjectionStoreV2;
266 const maintenance = yield* ProjectionMaintenanceV2;
267 const now = yield* DateTime.now;
268 const parentThreadId = ThreadId.make("thread:foundation-cross-thread:parent");
269 const childThreadId = ThreadId.make("thread:foundation-cross-thread:child");
270 const childProviderThreadId = ProviderThreadId.make(
271 "provider-thread:foundation-cross-thread:child",
272 );
273 const subagentId = NodeId.make("subagent:foundation-cross-thread");
274 const spawnTransferId = ContextTransferId.make("transfer:foundation-cross-thread:spawn");
275 const resultTransferId = ContextTransferId.make("transfer:foundation-cross-thread:result");
276 const parentThread = makeThread(parentThreadId, now);
277 const childThread = {
278 ...makeThread(childThreadId, now),
279 createdBy: "agent" as const,
280 creationSource: "provider" as const,
281 lineage: {
282 parentThreadId,
283 relationshipToParent: "subagent" as const,
284 rootThreadId: parentThreadId,
285 },
286 };
287
288 yield* eventSink.write({
289 events: [
290 threadCreatedEvent({
291 id: "event:foundation-cross-thread:parent",
292 thread: parentThread,
293 now,
294 }),
295 threadCreatedEvent({
296 id: "event:foundation-cross-thread:child",
297 thread: childThread,
298 now,
299 }),
300 {
301 id: EventId.make("event:foundation-cross-thread:subagent"),
302 type: "subagent.updated",
303 threadId: parentThreadId,
304 nodeId: subagentId,
305 providerInstanceId,
306 occurredAt: now,
307 payload: {
308 id: subagentId,
309 threadId: parentThreadId,
310 runId: null,
311 parentNodeId: NodeId.make("node:foundation-cross-thread:parent"),
312 origin: "app_owned",
313 createdBy: "agent",
314 driver: providerDriver,
315 providerInstanceId,
316 providerThreadId: childProviderThreadId,
317 childThreadId,
318 nativeTaskRef: null,
319 prompt: "Inspect the child flow",
320 title: "Cross-thread child",
321 model: modelSelection.model,
322 status: "completed",
323 result: "done",
324 startedAt: now,
325 completedAt: now,
326 updatedAt: now,
327 },
328 },
329 {
330 id: EventId.make("event:foundation-cross-thread:spawn-transfer"),
331 type: "context-transfer.created",
332 threadId: childThreadId,
333 providerInstanceId,
334 occurredAt: now,
335 payload: {
336 id: spawnTransferId,
337 type: "subagent_spawn",
338 sourceThreadId: parentThreadId,
339 targetThreadId: childThreadId,
340 sourcePoint: { threadId: parentThreadId },
341 basePoint: null,
342 sourceProviderInstanceId: providerInstanceId,
343 targetProviderInstanceId: providerInstanceId,
344 targetRunId: null,
345 status: "consumed",
346 resolution: null,
347 createdBy: "agent",
348 error: null,
349 createdAt: now,
350 updatedAt: now,
351 consumedAt: now,
352 },
353 },
354 {
355 id: EventId.make("event:foundation-cross-thread:provider-thread"),
356 type: "provider-thread.updated",
357 threadId: parentThreadId,
358 driver: providerDriver,
359 providerInstanceId,
360 occurredAt: now,
361 payload: {
362 id: childProviderThreadId,
363 driver: providerDriver,
364 providerInstanceId,
365 providerSessionId: null,
366 appThreadId: childThreadId,
367 ownerNodeId: null,
368 nativeThreadRef: null,
369 nativeConversationHeadRef: null,
370 status: "idle",
371 firstRunOrdinal: 1,
372 lastRunOrdinal: 1,
373 handoffIds: [],
374 forkedFrom: null,
375 createdAt: now,
376 updatedAt: now,
377 },
378 },
379 {
380 id: EventId.make("event:foundation-cross-thread:result-transfer"),
381 type: "context-transfer.created",
382 threadId: parentThreadId,
383 providerInstanceId,
384 occurredAt: now,
385 payload: {
386 id: resultTransferId,
387 type: "subagent_result",
388 sourceThreadId: childThreadId,
389 targetThreadId: parentThreadId,
390 sourcePoint: { threadId: childThreadId },
391 basePoint: null,
392 sourceProviderInstanceId: providerInstanceId,
393 targetProviderInstanceId: providerInstanceId,
394 targetRunId: null,
395 status: "consumed",
396 resolution: null,
397 createdBy: "system",
398 error: null,
399 createdAt: now,
400 updatedAt: now,
401 consumedAt: now,
402 },
403 },
404 ],
405 });
406
407 const assertCrossThreadProjection = Effect.gen(function* () {
408 const parent = yield* projectionStore.getThreadProjection(parentThreadId);
409 const child = yield* projectionStore.getThreadProjection(childThreadId);
410 const expectedTransferIds = [spawnTransferId, resultTransferId].toSorted();
411 assert.deepEqual(
412 parent.contextTransfers.map((transfer) => transfer.id).toSorted(),
413 expectedTransferIds,
414 );
415 assert.deepEqual(
416 child.contextTransfers.map((transfer) => transfer.id).toSorted(),
417 expectedTransferIds,
418 );
419 assert.deepEqual(
420 parent.providerThreads.map((providerThread) => providerThread.id),
421 [childProviderThreadId],
422 );
423 assert.equal(child.thread.activeProviderThreadId, childProviderThreadId);
424 });
425
426 yield* assertCrossThreadProjection;
427 assert.isTrue((yield* maintenance.verify).valid);
428 assert.isTrue((yield* maintenance.rebuild).valid);
429 yield* assertCrossThreadProjection;
430 }),
431 );
432
433 it.effect(
434 "rolls back events, projections, receipts, and effects after a projection failure",
435 () =>
436 Effect.gen(function* () {
437 const eventSink = yield* EventSinkV2;
438 const eventStore = yield* EventStoreV2;
439 const receipts = yield* CommandReceiptStoreV2;
440 const outbox = yield* EffectOutboxV2;
441 const sql = yield* SqlClient.SqlClient;
442 const now = yield* DateTime.now;
443 const commandId = CommandId.make("command:foundation-atomic-failure");
444 const threadId = ThreadId.make("thread:foundation-atomic-failure");
445 const scopeId = CheckpointScopeId.make("scope:foundation-atomic-failure");
446 const checkpoint = (index: number) => ({
447 id: CheckpointId.make(`checkpoint:foundation-atomic-failure:${index}`),
448 threadId,
449 scopeId,
450 runId: null,
451 nodeId: NodeId.make("node:foundation-atomic-failure"),
452 parentCheckpointId: null,
453 ordinalWithinScope: 1,
454 appRunOrdinal: null,
455 ref: CheckpointRef.make(`checkpoint-ref:foundation-atomic-failure:${index}`),
456 status: "ready" as const,
457 files: [],
458 capturedAt: now,
459 });
460 const events = [1, 2].map(
461 (index) =>
462 ({
463 id: EventId.make(`event:foundation-atomic-failure:${index}`),
464 type: "checkpoint.captured",
465 threadId,
466 occurredAt: now,
467 payload: checkpoint(index),
468 }) satisfies OrchestrationV2DomainEvent,
469 );
470
471 const exit = yield* Effect.exit(
472 eventSink.commitCommand({
473 commandId,
474 threadId,
475 commandType: "checkpoint.atomicity-test",
476 acceptedAt: now,
477 events,
478 effects: [
479 {
480 id: "effect:foundation-atomic-failure",
481 commandId,
482 threadId,
483 request: {
484 type: "provider-turn.start",
485 runId: RunId.make("run:foundation-atomic-failure"),
486 },
487 },
488 ],
489 }),
490 );
491 assert.equal(exit._tag, "Failure");
492 assert.isTrue(Option.isNone(yield* receipts.getByCommandId(commandId)));
493 assert.deepEqual(yield* outbox.listByCommandId(commandId), []);
494 assert.deepEqual(
495 yield* eventStore.readByCommandId({ commandId }).pipe(
496 Stream.runCollect,
497 Effect.map((events) => Array.from(events)),
498 ),
499 [],
500 );
501 const checkpointRows = yield* sql<{ readonly count: number }>`
502 SELECT COUNT(*) AS count
503 FROM orchestration_v2_projection_checkpoints
504 WHERE thread_id = ${threadId}
505 `;
506 assert.equal(checkpointRows[0]?.count, 0);
507 }),
508 );
509
510 it.effect("keeps one durable effect across command retries and executes it after recovery", () =>
511 Effect.gen(function* () {
512 const eventSink = yield* EventSinkV2;
513 const outbox = yield* EffectOutboxV2;
514 const now = yield* DateTime.now;
515 const commandId = CommandId.make("command:foundation-effect-recovery");
516 const threadId = ThreadId.make("thread:foundation-effect-recovery");
517 const thread = makeThread(threadId, now);
518 const event = threadCreatedEvent({
519 id: "event:foundation-effect-recovery",
520 thread,
521 now,
522 });
523 const effect = {
524 id: "effect:foundation-effect-recovery",
525 commandId,
526 threadId,
527 request: {
528 type: "provider-turn.start" as const,
529 runId: RunId.make("run:foundation-effect-recovery"),
530 },
531 };
532
533 const first = yield* eventSink.commitCommand({
534 commandId,
535 threadId,
536 commandType: "foundation.effect-recovery",
537 acceptedAt: now,
538 events: [event],
539 effects: [effect],
540 });
541 const retry = yield* eventSink.commitCommand({
542 commandId,
543 threadId,
544 commandType: "foundation.effect-recovery",
545 acceptedAt: now,
546 events: [event],
547 effects: [effect],
548 });
549
550 assert.isTrue(first.committed);
551 assert.isFalse(retry.committed);
552 assert.equal(retry.receipt.resultSequence, first.receipt.resultSequence);
553 assert.lengthOf(retry.storedEvents, 1);
554 assert.lengthOf(yield* outbox.listByCommandId(commandId), 1);
555
556 const executionCount = yield* Ref.make(0);
557 const executorLayer = Layer.succeed(
558 OrchestrationEffectExecutorV2,
559 OrchestrationEffectExecutorV2.of({
560 execute: () => Ref.update(executionCount, (count) => count + 1),
561 }),
562 );
563 const workerLayer = effectWorkerLayerWithOptions({ workerId: "recovery-worker" }).pipe(
564 Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer)),
565 );
566 yield* Effect.gen(function* () {
567 const worker = yield* OrchestrationEffectWorkerV2;
568 assert.isTrue(yield* worker.runOnce);
569 assert.isFalse(yield* worker.runOnce);
570 }).pipe(Effect.provide(workerLayer));
571
572 assert.equal(yield* Ref.get(executionCount), 1);
573 const storedEffect = yield* outbox.get(effect.id);
574 assert.isTrue(Option.isSome(storedEffect));
575 if (Option.isSome(storedEffect)) {
576 assert.equal(storedEffect.value.status, "succeeded");
577 }
578 }),
579 );
580
581 it.effect("does not publish a stale provider start after an interrupt wins", () =>
582 Effect.gen(function* () {
583 const eventSink = yield* EventSinkV2;
584 const projectionStore = yield* ProjectionStoreV2;
585 const now = yield* DateTime.now;
586 const threadId = ThreadId.make("thread:foundation-stale-provider-start");
587 const runId = RunId.make("run:foundation-stale-provider-start");
588 const attemptId = RunAttemptId.make("run-attempt:foundation-stale-provider-start");
589 const thread = makeThread(threadId, now);
590 const startingRun: OrchestrationV2Run = {
591 id: runId,
592 threadId,
593 ordinal: 1,
594 providerInstanceId,
595 modelSelection,
596 providerThreadId: null,
597 userMessageId: MessageId.make("message:foundation-stale-provider-start"),
598 rootNodeId: null,
599 activeAttemptId: attemptId,
600 status: "starting",
601 queuePosition: null,
602 requestedAt: now,
603 startedAt: null,
604 completedAt: null,
605 checkpointId: null,
606 contextHandoffId: null,
607 };
608 yield* eventSink.write({
609 events: [
610 threadCreatedEvent({
611 id: "event:foundation-stale-provider-start:thread",
612 thread,
613 now,
614 }),
615 {
616 id: EventId.make("event:foundation-stale-provider-start:run"),
617 type: "run.created",
618 threadId,
619 runId,
620 providerInstanceId,
621 occurredAt: now,
622 payload: startingRun,
623 },
624 ],
625 });
626
627 const reachedPrecommitGap = yield* Deferred.make<void>();
628 const releaseStaleStart = yield* Deferred.make<void>();
629 const providerStartCount = yield* Ref.make(0);
630 const staleStartFiber = yield* Effect.gen(function* () {
631 yield* Deferred.succeed(reachedPrecommitGap, undefined);
632 yield* Deferred.await(releaseStaleStart);
633 const result = yield* eventSink.writeIfRunCurrent({
634 threadId,
635 runId,
636 activeAttemptId: attemptId,
637 expectedStatus: "starting",
638 events: [
639 {
640 id: EventId.make("event:foundation-stale-provider-start:running"),
641 type: "run.updated",
642 threadId,
643 runId,
644 providerInstanceId,
645 occurredAt: now,
646 payload: { ...startingRun, status: "running", startedAt: now },
647 },
648 ],
649 });
650 if (result.committed) {
651 yield* Ref.update(providerStartCount, (count) => count + 1);
652 }
653 return result;
654 }).pipe(Effect.forkChild);
655
656 yield* Deferred.await(reachedPrecommitGap);
657 const interruptedAt = yield* DateTime.now;
658 yield* eventSink.write({
659 events: [
660 {
661 id: EventId.make("event:foundation-stale-provider-start:cancelled"),
662 type: "run.updated",
663 threadId,
664 runId,
665 providerInstanceId,
666 occurredAt: interruptedAt,
667 payload: {
668 ...startingRun,
669 status: "cancelled",
670 completedAt: interruptedAt,
671 },
672 },
673 ],
674 });
675 yield* Deferred.succeed(releaseStaleStart, undefined);
676
677 const staleResult = yield* Fiber.join(staleStartFiber);
678 assert.isFalse(staleResult.committed);
679 assert.deepEqual(staleResult.storedEvents, []);
680 assert.equal(yield* Ref.get(providerStartCount), 0);
681 const projection = yield* projectionStore.getThreadProjection(threadId);
682 assert.equal(projection.runs[0]?.status, "cancelled");
683 }),
684 );
685
686 it.effect("interrupts a running process-bound effect when it is cancelled", () =>
687 Effect.gen(function* () {
688 const outbox = yield* EffectOutboxV2;
689 const commandId = CommandId.make("command:foundation-cancel-running-effect");
690 const threadId = ThreadId.make("thread:foundation-cancel-running-effect");
691 const effectId = "effect:foundation-cancel-running-effect";
692 const started = yield* Deferred.make<void>();
693 const interrupted = yield* Deferred.make<void>();
694 yield* outbox.enqueue([
695 {
696 id: effectId,
697 commandId,
698 threadId,
699 request: {
700 type: "provider-turn.start",
701 runId: RunId.make("run:foundation-cancel-running-effect"),
702 },
703 },
704 ]);
705
706 const executorLayer = Layer.succeed(
707 OrchestrationEffectExecutorV2,
708 OrchestrationEffectExecutorV2.of({
709 execute: () =>
710 Deferred.succeed(started, undefined).pipe(
711 Effect.andThen(Effect.never),
712 Effect.onInterrupt(() =>
713 Deferred.succeed(interrupted, undefined).pipe(Effect.ignore),
714 ),
715 ),
716 }),
717 );
718 const workerLayer = effectWorkerLayerWithOptions({
719 workerId: "cancellation-worker",
720 }).pipe(Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer)));
721
722 yield* Effect.gen(function* () {
723 const worker = yield* OrchestrationEffectWorkerV2;
724 const workerFiber = yield* worker.runOnce.pipe(Effect.forkChild);
725 yield* Deferred.await(started);
726 const cancelledEffectIds = yield* outbox.cancelUnsettled({
727 threadId,
728 effectTypes: ["provider-turn.start"],
729 reason: "The owning run was interrupted.",
730 });
731 assert.deepEqual(cancelledEffectIds, [effectId]);
732 yield* outbox.signalCancellations(cancelledEffectIds);
733 assert.isTrue(yield* Fiber.join(workerFiber));
734 yield* Deferred.await(interrupted);
735 }).pipe(Effect.provide(workerLayer));
736
737 const cancelled = yield* outbox.get(effectId);
738 assert.isTrue(Option.isSome(cancelled));
739 if (Option.isSome(cancelled)) assert.equal(cancelled.value.status, "cancelled");
740 }),
741 );
742
743 it.effect("treats cancellation between execution and settlement as a normal outcome", () =>
744 Effect.gen(function* () {
745 const effectId = "effect:foundation-cancel-before-settlement";
746 const threadId = ThreadId.make("thread:foundation-cancel-before-settlement");
747 const commandId = CommandId.make("command:foundation-cancel-before-settlement");
748 const now = DateTime.formatIso(yield* DateTime.now);
749 const claimedEffect = {
750 id: effectId,
751 commandId,
752 threadId,
753 request: { type: "terminal.cleanup" as const },
754 status: "running" as const,
755 attemptCount: 1,
756 availableAt: now,
757 leaseOwner: "settlement-race-worker",
758 leaseExpiresAt: now,
759 createdAt: now,
760 updatedAt: now,
761 completedAt: null,
762 lastError: null,
763 };
764 const outboxLayer = Layer.mock(EffectOutboxV2)({
765 claimNext: () => Effect.succeed(Option.some(claimedEffect)),
766 awaitCancellation: () => Effect.never,
767 clearCancellation: () => Effect.void,
768 succeed: () => Effect.succeed(false),
769 get: () =>
770 Effect.succeed(
771 Option.some({
772 ...claimedEffect,
773 status: "cancelled" as const,
774 leaseOwner: null,
775 leaseExpiresAt: null,
776 completedAt: now,
777 }),
778 ),
779 });
780 const executorLayer = Layer.succeed(
781 OrchestrationEffectExecutorV2,
782 OrchestrationEffectExecutorV2.of({ execute: () => Effect.void }),
783 );
784 const workerLayer = effectWorkerLayerWithOptions({
785 workerId: "settlement-race-worker",
786 }).pipe(Layer.provide(Layer.merge(outboxLayer, executorLayer)));
787
788 assert.isTrue(
789 yield* OrchestrationEffectWorkerV2.pipe(
790 Effect.flatMap((worker) => worker.runOnce),
791 Effect.provide(workerLayer),
792 ),
793 );
794 }),
795 );
796
797 it.effect("does not start an effect that was cancelled during claim registration", () =>
798 Effect.gen(function* () {
799 const effectId = "effect:foundation-cancelled-during-claim";
800 const threadId = ThreadId.make("thread:foundation-cancelled-during-claim");
801 const commandId = CommandId.make("command:foundation-cancelled-during-claim");
802 const now = DateTime.formatIso(yield* DateTime.now);
803 const claimedEffect = {
804 id: effectId,
805 commandId,
806 threadId,
807 request: { type: "terminal.cleanup" as const },
808 status: "running" as const,
809 attemptCount: 1,
810 availableAt: now,
811 leaseOwner: "claim-cancellation-worker",
812 leaseExpiresAt: now,
813 createdAt: now,
814 updatedAt: now,
815 completedAt: null,
816 lastError: null,
817 };
818 const executionCount = yield* Ref.make(0);
819 const outboxLayer = Layer.mock(EffectOutboxV2)({
820 claimNext: () => Effect.succeed(Option.some(claimedEffect)),
821 get: () =>
822 Effect.succeed(
823 Option.some({
824 ...claimedEffect,
825 status: "cancelled" as const,
826 leaseOwner: null,
827 leaseExpiresAt: null,
828 completedAt: now,
829 }),
830 ),
831 clearCancellation: () => Effect.void,
832 awaitCancellation: () => Effect.never,
833 });
834 const executorLayer = Layer.succeed(
835 OrchestrationEffectExecutorV2,
836 OrchestrationEffectExecutorV2.of({
837 execute: () => Ref.update(executionCount, (count) => count + 1),
838 }),
839 );
840 const workerLayer = effectWorkerLayerWithOptions({
841 workerId: "claim-cancellation-worker",
842 }).pipe(Layer.provide(Layer.merge(outboxLayer, executorLayer)));
843
844 assert.isTrue(
845 yield* OrchestrationEffectWorkerV2.pipe(
846 Effect.flatMap((worker) => worker.runOnce),
847 Effect.provide(workerLayer),
848 ),
849 );
850 assert.equal(yield* Ref.get(executionCount), 0);
851 }),
852 );
853
854 it.effect("allows only one worker to claim an available effect", () =>
855 Effect.gen(function* () {
856 const outbox = yield* EffectOutboxV2;
857 const commandId = CommandId.make("command:foundation-exclusive-claim");
858 yield* outbox.enqueue([
859 {
860 id: "effect:foundation-exclusive-claim",
861 commandId,
862 threadId: ThreadId.make("thread:foundation-exclusive-claim"),
863 request: {
864 type: "provider-turn.start",
865 runId: RunId.make("run:foundation-exclusive-claim"),
866 },
867 },
868 ]);
869
870 const claims = yield* Effect.all(
871 [
872 outbox.claimNext({ workerId: "worker-a", leaseDurationMs: 30_000 }),
873 outbox.claimNext({ workerId: "worker-b", leaseDurationMs: 30_000 }),
874 ],
875 { concurrency: "unbounded" },
876 );
877 assert.equal(claims.filter(Option.isSome).length, 1);
878 assert.equal(claims.filter(Option.isNone).length, 1);
879 const claimedByA = claims[0];
880 const claimedByB = claims[1];
881 if (Option.isSome(claimedByA)) {
882 yield* outbox.succeed({ effectId: claimedByA.value.id, workerId: "worker-a" });
883 }
884 if (Option.isSome(claimedByB)) {
885 yield* outbox.succeed({ effectId: claimedByB.value.id, workerId: "worker-b" });
886 }
887 }),
888 );
889
890 it.effect("runs distinct threads concurrently while serializing effects within a thread", () =>
891 Effect.gen(function* () {
892 const outbox = yield* EffectOutboxV2;
893 const commandId = CommandId.make("command:foundation-concurrent-effects");
894 const threadA = ThreadId.make("thread:foundation-concurrent-effects:a");
895 const threadB = ThreadId.make("thread:foundation-concurrent-effects:b");
896 const effectA1 = "effect:foundation-concurrent-effects:a1";
897 const effectA2 = "effect:foundation-concurrent-effects:a2";
898 const effectB1 = "effect:foundation-concurrent-effects:b1";
899 const startedA1 = yield* Deferred.make<void>();
900 const startedA2 = yield* Deferred.make<void>();
901 const startedB1 = yield* Deferred.make<void>();
902 const releaseA1 = yield* Deferred.make<void>();
903 const releaseA2 = yield* Deferred.make<void>();
904 const releaseB1 = yield* Deferred.make<void>();
905 const gates = new Map([
906 [effectA1, { started: startedA1, release: releaseA1 }],
907 [effectA2, { started: startedA2, release: releaseA2 }],
908 [effectB1, { started: startedB1, release: releaseB1 }],
909 ]);
910 const executorLayer = Layer.succeed(
911 OrchestrationEffectExecutorV2,
912 OrchestrationEffectExecutorV2.of({
913 execute: (effect) => {
914 const gate = gates.get(effect.id);
915 if (gate === undefined) return Effect.die(`Missing gate for ${effect.id}`);
916 return Deferred.succeed(gate.started, undefined).pipe(
917 Effect.andThen(Deferred.await(gate.release)),
918 );
919 },
920 }),
921 );
922 const workerLayer = effectWorkerLayerWithOptions({
923 workerId: "concurrency-worker",
924 }).pipe(Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer)));
925
926 yield* Effect.gen(function* () {
927 yield* runEffectWorkerDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
928 // Let both slots reach the idle wait before work becomes available.
929 yield* Effect.yieldNow;
930 yield* Effect.yieldNow;
931 yield* outbox.enqueue([
932 {
933 id: effectA1,
934 commandId,
935 threadId: threadA,
936 request: {
937 type: "provider-turn.start",
938 runId: RunId.make("run:foundation-concurrent-effects:a1"),
939 },
940 },
941 {
942 id: effectA2,
943 commandId,
944 threadId: threadA,
945 request: {
946 type: "provider-turn.start",
947 runId: RunId.make("run:foundation-concurrent-effects:a2"),
948 },
949 },
950 {
951 id: effectB1,
952 commandId,
953 threadId: threadB,
954 request: {
955 type: "provider-turn.start",
956 runId: RunId.make("run:foundation-concurrent-effects:b1"),
957 },
958 },
959 ]);
960
961 yield* Effect.all([Deferred.await(startedA1), Deferred.await(startedB1)]);
962 assert.isFalse(yield* Deferred.isDone(startedA2));
963
964 yield* Deferred.succeed(releaseA1, undefined);
965 yield* Deferred.succeed(releaseB1, undefined);
966 yield* Deferred.await(startedA2);
967 yield* Deferred.succeed(releaseA2, undefined);
968 let settled = false;
969 while (!settled) {
970 settled = (yield* outbox.listByCommandId(commandId)).every(
971 (effect) => effect.status === "succeeded",
972 );
973 if (!settled) yield* Effect.yieldNow;
974 }
975 }).pipe(Effect.provide(workerLayer), Effect.scoped);
976 }),
977 );
978
979 it.effect("does not reclaim a running effect after its process-local lease expires", () =>
980 Effect.gen(function* () {
981 const outbox = yield* EffectOutboxV2;
982 const sql = yield* SqlClient.SqlClient;
983 const commandId = CommandId.make("command:foundation-no-live-reclaim");
984 const threadId = ThreadId.make("thread:foundation-no-live-reclaim");
985 const firstEffectId = "effect:foundation-no-live-reclaim:first";
986 const secondEffectId = "effect:foundation-no-live-reclaim:second";
987 const firstStarted = yield* Deferred.make<void>();
988 const releaseFirst = yield* Deferred.make<void>();
989 const executions = yield* Ref.make<ReadonlyArray<string>>([]);
990 yield* outbox.enqueue([
991 {
992 id: firstEffectId,
993 commandId,
994 threadId,
995 request: { type: "terminal.cleanup" },
996 },
997 {
998 id: secondEffectId,
999 commandId,
1000 threadId,
1001 request: { type: "terminal.cleanup" },
1002 },
1003 ]);
1004
1005 const executorLayer = Layer.succeed(
1006 OrchestrationEffectExecutorV2,
1007 OrchestrationEffectExecutorV2.of({
1008 execute: (effect) =>
1009 Ref.update(executions, (current) => [...current, effect.id]).pipe(
1010 Effect.andThen(
1011 effect.id === firstEffectId
1012 ? Deferred.succeed(firstStarted, undefined).pipe(
1013 Effect.andThen(Deferred.await(releaseFirst)),
1014 )
1015 : Effect.void,
1016 ),
1017 ),
1018 }),
1019 );
1020 const workerLayer = effectWorkerLayerWithOptions({
1021 workerId: "no-live-reclaim-worker",
1022 leaseDurationMs: 1,
1023 }).pipe(Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer)));
1024
1025 yield* Effect.gen(function* () {
1026 const worker = yield* OrchestrationEffectWorkerV2;
1027 const firstFiber = yield* worker.runOnce.pipe(Effect.forkChild);
1028 yield* Deferred.await(firstStarted);
1029 yield* sql`
1030 UPDATE orchestration_v2_effect_outbox
1031 SET lease_expires_at = '1970-01-01T00:00:00.000Z'
1032 WHERE effect_id = ${firstEffectId}
1033 `;
1034
1035 assert.isFalse(yield* worker.runOnce);
1036 assert.deepEqual(yield* Ref.get(executions), [firstEffectId]);
1037
1038 yield* Deferred.succeed(releaseFirst, undefined);
1039 assert.isTrue(yield* Fiber.join(firstFiber));
1040 assert.isTrue(yield* worker.runOnce);
1041 assert.deepEqual(yield* Ref.get(executions), [firstEffectId, secondEffectId]);
1042 }).pipe(Effect.provide(workerLayer));
1043 }),
1044 );
1045
1046 it.effect(
1047 "retires live provider effects and requeues replay-safe effects after process loss",
1048 () =>
1049 Effect.gen(function* () {
1050 const outbox = yield* EffectOutboxV2;
1051 const commandId = CommandId.make("command:foundation-reclaim-running");
1052 yield* outbox.enqueue([
1053 {
1054 id: "effect:a-foundation-cancel-provider-turn",
1055 commandId,
1056 threadId: ThreadId.make("thread:foundation-reclaim-running"),
1057 request: {
1058 type: "provider-turn.start",
1059 runId: RunId.make("run:foundation-reclaim-running"),
1060 },
1061 },
1062 {
1063 id: "effect:b-foundation-requeue-cleanup",
1064 commandId,
1065 threadId: ThreadId.make("thread:foundation-reclaim-cleanup"),
1066 request: { type: "terminal.cleanup" },
1067 },
1068 ]);
1069 assert.isTrue(
1070 Option.isSome(
1071 yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
1072 ),
1073 );
1074 assert.isTrue(
1075 Option.isSome(
1076 yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
1077 ),
1078 );
1079 assert.deepEqual(yield* outbox.reconcileAfterProcessLoss, {
1080 cancelled: 1,
1081 requeued: 1,
1082 });
1083 const cancelled = yield* outbox.get("effect:a-foundation-cancel-provider-turn");
1084 assert.isTrue(Option.isSome(cancelled));
1085 if (Option.isSome(cancelled)) assert.equal(cancelled.value.status, "cancelled");
1086
1087 const reclaimed = yield* outbox.claimNext({
1088 workerId: "recovery-worker",
1089 leaseDurationMs: 30_000,
1090 });
1091 assert.isTrue(Option.isSome(reclaimed));
1092 if (Option.isSome(reclaimed)) {
1093 assert.equal(reclaimed.value.request.type, "terminal.cleanup");
1094 assert.equal(reclaimed.value.attemptCount, 2);
1095 }
1096 }),
1097 );
1098
1099 it.effect("atomically cancels stale runs and their process-bound effects", () =>
1100 Effect.gen(function* () {
1101 const eventSink = yield* EventSinkV2;
1102 const outbox = yield* EffectOutboxV2;
1103 const projectionStore = yield* ProjectionStoreV2;
1104 const now = yield* DateTime.now;
1105 const threadId = ThreadId.make("thread:foundation-process-loss");
1106 const runId = RunId.make("run:foundation-process-loss");
1107 const commandId = CommandId.make("command:foundation-process-loss");
1108 const thread = makeThread(threadId, now);
1109 yield* eventSink.commitCommand({
1110 commandId,
1111 threadId,
1112 commandType: "foundation.process-loss",
1113 acceptedAt: now,
1114 events: [
1115 threadCreatedEvent({ id: "event:foundation-process-loss:thread", thread, now }),
1116 {
1117 id: EventId.make("event:foundation-process-loss:run"),
1118 type: "run.created",
1119 threadId,
1120 runId,
1121 providerInstanceId,
1122 occurredAt: now,
1123 payload: {
1124 id: runId,
1125 threadId,
1126 ordinal: 1,
1127 providerInstanceId,
1128 modelSelection,
1129 providerThreadId: null,
1130 userMessageId: MessageId.make("message:foundation-process-loss"),
1131 rootNodeId: null,
1132 activeAttemptId: null,
1133 status: "starting",
1134 queuePosition: null,
1135 requestedAt: now,
1136 startedAt: null,
1137 completedAt: null,
1138 checkpointId: null,
1139 contextHandoffId: null,
1140 },
1141 },
1142 ],
1143 effects: [
1144 {
1145 id: "effect:foundation-process-loss",
1146 commandId,
1147 threadId,
1148 request: { type: "provider-turn.start", runId },
1149 },
1150 ],
1151 });
1152 assert.isTrue(
1153 Option.isSome(
1154 yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
1155 ),
1156 );
1157
1158 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
1159 Effect.provideService(
1160 OrchestrationEffectWorkerV2,
1161 OrchestrationEffectWorkerV2.of({
1162 awaitWork: Effect.void,
1163 runOnce: Effect.succeed(false),
1164 drain: () => Effect.succeed(0),
1165 }),
1166 ),
1167 );
1168 const first = yield* recovery.recover;
1169 assert.equal(first.terminalizedRuns, 1);
1170 assert.equal(first.retiredEffects, 1);
1171 const projection = yield* projectionStore.getThreadProjection(threadId);
1172 assert.equal(projection.runs[0]?.status, "cancelled");
1173 const effect = yield* outbox.get("effect:foundation-process-loss");
1174 assert.isTrue(Option.isSome(effect));
1175 if (Option.isSome(effect)) assert.equal(effect.value.status, "cancelled");
1176
1177 const second = yield* recovery.recover;
1178 assert.equal(second.terminalizedRuns, 0);
1179 assert.equal(second.retiredEffects, 0);
1180 }),
1181 );
1182
1183 it.effect("allocates collision-free positions beyond 100 items and rebuilds equivalently", () =>
1184 Effect.gen(function* () {
1185 const eventSink = yield* EventSinkV2;
1186 const projectionStore = yield* ProjectionStoreV2;
1187 const maintenance = yield* ProjectionMaintenanceV2;
1188 const sql = yield* SqlClient.SqlClient;
1189 const now = yield* DateTime.now;
1190 const threadId = ThreadId.make("thread:foundation-many-items");
1191 const runId = RunId.make("run:foundation-many-items");
1192 const providerThreadId = ProviderThreadId.make("provider-thread:foundation-many-items");
1193 const thread = makeThread(threadId, now);
1194 const providerThreadEvent = {
1195 id: EventId.make("event:foundation-many-items:provider-thread"),
1196 type: "provider-thread.updated" as const,
1197 threadId,
1198 providerInstanceId,
1199 occurredAt: now,
1200 payload: {
1201 id: providerThreadId,
1202 driver: providerDriver,
1203 providerInstanceId,
1204 providerSessionId: null,
1205 appThreadId: threadId,
1206 ownerNodeId: null,
1207 nativeThreadRef: null,
1208 nativeConversationHeadRef: null,
1209 status: "active" as const,
1210 firstRunOrdinal: 1,
1211 lastRunOrdinal: 1,
1212 handoffIds: [],
1213 forkedFrom: null,
1214 createdAt: now,
1215 updatedAt: now,
1216 },
1217 } satisfies OrchestrationV2DomainEvent;
1218 const runEvent = {
1219 id: EventId.make("event:foundation-many-items:run"),
1220 type: "run.created" as const,
1221 threadId,
1222 runId,
1223 providerInstanceId,
1224 occurredAt: now,
1225 payload: {
1226 id: runId,
1227 threadId,
1228 ordinal: 1,
1229 providerInstanceId,
1230 modelSelection,
1231 providerThreadId: null,
1232 userMessageId: MessageId.make("message:foundation-many-items"),
1233 rootNodeId: null,
1234 activeAttemptId: null,
1235 status: "completed" as const,
1236 queuePosition: null,
1237 requestedAt: now,
1238 startedAt: now,
1239 completedAt: now,
1240 checkpointId: null,
1241 contextHandoffId: null,
1242 },
1243 } satisfies OrchestrationV2DomainEvent;
1244 const items = Array.from({ length: 151 }, (_, index) => ({
1245 id: TurnItemId.make(`turn-item:foundation-many-items:${index}`),
1246 threadId,
1247 runId,
1248 nodeId: null,
1249 providerThreadId: null,
1250 providerTurnId: null,
1251 nativeItemRef: null,
1252 parentItemId: null,
1253 ordinal: index % 3,
1254 status: "completed" as const,
1255 title: null,
1256 startedAt: now,
1257 completedAt: now,
1258 updatedAt: now,
1259 type: "dynamic_tool" as const,
1260 toolName: `tool-${index}`,
1261 input: { index },
1262 output: { completed: true },
1263 }));
1264 const itemEvents = items.map(
1265 (item, index) =>
1266 ({
1267 id: EventId.make(`event:foundation-many-items:item:${index}`),
1268 type: "turn-item.updated",
1269 threadId,
1270 runId,
1271 providerInstanceId,
1272 occurredAt: now,
1273 payload: item,
1274 }) satisfies OrchestrationV2DomainEvent,
1275 );
1276
1277 yield* eventSink.write({
1278 events: [
1279 threadCreatedEvent({ id: "event:foundation-many-items:thread", thread, now }),
1280 providerThreadEvent,
1281 runEvent,
1282 ...itemEvents,
1283 ],
1284 });
1285 const beforeUpdate = yield* projectionStore.getThreadProjection(threadId);
1286 assert.equal(beforeUpdate.thread.activeProviderThreadId, providerThreadId);
1287 const ordinals = beforeUpdate.turnItems.map((item) => item.ordinal);
1288 assert.lengthOf(ordinals, 151);
1289 assert.equal(new Set(ordinals).size, 151);
1290 assert.isTrue(ordinals.every((ordinal) => ordinal > 1_000_000));
1291 assert.isTrue(
1292 ordinals.every((ordinal, index) => index === 0 || ordinal > ordinals[index - 1]!),
1293 );
1294
1295 yield* eventSink.write({
1296 events: [
1297 {
1298 id: EventId.make("event:foundation-many-items:update"),
1299 type: "turn-item.updated",
1300 threadId,
1301 runId,
1302 providerInstanceId,
1303 occurredAt: now,
1304 payload: { ...items[0]!, ordinal: 99_999_999, title: "Updated" },
1305 },
1306 ],
1307 });
1308 const afterUpdate = yield* projectionStore.getThreadProjection(threadId);
1309 assert.equal(afterUpdate.turnItems[0]?.ordinal, ordinals[0]);
1310 assert.equal((yield* maintenance.verify).valid, true);
1311
1312 yield* sql`
1313 UPDATE orchestration_v2_projection_turn_items
1314 SET payload_json = '{}'
1315 WHERE turn_item_id = ${items[75]!.id}
1316 `;
1317 const broken = yield* maintenance.verify;
1318 assert.isFalse(broken.valid);
1319 assert.deepEqual(broken.unreadableThreadIds, [threadId]);
1320
1321 const rebuilt = yield* maintenance.rebuild;
1322 assert.isTrue(rebuilt.valid);
1323 assert.lengthOf((yield* projectionStore.getThreadProjection(threadId)).turnItems, 151);
1324 }),
1325 );
1326});
1327
1328it.live("keeps claiming new work after repeated idle periods", () =>
1329 Effect.gen(function* () {
1330 const outbox = yield* EffectOutboxV2;
1331 const completed = new Map<string, Deferred.Deferred<void>>();
1332 const executorLayer = Layer.succeed(
1333 OrchestrationEffectExecutorV2,
1334 OrchestrationEffectExecutorV2.of({
1335 execute: (effect) => {
1336 const completion = completed.get(effect.id);
1337 return completion === undefined
1338 ? Effect.die(`Missing completion signal for ${effect.id}`)
1339 : Deferred.succeed(completion, undefined).pipe(Effect.asVoid);
1340 },
1341 }),
1342 );
1343 const workerLayer = effectWorkerLayerWithOptions({
1344 workerId: "idle-wave-worker",
1345 }).pipe(Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer)));
1346
1347 yield* Effect.gen(function* () {
1348 yield* runEffectWorkerDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
1349 for (let wave = 1; wave <= 6; wave += 1) {
1350 yield* Effect.sleep("125 millis");
1351 const effectId = `effect:foundation-idle-wave:${wave}`;
1352 const completion = yield* Deferred.make<void>();
1353 completed.set(effectId, completion);
1354 yield* outbox.enqueue([
1355 {
1356 id: effectId,
1357 commandId: CommandId.make(`command:foundation-idle-wave:${wave}`),
1358 threadId: ThreadId.make(`thread:foundation-idle-wave:${wave}`),
1359 request: { type: "terminal.cleanup" },
1360 },
1361 ]);
1362 const observed = yield* Deferred.await(completion).pipe(Effect.timeoutOption("2 seconds"));
1363 assert.isTrue(Option.isSome(observed), `worker stopped before idle wave ${wave}`);
1364 }
1365 }).pipe(Effect.provide(workerLayer), Effect.scoped);
1366 }).pipe(Effect.provide(TestLayer)),
1367);