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

ProviderSessionReaper.ts

160 lines5.7 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 // Stopped rows stay for their resume cursors and far outnumber live
39 // ones, so the query skips them.
40 const bindings = yield* directory.listBindings({ excludeStopped: true });
41 const now = yield* Clock.currentTimeMillis;
42 let reapedCount = 0;
43​
44 for (const binding of bindings) {
45 const lastSeenMs = Date.parse(binding.lastSeenAt);
46 if (Number.isNaN(lastSeenMs)) {
47 yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
48 threadId: binding.threadId,
49 provider: binding.provider,
50 lastSeenAt: binding.lastSeenAt,
51 });
52 continue;
53 }
54​
55 if (now - lastSeenMs < inactivityThresholdMs) {
56 continue;
57 }
58​
59 const thread = yield* projectionSnapshotQuery
60 .getThreadShellById(binding.threadId)
61 .pipe(Effect.map(Option.getOrUndefined));
62 // Ingestion updates this timestamp alongside activeTurnId when a turn
63 // settles. Long turns must get a full idle window after that transition,
64 // even though the binding was last touched when the turn was sent.
65 const lastActivityMs = Math.max(
66 lastSeenMs,
67 Date.parse(thread?.session?.updatedAt ?? binding.lastSeenAt),
68 );
69 const idleDurationMs = now - lastActivityMs;
70 if (idleDurationMs < inactivityThresholdMs) {
71 continue;
72 }
73 if (thread?.session?.activeTurnId != null) {
74 yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
75 threadId: binding.threadId,
76 activeTurnId: thread.session.activeTurnId,
77 idleDurationMs,
78 });
79 continue;
80 }
81​
82 // The turn can settle while background work runs on (subagent
83 // fleets, workflow runs, Monitor watch loops). Those live inside the
84 // provider process, so stopping the session would kill them silently,
85 // and nothing bumps lastSeenAt between turns.
86 if (thread?.backgroundLiveness != null) {
87 yield* Effect.logDebug("provider.session.reaper.skipped-background-work", {
88 threadId: binding.threadId,
89 backgroundLiveness: thread.backgroundLiveness,
90 idleDurationMs,
91 });
92 continue;
93 }
94​
95 const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
96 Effect.tap(() =>
97 Effect.logInfo("provider.session.reaped", {
98 threadId: binding.threadId,
99 provider: binding.provider,
100 idleDurationMs,
101 reason: "inactivity_threshold",
102 }),
103 ),
104 Effect.as(true),
105 Effect.catchCause((cause) =>
106 Effect.logWarning("provider.session.reaper.stop-failed", {
107 threadId: binding.threadId,
108 provider: binding.provider,
109 idleDurationMs,
110 cause,
111 }).pipe(Effect.as(false)),
112 ),
113 );
114​
115 if (reaped) {
116 reapedCount += 1;
117 }
118 }
119​
120 if (reapedCount > 0) {
121 yield* Effect.logInfo("provider.session.reaper.sweep-complete", {
122 reapedCount,
123 liveBindings: bindings.length,
124 });
125 }
126 });
127​
128 const start: ProviderSessionReaperShape["start"] = () =>
129 Effect.gen(function* () {
130 yield* forkParked(
131 sweep.pipe(
132 Effect.catch((error: unknown) =>
133 Effect.logWarning("provider.session.reaper.sweep-failed", {
134 error,
135 }),
136 ),
137 Effect.catchDefect((defect: unknown) =>
138 Effect.logWarning("provider.session.reaper.sweep-defect", {
139 defect,
140 }),
141 ),
142 Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
143 ),
144 );
145​
146 yield* Effect.logInfo("provider.session.reaper.started", {
147 inactivityThresholdMs,
148 sweepIntervalMs,
149 });
150 });
151​
152 return {
153 start,
154 } satisfies ProviderSessionReaperShape;
155 });
156​
157export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
158 Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
159​
160export const ProviderSessionReaperLive = makeProviderSessionReaperLive();