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

ProviderRuntimeRecoveryService.test.ts

526 lines18.4 KB

1import { assert, it, vi } from "@effect/vitest";
2import {
3 MessageId,
4 NodeId,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 ProviderSessionId,
8 ProviderThreadId,
9 ProviderTurnId,
10 RunAttemptId,
11 RunId,
12 RuntimeRequestId,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationV2ThreadProjection,
16} from "@t3tools/contracts";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Ref from "effect/Ref";
20​
21import * as EffectWorker from "./EffectWorker.ts";
22import * as EffectOutbox from "./EffectOutbox.ts";
23import * as EventSink from "./EventSink.ts";
24import * as IdAllocator from "./IdAllocator.ts";
25import * as ProjectionStore from "./ProjectionStore.ts";
26import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
27​
28it.effect("drains durable effects before reporting recovery complete", () =>
29 Effect.gen(function* () {
30 const runs = yield* Ref.make(0);
31 const layer = ProviderRuntimeRecovery.layer.pipe(
32 Layer.provide(
33 Layer.mergeAll(
34 Layer.mock(ProjectionStore.ProjectionStoreV2)({
35 getShellSnapshot: () =>
36 Effect.succeed({
37 schemaVersion: 2,
38 snapshotSequence: 0,
39 threads: [],
40 archivedThreads: [],
41 }),
42 }),
43 Layer.mock(EventSink.EventSinkV2)({}),
44 IdAllocator.layer,
45 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
46 runOnce: Ref.getAndUpdate(runs, (count) => count + 1).pipe(
47 Effect.map((count) => count < 2),
48 ),
49 }),
50 Layer.mock(EffectOutbox.EffectOutboxV2)({
51 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
52 }),
53 ),
54 ),
55 );
56 const summary = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService.pipe(
57 Effect.flatMap((recovery) => recovery.recover),
58 Effect.provide(layer),
59 );
60 assert.deepEqual(summary, {
61 terminalizedRuns: 0,
62 stoppedSessions: 0,
63 closedRequests: 0,
64 retiredEffects: 0,
65 requeuedEffects: 0,
66 executedEffects: 2,
67 });
68 }),
69);
70​
71it.effect("expires orphaned runtime requests before command readiness", () => {
72 const threadId = ThreadId.make("thread_recovery_requests");
73 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
74 null;
75 const committed = vi.fn(
76 (input: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0]) => {
77 committedInput = input;
78 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
79 },
80 );
81 const projection = {
82 thread: { id: threadId },
83 runtimeRequests: [
84 {
85 id: RuntimeRequestId.make("request_orphaned"),
86 nodeId: NodeId.make("node_orphaned"),
87 status: "pending",
88 responseCapability: { type: "not_resumable", reason: "old process" },
89 },
90 ],
91 providerSessions: [],
92 providerThreads: [],
93 runs: [],
94 nodes: [],
95 } as unknown as OrchestrationV2ThreadProjection;
96 const layer = ProviderRuntimeRecovery.layer.pipe(
97 Layer.provide(
98 Layer.mergeAll(
99 Layer.mock(ProjectionStore.ProjectionStoreV2)({
100 getShellSnapshot: () =>
101 Effect.succeed({
102 schemaVersion: 2,
103 snapshotSequence: 0,
104 threads: [{ id: threadId }],
105 archivedThreads: [],
106 } as never),
107 getThreadProjection: () => Effect.succeed(projection),
108 }),
109 Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }),
110 IdAllocator.layer,
111 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
112 Layer.mock(EffectOutbox.EffectOutboxV2)({
113 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
114 }),
115 ),
116 ),
117 );
118 return Effect.gen(function* () {
119 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).recover;
120 const command = committedInput;
121 assert.isNotNull(command);
122 if (command === null) return;
123 assert.equal(command?.events[0]?.type, "runtime-request.updated");
124 if (command?.events[0]?.type === "runtime-request.updated") {
125 assert.equal(command.events[0].payload.status, "expired");
126 assert.equal(command.events[0].payload.responseCapability.type, "not_resumable");
127 }
128 }).pipe(Effect.provide(layer));
129});
130​
131it.effect("uses the same reconciliation path to cancel runtime requests during shutdown", () => {
132 const threadId = ThreadId.make("thread_shutdown_requests");
133 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
134 null;
135 const projection = {
136 thread: { id: threadId },
137 runtimeRequests: [
138 {
139 id: RuntimeRequestId.make("request_shutdown"),
140 nodeId: NodeId.make("node_shutdown"),
141 status: "pending",
142 responseCapability: { type: "live" },
143 },
144 ],
145 providerSessions: [],
146 providerThreads: [],
147 runs: [],
148 nodes: [],
149 } as unknown as OrchestrationV2ThreadProjection;
150 const layer = ProviderRuntimeRecovery.layer.pipe(
151 Layer.provide(
152 Layer.mergeAll(
153 Layer.mock(ProjectionStore.ProjectionStoreV2)({
154 getShellSnapshot: () =>
155 Effect.succeed({
156 schemaVersion: 2,
157 snapshotSequence: 0,
158 threads: [{ id: threadId }],
159 archivedThreads: [],
160 } as never),
161 getThreadProjection: () => Effect.succeed(projection),
162 }),
163 Layer.mock(EventSink.EventSinkV2)({
164 commitCommand: (input) => {
165 committedInput = input;
166 return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
167 },
168 }),
169 IdAllocator.layer,
170 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
171 Layer.mock(EffectOutbox.EffectOutboxV2)({
172 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
173 }),
174 ),
175 ),
176 );
177​
178 return Effect.gen(function* () {
179 const summary =
180 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("shutdown");
181 assert.equal(summary.closedRequests, 1);
182 assert.equal(summary.retiredEffects, 1);
183 const requestEvent = committedInput?.events[0];
184 assert.equal(requestEvent?.type, "runtime-request.updated");
185 if (requestEvent?.type === "runtime-request.updated") {
186 assert.equal(requestEvent.payload.status, "cancelled");
187 assert.equal(requestEvent.payload.responseCapability.type, "not_resumable");
188 if (requestEvent.payload.responseCapability.type === "not_resumable") {
189 assert.match(requestEvent.payload.responseCapability.reason, /shut down/);
190 }
191 }
192 }).pipe(Effect.provide(layer));
193});
194​
195it.effect("preserves a waiting run while its replay-safe checkpoint capture is unsettled", () => {
196 const threadId = ThreadId.make("thread_waiting_checkpoint");
197 const runId = RunId.make("run_waiting_checkpoint");
198 const committed = vi.fn(() => Effect.succeed({ committed: true } as never));
199 const projection = {
200 thread: { id: threadId },
201 runtimeRequests: [],
202 providerSessions: [],
203 providerThreads: [],
204 runs: [{ id: runId, status: "waiting" }],
205 } as unknown as OrchestrationV2ThreadProjection;
206 const layer = ProviderRuntimeRecovery.layer.pipe(
207 Layer.provide(
208 Layer.mergeAll(
209 Layer.mock(ProjectionStore.ProjectionStoreV2)({
210 getShellSnapshot: () =>
211 Effect.succeed({
212 schemaVersion: 2,
213 snapshotSequence: 0,
214 threads: [{ id: threadId }],
215 archivedThreads: [],
216 } as never),
217 getThreadProjection: () => Effect.succeed(projection),
218 }),
219 Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }),
220 IdAllocator.layer,
221 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
222 Layer.mock(EffectOutbox.EffectOutboxV2)({
223 listByCommandId: () =>
224 Effect.succeed([
225 {
226 request: { type: "checkpoint.capture", runId },
227 status: "running",
228 },
229 ] as never),
230 cancelUnsettled: () => Effect.succeed([]),
231 signalCancellations: () => Effect.void,
232 reconcileAfterProcessLoss: Effect.succeed({ requeued: 1, cancelled: 0 }),
233 }),
234 ),
235 ),
236 );
237​
238 return Effect.gen(function* () {
239 const summary =
240 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
241 assert.equal(summary.terminalizedRuns, 0);
242 assert.equal(summary.requeuedEffects, 1);
243 assert.equal(committed.mock.calls.length, 0);
244 }).pipe(Effect.provide(layer));
245});
246​
247it.effect("cancels a stale waiting run when no checkpoint capture can finish it", () => {
248 const threadId = ThreadId.make("thread_stale_waiting");
249 const runId = RunId.make("run_stale_waiting");
250 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
251 null;
252 const projection = {
253 thread: { id: threadId },
254 runtimeRequests: [],
255 providerSessions: [],
256 providerThreads: [],
257 providerTurns: [],
258 runs: [
259 {
260 id: runId,
261 status: "waiting",
262 providerInstanceId: ProviderInstanceId.make("codex"),
263 },
264 ],
265 attempts: [],
266 nodes: [],
267 subagents: [],
268 messages: [],
269 turnItems: [],
270 } as unknown as OrchestrationV2ThreadProjection;
271 const layer = ProviderRuntimeRecovery.layer.pipe(
272 Layer.provide(
273 Layer.mergeAll(
274 Layer.mock(ProjectionStore.ProjectionStoreV2)({
275 getShellSnapshot: () =>
276 Effect.succeed({
277 schemaVersion: 2,
278 snapshotSequence: 0,
279 threads: [{ id: threadId }],
280 archivedThreads: [],
281 } as never),
282 getThreadProjection: () => Effect.succeed(projection),
283 }),
284 Layer.mock(EventSink.EventSinkV2)({
285 commitCommand: (input) => {
286 committedInput = input;
287 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
288 },
289 }),
290 IdAllocator.layer,
291 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
292 Layer.mock(EffectOutbox.EffectOutboxV2)({
293 listByCommandId: () => Effect.succeed([]),
294 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
295 }),
296 ),
297 ),
298 );
299​
300 return Effect.gen(function* () {
301 const summary =
302 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
303 assert.equal(summary.terminalizedRuns, 1);
304 const runEvent = committedInput?.events.find((event) => event.type === "run.updated");
305 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled");
306 }).pipe(Effect.provide(layer));
307});
308​
309it.effect("cancels accepted queued work instead of replaying it after restart", () => {
310 const threadId = ThreadId.make("thread_queued_restart");
311 const runId = RunId.make("run_queued_restart");
312 const attemptId = RunAttemptId.make("attempt_queued_restart");
313 const rootNodeId = NodeId.make("node_queued_restart");
314 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
315 null;
316 const projection = {
317 thread: { id: threadId },
318 runtimeRequests: [],
319 providerSessions: [],
320 providerThreads: [],
321 providerTurns: [],
322 runs: [
323 {
324 id: runId,
325 status: "queued",
326 queuePosition: 1,
327 providerInstanceId: ProviderInstanceId.make("codex"),
328 },
329 ],
330 attempts: [
331 {
332 id: attemptId,
333 runId,
334 rootNodeId,
335 status: "pending",
336 },
337 ],
338 nodes: [
339 {
340 id: rootNodeId,
341 runId,
342 status: "pending",
343 },
344 ],
345 subagents: [],
346 messages: [],
347 turnItems: [],
348 } as unknown as OrchestrationV2ThreadProjection;
349 const layer = ProviderRuntimeRecovery.layer.pipe(
350 Layer.provide(
351 Layer.mergeAll(
352 Layer.mock(ProjectionStore.ProjectionStoreV2)({
353 getShellSnapshot: () =>
354 Effect.succeed({
355 schemaVersion: 2,
356 snapshotSequence: 0,
357 threads: [{ id: threadId }],
358 archivedThreads: [],
359 } as never),
360 getThreadProjection: () => Effect.succeed(projection),
361 }),
362 Layer.mock(EventSink.EventSinkV2)({
363 commitCommand: (input) => {
364 committedInput = input;
365 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
366 },
367 }),
368 IdAllocator.layer,
369 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
370 Layer.mock(EffectOutbox.EffectOutboxV2)({
371 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
372 }),
373 ),
374 ),
375 );
376​
377 return Effect.gen(function* () {
378 const summary =
379 yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
380 assert.equal(summary.terminalizedRuns, 1);
381 const command = committedInput;
382 assert.isNotNull(command);
383 if (command === null) return;
384 const runEvent = command.events.find((event) => event.type === "run.updated");
385 const attemptEvent = command.events.find((event) => event.type === "run-attempt.updated");
386 const nodeEvent = command.events.find((event) => event.type === "node.updated");
387 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled");
388 assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queuePosition : 1, null);
389 assert.equal(
390 attemptEvent?.type === "run-attempt.updated" ? attemptEvent.payload.status : null,
391 "cancelled",
392 );
393 assert.equal(nodeEvent?.type === "node.updated" ? nodeEvent.payload.status : null, "cancelled");
394 }).pipe(Effect.provide(layer));
395});
396​
397it.effect(
398 "cancels the complete in-flight subtree and stops its persisted session without reopening it",
399 () => {
400 const threadId = ThreadId.make("thread_recovery_cancel");
401 const runId = RunId.make("run_recovery_cancel");
402 const attemptId = RunAttemptId.make("attempt_recovery_cancel");
403 const rootNodeId = NodeId.make("node_recovery_cancel");
404 const providerThreadId = ProviderThreadId.make("provider_thread_recovery_cancel");
405 const providerTurnId = ProviderTurnId.make("provider_turn_recovery_cancel");
406 const providerSessionId = ProviderSessionId.make("provider_session_recovery_cancel");
407 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
408 null;
409 const projection = {
410 thread: { id: threadId },
411 runtimeRequests: [],
412 providerSessions: [
413 {
414 id: providerSessionId,
415 driver: ProviderDriverKind.make("codex"),
416 providerInstanceId: ProviderInstanceId.make("codex"),
417 status: "ready",
418 },
419 ],
420 providerThreads: [
421 {
422 id: providerThreadId,
423 driver: ProviderDriverKind.make("codex"),
424 providerInstanceId: ProviderInstanceId.make("codex"),
425 status: "active",
426 },
427 ],
428 providerTurns: [
429 {
430 id: providerTurnId,
431 runAttemptId: attemptId,
432 nodeId: rootNodeId,
433 status: "running",
434 },
435 ],
436 runs: [
437 {
438 id: runId,
439 status: "starting",
440 providerThreadId,
441 providerInstanceId: ProviderInstanceId.make("codex"),
442 },
443 ],
444 attempts: [
445 {
446 id: attemptId,
447 runId,
448 rootNodeId,
449 status: "running",
450 },
451 ],
452 nodes: [{ id: rootNodeId, runId, status: "running" }],
453 subagents: [],
454 messages: [{ id: MessageId.make("message_recovery_cancel"), runId, streaming: true }],
455 turnItems: [
456 {
457 id: TurnItemId.make("turn_item_recovery_cancel"),
458 runId,
459 nodeId: rootNodeId,
460 status: "running",
461 },
462 ],
463 } as unknown as OrchestrationV2ThreadProjection;
464 const layer = ProviderRuntimeRecovery.layer.pipe(
465 Layer.provide(
466 Layer.mergeAll(
467 Layer.mock(ProjectionStore.ProjectionStoreV2)({
468 getShellSnapshot: () =>
469 Effect.succeed({
470 schemaVersion: 2,
471 snapshotSequence: 0,
472 threads: [{ id: threadId }],
473 archivedThreads: [],
474 } as never),
475 getThreadProjection: () => Effect.succeed(projection),
476 }),
477 Layer.mock(EventSink.EventSinkV2)({
478 commitCommand: (input) => {
479 committedInput = input;
480 return Effect.succeed({ committed: true, cancelledEffectCount: 2 } as never);
481 },
482 }),
483 IdAllocator.layer,
484 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
485 Layer.mock(EffectOutbox.EffectOutboxV2)({
486 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
487 }),
488 ),
489 ),
490 );
491​
492 return Effect.gen(function* () {
493 const summary = yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)
494 .recover;
495 assert.equal(summary.terminalizedRuns, 1);
496 assert.equal(summary.stoppedSessions, 1);
497 assert.equal(summary.retiredEffects, 2);
498 assert.deepEqual(committedInput?.cancelUnsettledEffects?.effectTypes, [
499 "provider-turn.start",
500 "provider-turn.interrupt",
501 "provider-turn.steer",
502 "provider-turn.restart",
503 "runtime-request.respond",
504 ]);
505 const events = committedInput?.events ?? [];
506 assert.deepEqual(
507 events.map((event) => [
508 event.type,
509 "status" in event.payload ? event.payload.status : null,
510 ]),
511 [
512 ["run.updated", "cancelled"],
513 ["run-attempt.updated", "cancelled"],
514 ["node.updated", "cancelled"],
515 ["provider-turn.updated", "cancelled"],
516 ["message.updated", null],
517 ["turn-item.updated", "cancelled"],
518 ["provider-thread.updated", "idle"],
519 ["provider-session.updated", "stopped"],
520 ],
521 );
522 const messageEvent = events.find((event) => event.type === "message.updated");
523 assert.isFalse(messageEvent?.type === "message.updated" && messageEvent.payload.streaming);
524 }).pipe(Effect.provide(layer));
525 },
526);