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

ProviderContinuationService.test.ts

584 lines21.6 KB

1import { assert, describe, it } from "@effect/vitest";
2import {
3 MessageId,
4 ProjectId,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 ProviderThreadId,
8 RunId,
9 ThreadId,
10 type OrchestrationV2ThreadProjection,
11 type OrchestrationV2Notification,
12} from "@t3tools/contracts";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Queue from "effect/Queue";
19import * as Ref from "effect/Ref";
20import * as Semaphore from "effect/Semaphore";
21import * as TestClock from "effect/testing/TestClock";
22​
23import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
24import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
25import * as ProviderContinuationService from "./ProviderContinuationService.ts";
26import * as ThreadManagementService from "./ThreadManagementService.ts";
27​
28const threadId = ThreadId.make("thread-provider-continuation");
29const providerThreadId = ProviderThreadId.make("provider-thread-continuation");
30const driver = ProviderDriverKind.make("continuation-test");
31const parentRunId = RunId.make("run-provider-continuation-parent");
32const delegatedMessageId = MessageId.make("message-provider-continuation-delegated");
33const projection = {
34 thread: { archivedAt: null, deletedAt: null },
35 messages: [],
36} as unknown as OrchestrationV2ThreadProjection;
37​
38const request = (
39 dispatchIfCurrent?: ProviderContinuationRequests.ProviderContinuationRequest["dispatchIfCurrent"],
40 detail: string | null = null,
41): ProviderContinuationRequests.ProviderContinuationRequest => ({
42 threadId,
43 providerThreadId,
44 driver,
45 detail,
46 ...(dispatchIfCurrent === undefined ? {} : { dispatchIfCurrent }),
47});
48​
49const delegatedProjection = (disposition: "open" | "stopped" | "disposed" = "open") =>
50 ({
51 ...projection,
52 runs: [
53 {
54 id: parentRunId,
55 delegatedCompletion: {
56 disposition,
57 nextGeneration: 2,
58 delivery: {
59 generation: 1,
60 messageId: delegatedMessageId,
61 taskIds: ["node-provider-continuation-first", "node-provider-continuation-second"],
62 },
63 },
64 },
65 ],
66 }) as unknown as OrchestrationV2ThreadProjection;
67​
68const makeGuard = Effect.fnUntraced(function* (completed?: Deferred.Deferred<void>) {
69 const generation = yield* Ref.make(0);
70 const permit = yield* Semaphore.make(1);
71 const capture = Effect.gen(function* () {
72 const captured = yield* Ref.updateAndGet(generation, (value) => value + 1);
73 return <A, E, R>(effect: Effect.Effect<A, E, R>) =>
74 permit
75 .withPermit(
76 Effect.gen(function* () {
77 if ((yield* Ref.get(generation)) !== captured) return Option.none();
78 return Option.some(yield* effect);
79 }),
80 )
81 .pipe(
82 completed === undefined
83 ? (effect) => effect
84 : Effect.ensuring(Deferred.succeed(completed, undefined)),
85 );
86 });
87 return {
88 capture,
89 invalidate: permit.withPermit(Ref.update(generation, (value) => value + 1)),
90 };
91});
92​
93function layerTest(input: {
94 readonly dispatched: Queue.Queue<unknown>;
95 readonly getThreadRecords: () => Effect.Effect<OrchestrationV2ThreadProjection>;
96}) {
97 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
98 getThreadRecords: input.getThreadRecords,
99 dispatch: (command) => Queue.offer(input.dispatched, command).pipe(Effect.as({} as never)),
100 });
101 const layerWorker = ProviderContinuationService.layer.pipe(
102 Layer.provide(
103 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
104 ),
105 );
106 return Layer.merge(ProviderContinuationRequests.layer, layerWorker);
108​
109describe("ProviderContinuationService", () => {
110 it.effect("recovers an unaccepted persisted steer using the same delivery identity", () =>
111 Effect.gen(function* () {
112 const dispatched = yield* Queue.unbounded<unknown>();
113 const original = delegatedProjection();
114 const interruptedRunId = RunId.make("interrupted-mailbox-run");
115 const recovered = {
116 ...original,
117 runs: [
118 ...original.runs,
119 {
120 id: interruptedRunId,
121 status: "interrupted",
122 userMessageId: MessageId.make("original-user-input"),
123 },
124 ],
125 messages: [
126 {
127 id: delegatedMessageId,
128 runId: interruptedRunId,
129 delegatedCompletion: { parentRunId, generation: 1, taskIds: [] },
130 },
131 ],
132 } as unknown as OrchestrationV2ThreadProjection;
133 yield* Effect.gen(function* () {
134 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
135 yield* requests.offer({
136 threadId,
137 providerThreadId,
138 driver,
139 detail: null,
140 delivery: "message_text",
141 delegatedCompletion: { parentRunId, generation: 1, messageId: delegatedMessageId },
142 });
143 const command = (yield* Queue.take(dispatched)) as {
144 messageId: MessageId;
145 delegatedCompletion: { generation: number; taskIds: readonly string[] };
146 };
147 assert.equal(command.messageId, delegatedMessageId);
148 assert.equal(command.delegatedCompletion.generation, 1);
149 assert.equal(command.delegatedCompletion.taskIds.length, 2);
150 }).pipe(
151 Effect.provide(
152 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(recovered) }),
153 ),
154 Effect.scoped,
155 );
156 }),
157 );
158​
159 it.effect("delivers a message_text wake as a real prompt, not a buffered wake", () => {
160 return Effect.gen(function* () {
161 const dispatched = yield* Queue.unbounded<unknown>();
162 yield* Effect.gen(function* () {
163 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
164 yield* requests.offer({
165 threadId,
166 providerThreadId,
167 driver,
168 detail: "Delegated task completed.",
169 notification: {
170 source: { kind: "monitor" },
171 outcome: "updated",
172 summary: "Monitor updated",
173 },
174 delivery: "message_text",
175 });
176 const command = (yield* Queue.take(dispatched)) as {
177 readonly creationSource: string;
178 readonly text: string;
179 readonly notification: OrchestrationV2Notification;
180 };
181 assert.notEqual(command.creationSource, "provider");
182 assert.equal(command.creationSource, "server");
183 assert.equal(command.text, "Delegated task completed.");
184 assert.deepEqual(command.notification, {
185 source: { kind: "monitor" },
186 outcome: "updated",
187 summary: "Monitor updated",
188 });
189 }).pipe(
190 Effect.provide(
191 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
192 ),
193 Effect.scoped,
194 );
195 });
196 });
197​
198 it.effect("dispatches a current delegated completion as one server-owned queued message", () => {
199 return Effect.gen(function* () {
200 const dispatched = yield* Queue.unbounded<unknown>();
201 yield* Effect.gen(function* () {
202 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
203 yield* requests.offer({
204 threadId,
205 providerThreadId,
206 driver,
207 detail: null,
208 delivery: "message_text",
209 delegatedCompletion: {
210 parentRunId,
211 generation: 1,
212 messageId: delegatedMessageId,
213 },
214 });
215 const command = (yield* Queue.take(dispatched)) as {
216 readonly createdBy: string;
217 readonly creationSource: string;
218 readonly delegatedCompletion: {
219 readonly generation: number;
220 readonly parentRunId: RunId;
221 readonly taskIds: ReadonlyArray<string>;
222 };
223 readonly dispatchMode: { readonly type: string };
224 readonly messageId: MessageId;
225 readonly text: string;
226 };
227 assert.equal(command.createdBy, "agent");
228 assert.equal(command.creationSource, "server");
229 assert.deepEqual(command.dispatchMode, { type: "queue_after_active" });
230 assert.equal(command.messageId, delegatedMessageId);
231 assert.equal(command.delegatedCompletion.parentRunId, parentRunId);
232 assert.equal(command.delegatedCompletion.generation, 1);
233 assert.deepEqual(command.delegatedCompletion.taskIds, [
234 "node-provider-continuation-first",
235 "node-provider-continuation-second",
236 ]);
237 assert.include(command.text, "task_status");
238 }).pipe(
239 Effect.provide(
240 layerTest({
241 dispatched,
242 getThreadRecords: () => Effect.succeed(delegatedProjection()),
243 }),
244 ),
245 Effect.scoped,
246 );
247 });
248 });
249​
250 it.effect(
251 "a project-disabled instance refuses a delegated-completion wake exactly once, acknowledges it, and never retries",
252 () => {
253 return Effect.gen(function* () {
254 const attempts = yield* Ref.make(0);
255 const cleared = yield* Ref.make(false);
256 const acknowledged = yield* Queue.unbounded<unknown>();
257 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
258 getThreadRecords: () => Effect.succeed(delegatedProjection()),
259 dispatch: (command) => {
260 if ((command as { type: string }).type === "message.dispatch") {
261 return Ref.update(attempts, (count) => count + 1).pipe(
262 Effect.andThen(
263 Effect.fail(
264 new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
265 projectId: ProjectId.make("project-provider-continuation-disabled"),
266 instanceId: ProviderInstanceId.make(
267 "instance-provider-continuation-disabled",
268 ),
269 }) as never,
270 ),
271 ),
272 );
273 }
274 return Queue.offer(acknowledged, command).pipe(Effect.as({} as never));
275 },
276 });
277 const layerWorker = ProviderContinuationService.layer.pipe(
278 Layer.provide(
279 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
280 ),
281 );
282​
283 yield* Effect.gen(function* () {
284 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
285 yield* requests.offer({
286 threadId,
287 providerThreadId,
288 driver,
289 detail: null,
290 delivery: "message_text",
291 clearIfCurrent: () => Ref.set(cleared, true),
292 delegatedCompletion: {
293 parentRunId,
294 generation: 1,
295 messageId: delegatedMessageId,
296 },
297 });
298 yield* Effect.yieldNow;
299 assert.equal(yield* Ref.get(attempts), 1);
300 assert.isTrue(yield* Ref.get(cleared));
301​
302 const acknowledgements = (yield* Queue.takeAll(acknowledged)) as ReadonlyArray<{
303 type: string;
304 taskId: string;
305 observedByRunId: string | null;
306 }>;
307 assert.deepEqual(
308 acknowledgements.map((command) => command.taskId),
309 ["node-provider-continuation-first", "node-provider-continuation-second"],
310 );
311 for (const command of acknowledgements) {
312 assert.equal(command.type, "delegated_task.completion-delivery.acknowledge");
313 assert.isNull(command.observedByRunId);
314 }
315​
316 yield* TestClock.adjust("1 hour");
317 yield* Effect.yieldNow;
318 assert.equal(yield* Ref.get(attempts), 1);
319 assert.equal(yield* Queue.size(acknowledged), 0);
320 }).pipe(
321 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
322 Effect.scoped,
323 );
324 });
325 },
326 );
327​
328 it.effect(
329 "clears the adapter's sticky continuation flag when a non-delegated wake is refused",
330 () => {
331 return Effect.gen(function* () {
332 const requested = yield* Ref.make(true);
333 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
334 getThreadRecords: () => Effect.succeed(projection),
335 dispatch: () =>
336 Effect.fail(
337 new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
338 projectId: ProjectId.make("project-provider-continuation-disabled"),
339 instanceId: ProviderInstanceId.make("instance-provider-continuation-disabled"),
340 }) as never,
341 ),
342 });
343 const layerWorker = ProviderContinuationService.layer.pipe(
344 Layer.provide(
345 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
346 ),
347 );
348​
349 // ACP clears its sticky continuation flag on raw dispatch failure; pre-recovery would prevent that cleanup.
350 const dispatchIfCurrent = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
351 Effect.gen(function* () {
352 const exit = yield* Effect.exit(effect);
353 if (Exit.isFailure(exit)) {
354 yield* Ref.set(requested, false);
355 return yield* Effect.failCause(exit.cause);
356 }
357 return Option.some(exit.value);
358 });
359​
360 yield* Effect.gen(function* () {
361 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
362 yield* requests.offer(request(dispatchIfCurrent));
363 yield* Effect.yieldNow;
364 yield* Effect.yieldNow;
365 assert.isFalse(
366 yield* Ref.get(requested),
367 "a disabled instance must still clear the adapter's sticky offer flag",
368 );
369 }).pipe(
370 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
371 Effect.scoped,
372 );
373 });
374 },
375 );
376​
377 it.effect(
378 "clears a sticky continuation offer for an adapter whose dispatchIfCurrent does not self-clear on failure",
379 () => {
380 return Effect.gen(function* () {
381 const wakeHeld = yield* Ref.make(true);
382 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
383 getThreadRecords: () => Effect.succeed(projection),
384 dispatch: () =>
385 Effect.fail(
386 new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
387 projectId: ProjectId.make("project-provider-continuation-disabled"),
388 instanceId: ProviderInstanceId.make("instance-provider-continuation-disabled"),
389 }) as never,
390 ),
391 });
392 const layerWorker = ProviderContinuationService.layer.pipe(
393 Layer.provide(
394 Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads),
395 ),
396 );
397​
398 // Muse forwards dispatch failures unchanged; clearIfCurrent must release its sticky wake flag.
399 const dispatchIfCurrent = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
400 Effect.asSome(effect);
401​
402 yield* Effect.gen(function* () {
403 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
404 yield* requests.offer({
405 ...request(dispatchIfCurrent),
406 clearIfCurrent: () => Ref.set(wakeHeld, false),
407 });
408 yield* Effect.yieldNow;
409 yield* Effect.yieldNow;
410 assert.isFalse(
411 yield* Ref.get(wakeHeld),
412 "a disabled instance must clear the offer via the explicit callback " +
413 "when the adapter itself does not clear on dispatch failure",
414 );
415 }).pipe(
416 Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)),
417 Effect.scoped,
418 );
419 });
420 },
421 );
422​
423 it.effect(
424 "drops stopped and disposed delegated completions instead of reviving them after recovery",
425 () => {
426 return Effect.gen(function* () {
427 for (const disposition of ["stopped", "disposed"] as const) {
428 const dispatched = yield* Queue.unbounded<unknown>();
429 yield* Effect.gen(function* () {
430 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
431 yield* requests.offer({
432 threadId,
433 providerThreadId,
434 driver,
435 detail: null,
436 delivery: "message_text",
437 delegatedCompletion: {
438 parentRunId,
439 generation: 1,
440 messageId: delegatedMessageId,
441 },
442 });
443 yield* Effect.yieldNow;
444 yield* Effect.yieldNow;
445 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
446 }).pipe(
447 Effect.provide(
448 layerTest({
449 dispatched,
450 getThreadRecords: () => Effect.succeed(delegatedProjection(disposition)),
451 }),
452 ),
453 Effect.scoped,
454 );
455 }
456 });
457 },
458 );
459​
460 it.effect("does not redispatch a persisted delegated completion message during recovery", () => {
461 return Effect.gen(function* () {
462 const dispatched = yield* Queue.unbounded<unknown>();
463 yield* Effect.gen(function* () {
464 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
465 yield* requests.offer({
466 threadId,
467 providerThreadId,
468 driver,
469 detail: null,
470 delivery: "message_text",
471 delegatedCompletion: {
472 parentRunId,
473 generation: 1,
474 messageId: delegatedMessageId,
475 },
476 });
477 yield* Effect.yieldNow;
478 yield* Effect.yieldNow;
479 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
480 }).pipe(
481 Effect.provide(
482 layerTest({
483 dispatched,
484 getThreadRecords: () =>
485 Effect.succeed({
486 ...delegatedProjection(),
487 messages: [{ id: delegatedMessageId }],
488 } as unknown as OrchestrationV2ThreadProjection),
489 }),
490 ),
491 Effect.scoped,
492 );
493 });
494 });
495​
496 it.effect("dispatches a current request exactly once", () => {
497 return Effect.gen(function* () {
498 const dispatched = yield* Queue.unbounded<unknown>();
499 yield* Effect.gen(function* () {
500 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
501 yield* requests.offer(request());
502 yield* Queue.take(dispatched);
503 yield* Effect.yieldNow;
504 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
505 }).pipe(
506 Effect.provide(
507 layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
508 ),
509 Effect.scoped,
510 );
511 });
512 });
513​
514 it.effect("drops a request invalidated while projection is blocked", () => {
515 return Effect.gen(function* () {
516 const dispatched = yield* Queue.unbounded<unknown>();
517 const projectionEntered = yield* Deferred.make<void>();
518 const releaseProjection = yield* Deferred.make<void>();
519 const guardCompleted = yield* Deferred.make<void>();
520 yield* Effect.gen(function* () {
521 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
522 const guard = yield* makeGuard(guardCompleted);
523 const dispatchIfCurrent = yield* guard.capture;
524 yield* requests.offer(request(dispatchIfCurrent));
525 yield* Deferred.await(projectionEntered);
526 yield* guard.invalidate;
527 yield* Deferred.succeed(releaseProjection, undefined);
528 yield* Deferred.await(guardCompleted);
529 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
530 }).pipe(
531 Effect.provide(
532 layerTest({
533 dispatched,
534 getThreadRecords: () =>
535 Deferred.succeed(projectionEntered, undefined).pipe(
536 Effect.andThen(Deferred.await(releaseProjection)),
537 Effect.as(projection),
538 ),
539 }),
540 ),
541 Effect.scoped,
542 );
543 });
544 });
545​
546 it.effect("does not revive an old request when a later generation is current", () => {
547 return Effect.gen(function* () {
548 const dispatched = yield* Queue.unbounded<unknown>();
549 const firstProjectionEntered = yield* Deferred.make<void>();
550 const releaseFirstProjection = yield* Deferred.make<void>();
551 let projectionCalls = 0;
552 yield* Effect.gen(function* () {
553 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
554 const guard = yield* makeGuard();
555 const first = yield* guard.capture;
556 yield* requests.offer(request(first, "A"));
557 yield* Deferred.await(firstProjectionEntered);
558 const second = yield* guard.capture;
559 yield* requests.offer(request(second, "B"));
560 yield* Deferred.succeed(releaseFirstProjection, undefined);
561 const command = yield* Queue.take(dispatched);
562 assert.equal((command as { readonly text?: unknown }).text, "B");
563 yield* Effect.yieldNow;
564 assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
565 }).pipe(
566 Effect.provide(
567 layerTest({
568 dispatched,
569 getThreadRecords: () => {
570 projectionCalls += 1;
571 return projectionCalls === 1
572 ? Deferred.succeed(firstProjectionEntered, undefined).pipe(
573 Effect.andThen(Deferred.await(releaseFirstProjection)),
574 Effect.as(projection),
575 )
576 : Effect.succeed(projection);
577 },
578 }),
579 ),
580 Effect.scoped,
581 );
582 });
583 });
584});