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

ProviderSessionReaper.ts

162 lines5.6 KB

1import * as Clock from "effect/Clock";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schedule from "effect/Schedule";
7​
8import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
9import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
10import {
11 ProviderSessionReaper,
12 type ProviderSessionReaperShape,
13} from "../Services/ProviderSessionReaper.ts";
14import { forkParked } from "../../serverActivation.ts";
15import { ProviderService } from "../Services/ProviderService.ts";
16​
17const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
18const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
19​
20export interface ProviderSessionReaperLiveOptions {
21 readonly inactivityThresholdMs?: number;
22 readonly sweepIntervalMs?: number;
24​
25const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
26 Effect.gen(function* () {
27 const providerService = yield* ProviderService;
28 const directory = yield* ProviderSessionDirectory;
29 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
30​
31 const inactivityThresholdMs = Math.max(
32 1,
33 options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,
34 );
35 const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
36​
37 const sweep = Effect.gen(function* () {
38 const bindings = yield* directory.listBindings();
39 const now = yield* Clock.currentTimeMillis;
40 let reapedCount = 0;
41​
42 for (const binding of bindings) {
43 if (binding.status === "stopped") {
44 continue;
45 }
46​
47 const lastSeenMs = Date.parse(binding.lastSeenAt);
48 if (Number.isNaN(lastSeenMs)) {
49 yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
50 threadId: binding.threadId,
51 provider: binding.provider,
52 lastSeenAt: binding.lastSeenAt,
53 });
54 continue;
55 }
56​
57 if (now - lastSeenMs < inactivityThresholdMs) {
58 continue;
59 }
60​
61 const thread = yield* projectionSnapshotQuery
62 .getThreadShellById(binding.threadId)
63 .pipe(Effect.map(Option.getOrUndefined));
64 // Ingestion updates this timestamp alongside activeTurnId when a turn
65 // settles. Long turns must get a full idle window after that transition,
66 // even though the binding was last touched when the turn was sent.
67 const lastActivityMs = Math.max(
68 lastSeenMs,
69 Date.parse(thread?.session?.updatedAt ?? binding.lastSeenAt),
70 );
71 const idleDurationMs = now - lastActivityMs;
72 if (idleDurationMs < inactivityThresholdMs) {
73 continue;
74 }
75 if (thread?.session?.activeTurnId != null) {
76 yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
77 threadId: binding.threadId,
78 activeTurnId: thread.session.activeTurnId,
79 idleDurationMs,
80 });
81 continue;
82 }
83​
84 // The turn can settle while background work runs on (subagent
85 // fleets, workflow runs, Monitor watch loops). Those live inside the
86 // provider process, so stopping the session would kill them silently,
87 // and nothing bumps lastSeenAt between turns.
88 if (thread?.backgroundLiveness != null) {
89 yield* Effect.logDebug("provider.session.reaper.skipped-background-work", {
90 threadId: binding.threadId,
91 backgroundLiveness: thread.backgroundLiveness,
92 idleDurationMs,
93 });
94 continue;
95 }
96​
97 const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
98 Effect.tap(() =>
99 Effect.logInfo("provider.session.reaped", {
100 threadId: binding.threadId,
101 provider: binding.provider,
102 idleDurationMs,
103 reason: "inactivity_threshold",
104 }),
105 ),
106 Effect.as(true),
107 Effect.catchCause((cause) =>
108 Effect.logWarning("provider.session.reaper.stop-failed", {
109 threadId: binding.threadId,
110 provider: binding.provider,
111 idleDurationMs,
112 cause,
113 }).pipe(Effect.as(false)),
114 ),
115 );
116​
117 if (reaped) {
118 reapedCount += 1;
119 }
120 }
121​
122 if (reapedCount > 0) {
123 yield* Effect.logInfo("provider.session.reaper.sweep-complete", {
124 reapedCount,
125 totalBindings: bindings.length,
126 });
127 }
128 });
129​
130 const start: ProviderSessionReaperShape["start"] = () =>
131 Effect.gen(function* () {
132 yield* forkParked(
133 sweep.pipe(
134 Effect.catch((error: unknown) =>
135 Effect.logWarning("provider.session.reaper.sweep-failed", {
136 error,
137 }),
138 ),
139 Effect.catchDefect((defect: unknown) =>
140 Effect.logWarning("provider.session.reaper.sweep-defect", {
141 defect,
142 }),
143 ),
144 Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
145 ),
146 );
147​
148 yield* Effect.logInfo("provider.session.reaper.started", {
149 inactivityThresholdMs,
150 sweepIntervalMs,
151 });
152 });
153​
154 return {
155 start,
156 } satisfies ProviderSessionReaperShape;
157 });
158​
159export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
160 Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
161​
162export const ProviderSessionReaperLive = makeProviderSessionReaperLive();