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

ProviderSessionReaper.test.ts

592 lines19.2 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 ProjectId,
4 ThreadId,
5 TurnId,
6 ProviderDriverKind,
7 ProviderInstanceId,
8} from "@t3tools/contracts";
9import * as Clock from "effect/Clock";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Layer from "effect/Layer";
14import * as ManagedRuntime from "effect/ManagedRuntime";
15import * as Option from "effect/Option";
16import * as Scope from "effect/Scope";
17import * as Stream from "effect/Stream";
18import { afterEach, describe, expect, it, vi } from "vite-plus/test";
19​
20import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
21import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
22import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
23import { ProviderValidationError } from "../Errors.ts";
24import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
25import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
26import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
27import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
28​
29const defaultModelSelection = {
30 instanceId: ProviderInstanceId.make("codex"),
31 model: "gpt-5-codex",
32} as const;
33​
34async function waitFor(
35 predicate: () => boolean | Promise<boolean>,
36 timeoutMs = 2_000,
37): Promise<void> {
38 const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
39 const poll = async (): Promise<void> => {
40 if (await predicate()) {
41 return;
42 }
43 if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
44 throw new Error("Timed out waiting for expectation.");
45 }
46 await Effect.runPromise(Effect.yieldNow);
47 return poll();
48 };
49​
50 return poll();
52​
53const drainFibers = Effect.forEach(Array.from({ length: 10 }), () => Effect.yieldNow, {
54 discard: true,
55});
56​
57const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
58​
59function makeReadModel(
60 threads: ReadonlyArray<{
61 readonly id: ThreadId;
62 readonly session: {
63 readonly threadId: ThreadId;
64 readonly status: "starting" | "running" | "ready" | "interrupted" | "stopped" | "error";
65 readonly providerName: "codex" | "claudeAgent";
66 readonly runtimeMode: "approval-required" | "full-access" | "auto-accept-edits";
67 readonly activeTurnId: TurnId | null;
68 readonly lastError: string | null;
69 readonly updatedAt: string;
70 } | null;
71 }>,
72) {
73 const now = "2026-01-01T00:00:00.000Z";
74 const projectId = ProjectId.make("project-provider-session-reaper");
75​
76 return {
77 snapshotSequence: 0,
78 updatedAt: now,
79 projects: [
80 {
81 id: projectId,
82 title: "Provider Reaper Project",
83 workspaceRoot: "/tmp/provider-reaper-project",
84 defaultModelSelection,
85 scripts: [],
86 createdAt: now,
87 updatedAt: now,
88 deletedAt: null,
89 },
90 ],
91 threads: threads.map((thread) => ({
92 id: thread.id,
93 projectId,
94 title: `Thread ${thread.id}`,
95 modelSelection: defaultModelSelection,
96 interactionMode: "default" as const,
97 runtimeMode: "full-access" as const,
98 branch: null,
99 worktreePath: null,
100 createdAt: now,
101 updatedAt: now,
102 archivedAt: null,
103 settledOverride: null,
104 settledAt: null,
105 latestUserMessageAt: null,
106 hasPendingApprovals: false,
107 hasPendingUserInput: false,
108 hasActionableProposedPlan: false,
109 latestTurn: null,
110 messages: [],
111 session: thread.session,
112 activities: [],
113 proposedPlans: [],
114 checkpoints: [],
115 deletedAt: null,
116 })),
117 };
119​
120describe("ProviderSessionReaper", () => {
121 let runtime: ManagedRuntime.ManagedRuntime<
122 ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository,
123 unknown
124 > | null = null;
125 let scope: Scope.Closeable | null = null;
126​
127 afterEach(async () => {
128 if (scope) {
129 await Effect.runPromise(Scope.close(scope, Exit.void));
130 }
131 scope = null;
132 if (runtime) {
133 await runtime.dispose();
134 }
135 runtime = null;
136 });
137​
138 async function createHarness(input: {
139 readonly readModel: ReturnType<typeof makeReadModel>;
140 readonly stopSessionImplementation?: (input: {
141 readonly threadId: ThreadId;
142 }) => ReturnType<ProviderServiceShape["stopSession"]>;
143 }) {
144 const stoppedThreadIds = new Set<ThreadId>();
145 const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
146 (request) =>
147 (input.stopSessionImplementation
148 ? input.stopSessionImplementation(request)
149 : Effect.sync(() => {
150 stoppedThreadIds.add(request.threadId);
151 })) as ReturnType<ProviderServiceShape["stopSession"]>,
152 );
153​
154 const providerService: ProviderServiceShape = {
155 startSession: () => unsupported(),
156 sendTurn: () => unsupported(),
157 interruptTurn: () => unsupported(),
158 respondToRequest: () => unsupported(),
159 respondToUserInput: () => unsupported(),
160 stopSession,
161 listSessions: () => Effect.succeed([]),
162 getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
163 getInstanceInfo: (instanceId) => {
164 const driverKind = ProviderDriverKind.make(String(instanceId));
165 return Effect.succeed({
166 instanceId,
167 driverKind,
168 displayName: undefined,
169 enabled: true,
170 continuationIdentity: {
171 driverKind,
172 continuationKey: `${driverKind}:instance:${instanceId}`,
173 },
174 });
175 },
176 rollbackConversation: () => unsupported(),
177 streamEvents: Stream.empty,
178 };
179​
180 const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
181 Layer.provide(SqlitePersistenceMemory),
182 );
183 const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
184 Layer.provide(runtimeRepositoryLayer),
185 );
186 const layer = makeProviderSessionReaperLive({
187 inactivityThresholdMs: 1_000,
188 sweepIntervalMs: 60_000,
189 }).pipe(
190 Layer.provideMerge(providerSessionDirectoryLayer),
191 Layer.provideMerge(runtimeRepositoryLayer),
192 Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
193 Layer.provideMerge(
194 Layer.succeed(ProjectionSnapshotQuery, {
195 getCommandReadModel: () => Effect.die("unused"),
196 getSnapshot: () => Effect.die("unused"),
197 getShellSnapshot: () => Effect.die("unused"),
198 getArchivedShellSnapshot: () => Effect.die("unused"),
199 getSnapshotSequence: () =>
200 Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
201 getCounts: () => Effect.die("unused"),
202 getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
203 getProjectShellById: () => Effect.die("unused"),
204 getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
205 getThreadCheckpointContext: () => Effect.die("unused"),
206 getFullThreadDiffContext: () => Effect.die("unused"),
207 getThreadShellById: (threadId) =>
208 Effect.succeed(
209 input.readModel.threads.find((thread) => thread.id === threadId)
210 ? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!)
211 : Option.none(),
212 ),
213 getThreadDetailById: () => Effect.die("unused"),
214 getThreadDetailSnapshot: () => Effect.die("unused"),
215 searchThreads: () => Effect.succeed({ matches: [] }),
216 }),
217 ),
218 Layer.provideMerge(NodeServices.layer),
219 );
220​
221 runtime = ManagedRuntime.make(layer);
222 return { stopSession, stoppedThreadIds };
223 }
224​
225 it("reaps stale persisted sessions without active turns", async () => {
226 const threadId = ThreadId.make("thread-reaper-stale");
227 const now = "2026-01-01T00:00:00.000Z";
228 const harness = await createHarness({
229 readModel: makeReadModel([
230 {
231 id: threadId,
232 session: {
233 threadId,
234 status: "ready",
235 providerName: "claudeAgent",
236 runtimeMode: "full-access",
237 activeTurnId: null,
238 lastError: null,
239 updatedAt: now,
240 },
241 },
242 ]),
243 });
244 const repository = await runtime!.runPromise(
245 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
246 );
247​
248 await runtime!.runPromise(
249 repository.upsert({
250 threadId,
251 providerName: "claudeAgent",
252 providerInstanceId: null,
253 adapterKey: "claudeAgent",
254 runtimeMode: "full-access",
255 status: "running",
256 lastSeenAt: "2026-04-14T00:00:00.000Z",
257 resumeCursor: {
258 opaque: "resume-stale",
259 },
260 runtimePayload: null,
261 }),
262 );
263​
264 const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
265 scope = await Effect.runPromise(Scope.make("sequential"));
266 await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
267​
268 await waitFor(() => harness.stopSession.mock.calls.length === 1);
269​
270 expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId });
271 expect(harness.stoppedThreadIds.has(threadId)).toBe(true);
272 });
273​
274 it("skips stale sessions when the thread still has an active turn", async () => {
275 const threadId = ThreadId.make("thread-reaper-active-turn");
276 const turnId = TurnId.make("turn-reaper-active");
277 const now = "2026-01-01T00:00:00.000Z";
278 const harness = await createHarness({
279 readModel: makeReadModel([
280 {
281 id: threadId,
282 session: {
283 threadId,
284 status: "running",
285 providerName: "claudeAgent",
286 runtimeMode: "full-access",
287 activeTurnId: turnId,
288 lastError: null,
289 updatedAt: now,
290 },
291 },
292 ]),
293 });
294 const repository = await runtime!.runPromise(
295 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
296 );
297​
298 await runtime!.runPromise(
299 repository.upsert({
300 threadId,
301 providerName: "claudeAgent",
302 providerInstanceId: null,
303 adapterKey: "claudeAgent",
304 runtimeMode: "full-access",
305 status: "running",
306 lastSeenAt: "2026-04-14T00:00:00.000Z",
307 resumeCursor: {
308 opaque: "resume-active-turn",
309 },
310 runtimePayload: null,
311 }),
312 );
313​
314 const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
315 scope = await Effect.runPromise(Scope.make("sequential"));
316 await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
317 await Effect.runPromise(drainFibers);
318​
319 expect(harness.stopSession).not.toHaveBeenCalled();
320 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
321 expect(Option.isSome(remaining)).toBe(true);
322 });
323​
324 it("does not reap sessions that are still within the inactivity threshold", async () => {
325 const threadId = ThreadId.make("thread-reaper-fresh");
326 const now = DateTime.formatIso(await Effect.runPromise(DateTime.now));
327 const harness = await createHarness({
328 readModel: makeReadModel([
329 {
330 id: threadId,
331 session: {
332 threadId,
333 status: "ready",
334 providerName: "claudeAgent",
335 runtimeMode: "full-access",
336 activeTurnId: null,
337 lastError: null,
338 updatedAt: now,
339 },
340 },
341 ]),
342 });
343 const repository = await runtime!.runPromise(
344 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
345 );
346​
347 await runtime!.runPromise(
348 repository.upsert({
349 threadId,
350 providerName: "claudeAgent",
351 providerInstanceId: null,
352 adapterKey: "claudeAgent",
353 runtimeMode: "full-access",
354 status: "running",
355 lastSeenAt: now,
356 resumeCursor: {
357 opaque: "resume-fresh",
358 },
359 runtimePayload: null,
360 }),
361 );
362​
363 const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
364 scope = await Effect.runPromise(Scope.make("sequential"));
365 await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
366 await Effect.runPromise(drainFibers);
367​
368 expect(harness.stopSession).not.toHaveBeenCalled();
369 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
370 expect(Option.isSome(remaining)).toBe(true);
371 });
372​
373 it("skips persisted sessions that are already marked stopped", async () => {
374 const threadId = ThreadId.make("thread-reaper-stopped");
375 const now = "2026-01-01T00:00:00.000Z";
376 const harness = await createHarness({
377 readModel: makeReadModel([
378 {
379 id: threadId,
380 session: {
381 threadId,
382 status: "stopped",
383 providerName: "claudeAgent",
384 runtimeMode: "full-access",
385 activeTurnId: null,
386 lastError: null,
387 updatedAt: now,
388 },
389 },
390 ]),
391 });
392 const repository = await runtime!.runPromise(
393 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
394 );
395​
396 await runtime!.runPromise(
397 repository.upsert({
398 threadId,
399 providerName: "claudeAgent",
400 providerInstanceId: null,
401 adapterKey: "claudeAgent",
402 runtimeMode: "full-access",
403 status: "stopped",
404 lastSeenAt: "2026-04-14T00:00:00.000Z",
405 resumeCursor: {
406 opaque: "resume-stopped",
407 },
408 runtimePayload: null,
409 }),
410 );
411​
412 const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
413 scope = await Effect.runPromise(Scope.make("sequential"));
414 await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
415 await Effect.runPromise(drainFibers);
416​
417 expect(harness.stopSession).not.toHaveBeenCalled();
418 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
419 expect(Option.isSome(remaining)).toBe(true);
420 });
421​
422 it("continues reaping other sessions when one stop attempt fails", async () => {
423 const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
424 const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
425 const now = "2026-01-01T00:00:00.000Z";
426 const harness = await createHarness({
427 readModel: makeReadModel([
428 {
429 id: failedThreadId,
430 session: {
431 threadId: failedThreadId,
432 status: "ready",
433 providerName: "claudeAgent",
434 runtimeMode: "full-access",
435 activeTurnId: null,
436 lastError: null,
437 updatedAt: now,
438 },
439 },
440 {
441 id: reapedThreadId,
442 session: {
443 threadId: reapedThreadId,
444 status: "ready",
445 providerName: "codex",
446 runtimeMode: "full-access",
447 activeTurnId: null,
448 lastError: null,
449 updatedAt: now,
450 },
451 },
452 ]),
453 stopSessionImplementation: (request) =>
454 request.threadId === failedThreadId
455 ? Effect.fail(
456 new ProviderValidationError({
457 operation: "ProviderSessionReaper.test",
458 issue: "simulated stop failure",
459 }),
460 )
461 : Effect.void,
462 });
463 const repository = await runtime!.runPromise(
464 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
465 );
466​
467 await runtime!.runPromise(
468 repository.upsert({
469 threadId: failedThreadId,
470 providerName: "claudeAgent",
471 providerInstanceId: null,
472 adapterKey: "claudeAgent",
473 runtimeMode: "full-access",
474 status: "running",
475 lastSeenAt: "2026-04-14T00:00:00.000Z",
476 resumeCursor: {
477 opaque: "resume-failure",
478 },
479 runtimePayload: null,
480 }),
481 );
482 await runtime!.runPromise(
483 repository.upsert({
484 threadId: reapedThreadId,
485 providerName: "codex",
486 providerInstanceId: null,
487 adapterKey: "codex",
488 runtimeMode: "full-access",
489 status: "running",
490 lastSeenAt: "2026-04-14T00:01:00.000Z",
491 resumeCursor: {
492 opaque: "resume-success",
493 },
494 runtimePayload: null,
495 }),
496 );
497​
498 const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
499 scope = await Effect.runPromise(Scope.make("sequential"));
500 await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
501​
502 await waitFor(() => harness.stopSession.mock.calls.length === 2);
503​
504 expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
505 failedThreadId,
506 reapedThreadId,
507 ]);
508 });
509​
510 it("continues reaping other sessions when one stop attempt defects", async () => {
511 const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
512 const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
513 const now = "2026-01-01T00:00:00.000Z";
514 const harness = await createHarness({
515 readModel: makeReadModel([
516 {
517 id: defectThreadId,
518 session: {
519 threadId: defectThreadId,
520 status: "ready",
521 providerName: "claudeAgent",
522 runtimeMode: "full-access",
523 activeTurnId: null,
524 lastError: null,
525 updatedAt: now,
526 },
527 },
528 {
529 id: reapedThreadId,
530 session: {
531 threadId: reapedThreadId,
532 status: "ready",
533 providerName: "codex",
534 runtimeMode: "full-access",
535 activeTurnId: null,
536 lastError: null,
537 updatedAt: now,
538 },
539 },
540 ]),
541 stopSessionImplementation: (request) =>
542 request.threadId === defectThreadId
543 ? Effect.die(new Error("simulated stop defect"))
544 : Effect.void,
545 });
546 const repository = await runtime!.runPromise(
547 Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
548 );
549​
550 await runtime!.runPromise(
551 repository.upsert({
552 threadId: defectThreadId,
553 providerName: "claudeAgent",
554 providerInstanceId: null,
555 adapterKey: "claudeAgent",
556 runtimeMode: "full-access",
557 status: "running",
558 lastSeenAt: "2026-04-14T00:00:00.000Z",
559 resumeCursor: {
560 opaque: "resume-defect",
561 },
562 runtimePayload: null,
563 }),
564 );
565 await runtime!.runPromise(
566 repository.upsert({
567 threadId: reapedThreadId,
568 providerName: "codex",
569 providerInstanceId: null,
570 adapterKey: "codex",
571 runtimeMode: "full-access",
572 status: "running",
573 lastSeenAt: "2026-04-14T00:01:00.000Z",
574 resumeCursor: {
575 opaque: "resume-after-defect",
576 },
577 runtimePayload: null,
578 }),
579 );
580​
581 const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
582 scope = await Effect.runPromise(Scope.make("sequential"));
583 await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
584​
585 await waitFor(() => harness.stopSession.mock.calls.length === 2);
586​
587 expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
588 defectThreadId,
589 reapedThreadId,
590 ]);
591 });
592});