Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 ProviderSessionId,
5 ProviderThreadId,
6 ProviderTurnId,
7 RunAttemptId,
8 RunId,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Ref from "effect/Ref";
17
18import { CheckpointRollbackServiceV2 } from "./CheckpointRollbackService.ts";
19import type { OrchestrationEffectV2 } from "./EffectOutbox.ts";
20import { executorLayer, OrchestrationEffectExecutorV2 } from "./EffectWorker.ts";
21import { RunFinalizationService } from "./RunFinalizationService.ts";
22import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
23import { ProviderTurnControlServiceV2 } from "./ProviderTurnControlService.ts";
24import { ProviderTurnStartError, ProviderTurnStartServiceV2 } from "./ProviderTurnStartService.ts";
25import { RuntimeRequestServiceV2 } from "./RuntimeRequestService.ts";
26
27const threadId = ThreadId.make("thread:effect-worker-restart");
28const oldSessionId = ProviderSessionId.make("provider-session:effect-worker-restart:old");
29const replacementSessionId = ProviderSessionId.make(
30 "provider-session:effect-worker-restart:replacement",
31);
32const providerThreadId = ProviderThreadId.make("provider-thread:effect-worker-restart");
33const providerTurnId = ProviderTurnId.make("provider-turn:effect-worker-restart");
34const attemptId = RunAttemptId.make("run-attempt:effect-worker-restart");
35const runId = RunId.make("run:effect-worker-restart");
36
37function restartEffect(
38 now: DateTime.Utc,
39 sessionTransition: NonNullable<
40 Extract<
41 OrchestrationEffectV2["request"],
42 { readonly type: "provider-turn.restart" }
43 >["sessionTransition"]
44 >,
45): OrchestrationEffectV2 {
46 const timestamp = DateTime.formatIso(now);
47 return {
48 id: `effect:restart:${sessionTransition.type}`,
49 commandId: CommandId.make(`command:restart:${sessionTransition.type}`),
50 threadId,
51 request: {
52 type: "provider-turn.restart",
53 providerSessionId: oldSessionId,
54 providerThreadId,
55 providerTurnId,
56 interruptedAttemptId: attemptId,
57 runId,
58 sessionTransition,
59 },
60 status: "running",
61 attemptCount: 1,
62 availableAt: timestamp,
63 leaseOwner: "test-worker",
64 leaseExpiresAt: timestamp,
65 createdAt: timestamp,
66 updatedAt: timestamp,
67 completedAt: null,
68 lastError: null,
69 };
70}
71
72function makeExecutorLayer(input: {
73 readonly events: Ref.Ref<ReadonlyArray<string>>;
74 readonly failFirstStart?: Ref.Ref<boolean>;
75}) {
76 const record = (event: string) => Ref.update(input.events, (events) => [...events, event]);
77 const dependencies = Layer.mergeAll(
78 Layer.succeed(
79 ProviderTurnControlServiceV2,
80 ProviderTurnControlServiceV2.of({
81 interrupt: () => Effect.void,
82 steer: () => Effect.void,
83 interruptAndAwaitTerminal: (request) =>
84 record(
85 request.replacementProviderSessionId === undefined
86 ? "interrupt"
87 : `interrupt:${request.replacementProviderSessionId}`,
88 ),
89 }),
90 ),
91 Layer.succeed(
92 ProviderSessionManagerV2,
93 ProviderSessionManagerV2.of({
94 shutdown: Effect.void,
95 open: () => Effect.die("unused open"),
96 get: () => Effect.succeed(Option.none()),
97 close: () => Effect.void,
98 release: () => record("release"),
99 detach: () => record("detach"),
100 }),
101 ),
102 Layer.succeed(
103 ProviderTurnStartServiceV2,
104 ProviderTurnStartServiceV2.of({
105 start: () =>
106 Effect.gen(function* () {
107 yield* record("start");
108 if (
109 input.failFirstStart !== undefined &&
110 (yield* Ref.getAndSet(input.failFirstStart, false))
111 ) {
112 return yield* new ProviderTurnStartError({
113 runId,
114 cause: "simulated first start failure",
115 });
116 }
117 }),
118 }),
119 ),
120 Layer.succeed(
121 RunFinalizationService,
122 RunFinalizationService.of({ finalize: () => Effect.void }),
123 ),
124 Layer.succeed(
125 CheckpointRollbackServiceV2,
126 CheckpointRollbackServiceV2.of({ execute: () => Effect.void }),
127 ),
128 Layer.succeed(
129 RuntimeRequestServiceV2,
130 RuntimeRequestServiceV2.of({ respond: () => Effect.void }),
131 ),
132 );
133 return executorLayer.pipe(Layer.provide(dependencies));
134}
135
136it.effect("detaches a handed-off session only after the old turn terminalizes", () =>
137 Effect.gen(function* () {
138 const now = yield* DateTime.now;
139 const events = yield* Ref.make<ReadonlyArray<string>>([]);
140
141 yield* Effect.gen(function* () {
142 const executor = yield* OrchestrationEffectExecutorV2;
143 yield* executor.execute(restartEffect(now, { type: "detach" }));
144 }).pipe(Effect.provide(makeExecutorLayer({ events })));
145
146 assert.deepEqual(yield* Ref.get(events), ["interrupt", "detach", "start"]);
147 }),
148);
149
150it.effect("safely retries after replacement cleanup succeeds and start fails", () =>
151 Effect.gen(function* () {
152 const now = yield* DateTime.now;
153 const events = yield* Ref.make<ReadonlyArray<string>>([]);
154 const failFirstStart = yield* Ref.make(true);
155 const effect = restartEffect(now, {
156 type: "replace",
157 replacementProviderSessionId: replacementSessionId,
158 });
159 const layer = makeExecutorLayer({ events, failFirstStart });
160
161 const first = yield* Effect.gen(function* () {
162 const executor = yield* OrchestrationEffectExecutorV2;
163 return yield* Effect.exit(executor.execute(effect));
164 }).pipe(Effect.provide(layer));
165 assert.isTrue(Exit.isFailure(first));
166
167 yield* Effect.gen(function* () {
168 const executor = yield* OrchestrationEffectExecutorV2;
169 yield* executor.execute(effect);
170 }).pipe(Effect.provide(layer));
171
172 assert.deepEqual(yield* Ref.get(events), [
173 `interrupt:${replacementSessionId}`,
174 "detach",
175 "start",
176 `interrupt:${replacementSessionId}`,
177 "detach",
178 "start",
179 ]);
180 }),
181);