|
| 1 | +/** |
| 2 | + * Fork: agent slots (issue 724) for upstream's provider continuation, through upstream's real |
| 3 | + * continuation worker over a gate with a set number of free slots. |
| 4 | + */ |
| 5 | +import { assert, describe, it } from "@effect/vitest"; |
| 6 | +import { |
| 7 | + type OrchestrationV2ServerCommand, |
| 8 | + type OrchestrationV2ThreadProjection, |
| 9 | + ProviderDriverKind, |
| 10 | + ProviderInstanceId, |
| 11 | + ProviderThreadId, |
| 12 | + MessageId, |
| 13 | + RunId, |
| 14 | + ThreadId, |
| 15 | +} from "@t3tools/contracts"; |
| 16 | +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 17 | +import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; |
| 18 | +import * as Effect from "effect/Effect"; |
| 19 | +import * as FileSystem from "effect/FileSystem"; |
| 20 | +import * as Layer from "effect/Layer"; |
| 21 | +import * as Logger from "effect/Logger"; |
| 22 | +import * as Option from "effect/Option"; |
| 23 | +import * as Path from "effect/Path"; |
| 24 | +import * as Queue from "effect/Queue"; |
| 25 | +import * as TestClock from "effect/testing/TestClock"; |
| 26 | +import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 27 | + |
| 28 | +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; |
| 29 | +import * as ProviderContinuationService from "../orchestration-v2/ProviderContinuationService.ts"; |
| 30 | +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; |
| 31 | +import * as SlotGate from "../slots/SlotGate.ts"; |
| 32 | +import * as WaitWorker from "../waits/WaitWorker.ts"; |
| 33 | +import * as ContinuationSlot from "./continuationSlot.ts"; |
| 34 | + |
| 35 | +const INSTANCE = ProviderInstanceId.make("claudeAgent"); |
| 36 | +const [A, B] = ["thread:continuation-a", "thread:continuation-b"].map((id) => |
| 37 | + ThreadId.make(id), |
| 38 | +) as [ThreadId, ThreadId]; |
| 39 | + |
| 40 | +const request = ( |
| 41 | + threadId: ThreadId, |
| 42 | + patch: Partial<ProviderContinuationRequests.ProviderContinuationRequest> = {}, |
| 43 | +): ProviderContinuationRequests.ProviderContinuationRequest => ({ |
| 44 | + threadId, |
| 45 | + providerThreadId: ProviderThreadId.make(`provider:${threadId}`), |
| 46 | + driver: ProviderDriverKind.make("claudeAgent"), |
| 47 | + detail: null, |
| 48 | + ...patch, |
| 49 | +}); |
| 50 | + |
| 51 | +interface World { |
| 52 | + /** Free slots; each start the gate allows takes one. */ |
| 53 | + free: number; |
| 54 | + /** Threads the gate refuses whatever is free. */ |
| 55 | + full: Set<ThreadId>; |
| 56 | + asks: Array<SlotGate.SlotAcquireInput>; |
| 57 | + /** Threads gone (`null` shell), and whether a shell read fails. */ |
| 58 | + gone: Set<ThreadId>; |
| 59 | + unreadable: boolean; |
| 60 | + logs: Array<string>; |
| 61 | +} |
| 62 | + |
| 63 | +const newWorld = (free: number): World => ({ |
| 64 | + free, |
| 65 | + full: new Set(), |
| 66 | + asks: [], |
| 67 | + gone: new Set(), |
| 68 | + unreadable: false, |
| 69 | + logs: [], |
| 70 | +}); |
| 71 | + |
| 72 | +const gateOf = (world: World) => |
| 73 | + Layer.mock(SlotGate.SlotGate)({ |
| 74 | + acquire: (input) => |
| 75 | + Effect.sync((): SlotGate.SlotAcquire => { |
| 76 | + world.asks.push(input); |
| 77 | + if (world.free === 0 || world.full.has(input.callerThreadId!)) |
| 78 | + return { |
| 79 | + type: "refuse", |
| 80 | + message: "full", |
| 81 | + refusal: { type: "unread", problem: "timeout" }, |
| 82 | + }; |
| 83 | + world.free -= 1; |
| 84 | + return { type: "allow", token: world.asks.length }; |
| 85 | + }), |
| 86 | + started: () => Effect.void, |
| 87 | + release: () => Effect.void, |
| 88 | + }); |
| 89 | + |
| 90 | +const projection = { |
| 91 | + thread: { archivedAt: null, deletedAt: null }, |
| 92 | + messages: [], |
| 93 | + runs: [], |
| 94 | +} as unknown as OrchestrationV2ThreadProjection; |
| 95 | + |
| 96 | +/** Upstream's queue and worker, the worker reading it through the gate; `null`: no gate. */ |
| 97 | +const server = ( |
| 98 | + world: World, |
| 99 | + dispatched: Queue.Queue<OrchestrationV2ServerCommand>, |
| 100 | + gate: "gate" | null = "gate", |
| 101 | +) => { |
| 102 | + const threads = Layer.mock(ThreadManagement.ThreadManagementService)({ |
| 103 | + getThreadShell: (threadId) => |
| 104 | + world.unreadable |
| 105 | + ? Effect.fail(new Orchestrator.OrchestratorProjectionError({ threadId })) |
| 106 | + : Effect.succeed( |
| 107 | + world.gone.has(threadId) |
| 108 | + ? null |
| 109 | + : ({ |
| 110 | + id: threadId, |
| 111 | + deletedAt: null, |
| 112 | + archivedAt: null, |
| 113 | + modelSelection: { instanceId: INSTANCE }, |
| 114 | + } as never), |
| 115 | + ), |
| 116 | + getThreadRecords: (threadId) => |
| 117 | + Effect.succeed( |
| 118 | + world.gone.has(threadId) |
| 119 | + ? { ...projection, thread: { archivedAt: "2026-11-21T00:00:00.000Z", deletedAt: null } } |
| 120 | + : projection, |
| 121 | + ) as never, |
| 122 | + dispatch: (command) => |
| 123 | + Queue.offer(dispatched, command).pipe(Effect.as({ sequence: 1, storedEvents: [] })), |
| 124 | + }); |
| 125 | + const worker = ProviderContinuationService.layer.pipe( |
| 126 | + Layer.provide(ContinuationSlot.layerOver), |
| 127 | + Layer.provide( |
| 128 | + Layer.mergeAll( |
| 129 | + IdAllocator.layer, |
| 130 | + ProviderContinuationRequests.layer, |
| 131 | + threads, |
| 132 | + ...(gate === null ? [] : [gateOf(world)]), |
| 133 | + ), |
| 134 | + ), |
| 135 | + ); |
| 136 | + return Layer.merge(ProviderContinuationRequests.layer, worker).pipe( |
| 137 | + Layer.provideMerge( |
| 138 | + Logger.layer( |
| 139 | + [ |
| 140 | + Logger.make(({ message, logLevel }) => { |
| 141 | + if (logLevel === "Info") world.logs.push(JSON.stringify(message)); |
| 142 | + }), |
| 143 | + ], |
| 144 | + { mergeWithExisting: false }, |
| 145 | + ), |
| 146 | + ), |
| 147 | + ); |
| 148 | +}; |
| 149 | + |
| 150 | +const offer = (value: ProviderContinuationRequests.ProviderContinuationRequest) => |
| 151 | + ProviderContinuationRequests.ProviderContinuationRequests.pipe( |
| 152 | + Effect.flatMap((requests) => requests.offer(value)), |
| 153 | + ); |
| 154 | + |
| 155 | +const waitLogs = (world: World) => |
| 156 | + world.logs.filter((log) => log.includes("provider continuation waits for an agent slot")); |
| 157 | + |
| 158 | +describe("provider continuations take an agent slot", () => { |
| 159 | + it.effect( |
| 160 | + "full: waits outside the adapter's lock, asked every 5 s, logged once, sent once with a slot", |
| 161 | + () => |
| 162 | + Effect.gen(function* () { |
| 163 | + const world = newWorld(0); |
| 164 | + const dispatched = yield* Queue.unbounded<OrchestrationV2ServerCommand>(); |
| 165 | + const locked: Array<ThreadId> = []; |
| 166 | + yield* Effect.gen(function* () { |
| 167 | + yield* offer( |
| 168 | + request(A, { |
| 169 | + // The adapter's own lock is taken here: never while the request waits. |
| 170 | + dispatchIfCurrent: (effect) => |
| 171 | + Effect.sync(() => locked.push(A)).pipe(Effect.andThen(Effect.asSome(effect))), |
| 172 | + }), |
| 173 | + ); |
| 174 | + yield* TestClock.adjust("0 seconds"); |
| 175 | + yield* TestClock.adjust("1 minute"); |
| 176 | + assert.strictEqual(yield* Queue.size(dispatched), 0); |
| 177 | + assert.deepStrictEqual(locked, []); |
| 178 | + assert.isAtLeast(world.asks.length, 12); |
| 179 | + assert.lengthOf(waitLogs(world), 1); |
| 180 | + assert.deepStrictEqual(world.asks[0], { |
| 181 | + callerThreadId: A, |
| 182 | + targetInstanceId: INSTANCE, |
| 183 | + intoThreadId: A, |
| 184 | + keepsHeld: true, |
| 185 | + }); |
| 186 | + world.free = 1; |
| 187 | + yield* TestClock.adjust("5 seconds"); |
| 188 | + const sent = yield* Queue.take(dispatched); |
| 189 | + assert.strictEqual(sent.type === "message.dispatch" && sent.threadId, A); |
| 190 | + assert.deepStrictEqual(locked, [A]); |
| 191 | + yield* TestClock.adjust("1 minute"); |
| 192 | + assert.strictEqual(yield* Queue.size(dispatched), 0); |
| 193 | + }).pipe(Effect.provide(server(world, dispatched)), Effect.scoped); |
| 194 | + }), |
| 195 | + ); |
| 196 | + |
| 197 | + it.effect("a waiting thread holds up no other thread's continuation", () => |
| 198 | + Effect.gen(function* () { |
| 199 | + const world = newWorld(5); |
| 200 | + world.full.add(A); |
| 201 | + const dispatched = yield* Queue.unbounded<OrchestrationV2ServerCommand>(); |
| 202 | + yield* Effect.gen(function* () { |
| 203 | + yield* offer(request(A)); |
| 204 | + yield* offer(request(B)); |
| 205 | + const sent = yield* Queue.take(dispatched); |
| 206 | + assert.strictEqual(sent.type === "message.dispatch" && sent.threadId, B); |
| 207 | + yield* TestClock.adjust("30 seconds"); |
| 208 | + assert.strictEqual(yield* Queue.size(dispatched), 0); |
| 209 | + world.full.delete(A); |
| 210 | + yield* TestClock.adjust("5 seconds"); |
| 211 | + const late = yield* Queue.take(dispatched); |
| 212 | + assert.strictEqual(late.type === "message.dispatch" && late.threadId, A); |
| 213 | + }).pipe(Effect.provide(server(world, dispatched)), Effect.scoped); |
| 214 | + }), |
| 215 | + ); |
| 216 | + |
| 217 | + it.effect("a thread that cannot be read waits, then is sent once", () => |
| 218 | + Effect.gen(function* () { |
| 219 | + const world = newWorld(5); |
| 220 | + world.unreadable = true; |
| 221 | + const dispatched = yield* Queue.unbounded<OrchestrationV2ServerCommand>(); |
| 222 | + yield* Effect.gen(function* () { |
| 223 | + yield* offer(request(A)); |
| 224 | + yield* TestClock.adjust("30 seconds"); |
| 225 | + assert.strictEqual(yield* Queue.size(dispatched), 0); |
| 226 | + assert.deepStrictEqual(world.asks, []); |
| 227 | + world.unreadable = false; |
| 228 | + yield* TestClock.adjust("5 seconds"); |
| 229 | + yield* Queue.take(dispatched); |
| 230 | + yield* TestClock.adjust("1 minute"); |
| 231 | + assert.strictEqual(yield* Queue.size(dispatched), 0); |
| 232 | + }).pipe(Effect.provide(server(world, dispatched)), Effect.scoped); |
| 233 | + }), |
| 234 | + ); |
| 235 | + |
| 236 | + it.effect("a gone thread is upstream's at once: no slot asked, the adapter's latch cleared", () => |
| 237 | + Effect.gen(function* () { |
| 238 | + const world = newWorld(0); |
| 239 | + world.gone.add(A); |
| 240 | + const dispatched = yield* Queue.unbounded<OrchestrationV2ServerCommand>(); |
| 241 | + const cleared: Array<ThreadId> = []; |
| 242 | + yield* Effect.gen(function* () { |
| 243 | + yield* offer(request(A, { clearIfCurrent: () => Effect.sync(() => cleared.push(A)) })); |
| 244 | + yield* TestClock.adjust("0 seconds"); |
| 245 | + assert.deepStrictEqual(cleared, [A]); |
| 246 | + assert.deepStrictEqual(world.asks, []); |
| 247 | + assert.strictEqual(yield* Queue.size(dispatched), 0); |
| 248 | + }).pipe(Effect.provide(server(world, dispatched)), Effect.scoped); |
| 249 | + }), |
| 250 | + ); |
| 251 | + |
| 252 | + it.effect("a delegated result is upstream's at once: no slot asked, even with none free", () => |
| 253 | + Effect.gen(function* () { |
| 254 | + const world = newWorld(0); |
| 255 | + const inner = |
| 256 | + yield* Queue.unbounded<ProviderContinuationRequests.ProviderContinuationRequest>(); |
| 257 | + const gated = ContinuationSlot.gateContinuations( |
| 258 | + { |
| 259 | + offer: (value) => Queue.offer(inner, value).pipe(Effect.asVoid), |
| 260 | + take: Queue.take(inner), |
| 261 | + }, |
| 262 | + Option.some(yield* SlotGate.SlotGate.pipe(Effect.provide(gateOf(world)))), |
| 263 | + () => Effect.succeed({ instanceId: INSTANCE }), |
| 264 | + yield* Effect.scope, |
| 265 | + ); |
| 266 | + const delegated = request(A, { |
| 267 | + delegatedCompletion: { |
| 268 | + parentRunId: RunId.make("run:continuation-a"), |
| 269 | + generation: 1, |
| 270 | + messageId: MessageId.make("message:continuation-a"), |
| 271 | + }, |
| 272 | + }); |
| 273 | + yield* gated.offer(delegated); |
| 274 | + const taken: Array<ProviderContinuationRequests.ProviderContinuationRequest> = []; |
| 275 | + yield* gated.take.pipe( |
| 276 | + Effect.tap((value) => Effect.sync(() => taken.push(value))), |
| 277 | + Effect.forkScoped, |
| 278 | + ); |
| 279 | + yield* TestClock.adjust("1 minute"); |
| 280 | + assert.deepStrictEqual(taken, [delegated]); |
| 281 | + assert.deepStrictEqual(world.asks, []); |
| 282 | + }).pipe(Effect.scoped), |
| 283 | + ); |
| 284 | + |
| 285 | + it.effect("stopped while one waits: nothing is sent later, half-way or twice", () => |
| 286 | + Effect.gen(function* () { |
| 287 | + const world = newWorld(0); |
| 288 | + const dispatched = yield* Queue.unbounded<OrchestrationV2ServerCommand>(); |
| 289 | + yield* Effect.gen(function* () { |
| 290 | + yield* offer(request(A)); |
| 291 | + yield* TestClock.adjust("12 seconds"); |
| 292 | + }).pipe(Effect.provide(server(world, dispatched)), Effect.scoped); |
| 293 | + const asked = world.asks.length; |
| 294 | + world.free = 5; |
| 295 | + yield* TestClock.adjust("1 minute"); |
| 296 | + assert.strictEqual(yield* Queue.size(dispatched), 0); |
| 297 | + assert.strictEqual(world.asks.length, asked); |
| 298 | + }), |
| 299 | + ); |
| 300 | + |
| 301 | + it.effect("no gate: upstream's own queue, sent at once", () => |
| 302 | + Effect.gen(function* () { |
| 303 | + const world = newWorld(0); |
| 304 | + const dispatched = yield* Queue.unbounded<OrchestrationV2ServerCommand>(); |
| 305 | + yield* Effect.gen(function* () { |
| 306 | + yield* offer(request(A)); |
| 307 | + yield* Queue.take(dispatched); |
| 308 | + }).pipe(Effect.provide(server(world, dispatched, null)), Effect.scoped); |
| 309 | + const inner = { offer: () => Effect.void, take: Effect.never }; |
| 310 | + assert.strictEqual( |
| 311 | + ContinuationSlot.gateContinuations( |
| 312 | + inner, |
| 313 | + Option.none(), |
| 314 | + () => Effect.succeed(null), |
| 315 | + null as never, |
| 316 | + ), |
| 317 | + inner, |
| 318 | + ); |
| 319 | + }), |
| 320 | + ); |
| 321 | + |
| 322 | + it.effect("runtime wiring: upstream's continuation worker reads the gated queue", () => |
| 323 | + Effect.gen(function* () { |
| 324 | + assert.strictEqual(WaitWorker.continuationSlot, ContinuationSlot.layer); |
| 325 | + const path = yield* Path.Path; |
| 326 | + const fileSystem = yield* FileSystem.FileSystem; |
| 327 | + const runtime = yield* fileSystem.readFileString( |
| 328 | + yield* path.fromFileUrl(new URL("../orchestration-v2/runtimeLayer.ts", import.meta.url)), |
| 329 | + ); |
| 330 | + const start = runtime.indexOf( |
| 331 | + "const layerProviderContinuationWorkerProvided = ProviderContinuationService.layer.pipe(\n", |
| 332 | + ); |
| 333 | + assert.isAbove(start, -1); |
| 334 | + const firstInPipe = runtime.slice( |
| 335 | + start, |
| 336 | + runtime.indexOf("\n", runtime.indexOf("\n", start) + 1), |
| 337 | + ); |
| 338 | + assert.include(firstInPipe, "Layer.provide(WaitWorker.continuationSlot)"); |
| 339 | + assert.lengthOf(runtime.split("ProviderContinuationService.layer"), 2); |
| 340 | + // Over the server's one gate. |
| 341 | + const own = yield* fileSystem.readFileString( |
| 342 | + yield* path.fromFileUrl(new URL("./continuationSlot.ts", import.meta.url)), |
| 343 | + ); |
| 344 | + assert.include(own, "export const layer = layerOver.pipe(Layer.provide(SlotGate.layer));"); |
| 345 | + // The wait worker keeps its gate, now given in its own file rather than runtimeLayer.ts. |
| 346 | + const worker = yield* fileSystem.readFileString( |
| 347 | + yield* path.fromFileUrl(new URL("../waits/WaitWorker.ts", import.meta.url)), |
| 348 | + ); |
| 349 | + assert.include(worker, "Layer.provide(SlotGate.layer),"); |
| 350 | + }).pipe(Effect.provide(NodeServices.layer)), |
| 351 | + ); |
| 352 | +}); |