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

agentScope.ts

318 lines12.6 KB

1// @effect-diagnostics nodeBuiltinImport:off -- unit names and RAM size come from the host.
2import * as NodeCrypto from "node:crypto";
3import * as NodeOS from "node:os";
4​
5import {
6 AgentScope,
7 agentScopeCommand,
8 type AgentScopeShape,
9 type AgentSystemdScope,
10} from "@t3tools/shared/AgentScope";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import { resolveCommandPath } from "@t3tools/shared/shell";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Path from "effect/Path";
17​
18import * as ProcessRunner from "../processRunner.ts";
19​
20/**
21 * Agents and terminals share this slice. It sits in app.slice next to the
22 * server's own unit, so the server's CPUWeight and IOWeight compete with the
23 * agents directly.
24 */
25const AGENT_SLICE = "app-t3code-agents.slice";
26​
27const GiB = 1024 ** 3;
28​
29/**
30 * Memory limits for the agents slice. Agents together leave about 6 GB free
31 * before they are throttled and 4 GB before the kernel kills one, so the
32 * server, sshd, and tailscaled keep working. Small machines still give agents
33 * at least half of RAM before throttling and three quarters before a kill.
34 */
35export function agentSliceMemoryLimits(totalBytes: number) {
36 return {
37 high: Math.max(totalBytes - 6 * GiB, Math.floor(totalBytes / 2)),
38 max: Math.max(totalBytes - 4 * GiB, Math.floor(totalBytes * 0.75)),
39 };
41​
42export interface ScopeState {
43 readonly loadState: string;
44 readonly activeState: string;
45 readonly result: string;
46 /** `oom_kill` from the scope's memory.events, while its cgroup exists. */
47 readonly oomKills: number;
48 /** `populated` from the scope's cgroup.events, while its cgroup exists. */
49 readonly populated: boolean | undefined;
51​
52/**
53 * Reads one scope as the server sees it right after the agent process exits.
54 * Our pipe can close before systemd handles the kill, so a scope that is
55 * still stopping, is empty, or already counted an OOM kill is "stopping":
56 * systemd records `Result=oom-kill` for it in a moment.
57 */
58export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "running" | "stopping" {
59 if (state.result === "oom-kill") return "oom-killed";
60 if (
61 state.loadState !== "loaded" ||
62 state.activeState === "inactive" ||
63 state.activeState === "failed"
64 ) {
65 return "gone";
66 }
67 if (state.activeState === "deactivating" || state.oomKills > 0 || state.populated === false) {
68 return "stopping";
69 }
70 return "running";
72​
73function parseKeyValues(text: string): Map<string, string> {
74 const values = new Map<string, string>();
75 for (const line of text.split("\n")) {
76 const index = line.indexOf("=");
77 if (index > 0) values.set(line.slice(0, index), line.slice(index + 1).trim());
78 }
79 return values;
81​
82function parseCgroupCounter(text: string, key: string): number | undefined {
83 const match = new RegExp(`^${key} (\\d+)$`, "m").exec(text);
84 return match === null ? undefined : Number(match[1]);
86​
87const STOPPING_POLL_INTERVAL = "100 millis";
88const STOPPING_POLL_ATTEMPTS = 20;
89// A stopping scope can wait out TimeoutStopSec (90 s by default) for a stuck process.
90const CLEAR_FAILED_INTERVAL = "1 second";
91const CLEAR_FAILED_ATTEMPTS = 120;
92const MAX_TRACKED_THREADS = 500;
93​
94export const make = Effect.gen(function* () {
95 const platform = yield* HostProcess.Platform;
96 if (platform !== "linux") return AgentScope.defaultValue();
97​
98 const runner = yield* ProcessRunner.ProcessRunner;
99 const fileSystem = yield* FileSystem.FileSystem;
100 const path = yield* Path.Path;
101 const hostEnvironment = yield* HostProcess.Environment;
102 const layerScope = yield* Effect.scope;
103​
104 const resolve = (command: string, env: NodeJS.ProcessEnv) =>
105 resolveCommandPath(command, { env }).pipe(
106 Effect.provideService(FileSystem.FileSystem, fileSystem),
107 Effect.provideService(Path.Path, path),
108 Effect.provideService(HostProcess.Platform, platform),
109 Effect.option,
110 );
111​
112 const run = (command: string, args: ReadonlyArray<string>) =>
113 runner.run({ command, args, timeout: "5 seconds" }).pipe(Effect.option);
114​
115 // Runs once, on the first agent launch. It proves this process can reach a
116 // systemd user manager, creates the agents slice, and sets its limits.
117 const systemd = yield* Effect.cached(
118 Effect.gen(function* () {
119 const runtimeDir = hostEnvironment.XDG_RUNTIME_DIR;
120 if (runtimeDir === undefined || runtimeDir.length === 0) return undefined;
121 const systemdRun = yield* resolve("systemd-run", hostEnvironment);
122 const systemctl = yield* resolve("systemctl", hostEnvironment);
123 if (systemdRun._tag === "None" || systemctl._tag === "None") return undefined;
124 const probe = (options: ReadonlyArray<string>) =>
125 run(systemdRun.value, [
126 "--user",
127 "--scope",
128 "--quiet",
129 "--collect",
130 `--slice=${AGENT_SLICE}`,
131 ...options,
132 "--",
133 "true",
134 ]).pipe(Effect.map((result) => result._tag === "Some" && result.value.code === 0));
135 // Stop the whole scope when the kernel kills one of its processes, and
136 // record the result as oom-kill. Scopes take OOMPolicy from systemd 253;
137 // older user managers still get plain scopes, without the OOM label.
138 const oomOptions = ["--property=OOMPolicy=stop"];
139 const scopeOptions = (yield* probe(oomOptions))
140 ? oomOptions
141 : (yield* probe([]))
142 ? []
143 : undefined;
144 if (scopeOptions === undefined) {
145 yield* Effect.logInfo("Agent scopes are off: no systemd user manager");
146 return undefined;
147 }
148 const limits = agentSliceMemoryLimits(NodeOS.totalmem());
149 const limited = yield* run(systemctl.value, [
150 "--user",
151 "set-property",
152 "--runtime",
153 AGENT_SLICE,
154 `MemoryHigh=${limits.high}`,
155 `MemoryMax=${limits.max}`,
156 ]);
157 if (limited._tag === "None" || limited.value.code !== 0) {
158 yield* Effect.logWarning("Could not set memory limits on the agents slice", {
159 stderr: limited._tag === "Some" ? limited.value.stderr.trim() : undefined,
160 });
161 }
162 yield* Effect.logInfo("Agent scopes are on", {
163 slice: AGENT_SLICE,
164 ...limits,
165 oomPolicy: scopeOptions.length > 0,
166 });
167 return {
168 systemdRun: systemdRun.value,
169 systemctl: systemctl.value,
170 runtimeDir,
171 scopeOptions,
172 };
173 }),
174 );
175​
176 // The newest scope per thread, oldest thread first. A thread runs one agent
177 // at a time, so only its latest scope can explain a failure.
178 const scopeByThread = new Map<string, { unit: string; oomKilled: boolean }>();
179​
180 const readCgroupFile = (controlGroup: string, file: string) =>
181 fileSystem
182 .readFileString(path.join("/sys/fs/cgroup", controlGroup, file))
183 .pipe(Effect.orElseSucceed(() => ""));
184​
185 const readScope = (systemctl: string, unit: string) =>
186 Effect.gen(function* () {
187 const shown = yield* run(systemctl, [
188 "--user",
189 "show",
190 unit,
191 "--property=LoadState,ActiveState,Result,ControlGroup",
192 ]);
193 // A failed query says nothing about the scope; the caller keeps the unit.
194 if (shown._tag === "None" || shown.value.code !== 0) return undefined;
195 const values = parseKeyValues(shown.value.stdout);
196 const controlGroup = values.get("ControlGroup") ?? "";
197 const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";
198 const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
199 const populated = parseCgroupCounter(cgroupEvents, "populated");
200 return {
201 loadState: values.get("LoadState") ?? "",
202 activeState: values.get("ActiveState") ?? "",
203 result: values.get("Result") ?? "",
204 oomKills: parseCgroupCounter(memoryEvents, "oom_kill") ?? 0,
205 populated: populated === undefined ? undefined : populated === 1,
206 } satisfies ScopeState;
207 });
208​
209 const clearFailed = (systemctl: string, unit: string) =>
210 Effect.gen(function* () {
211 for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {
212 const state = yield* readScope(systemctl, unit);
213 if (state === undefined) return;
214 if (state.activeState === "failed") {
215 yield* run(systemctl, ["--user", "reset-failed", unit]);
216 return;
217 }
218 if (state.activeState !== "deactivating") return;
219 yield* Effect.sleep(CLEAR_FAILED_INTERVAL);
220 }
221 });
222​
223 // Failed scopes stay loaded so we can read their result. Clear them once
224 // systemd finishes stopping them.
225 const forget = (systemctl: string, unit: string) =>
226 clearFailed(systemctl, unit).pipe(Effect.forkIn(layerScope), Effect.asVoid);
227​
228 // Drops the oldest thread's scope once it has ended. A scope that still
229 // runs moves to the back, so its thread keeps its OOM answer and cleanup.
230 const evictOldest = (systemctl: string) =>
231 Effect.gen(function* () {
232 const oldest = scopeByThread.entries().next();
233 if (oldest.done === true) return;
234 const [threadId, tracked] = oldest.value;
235 const state = yield* readScope(systemctl, tracked.unit);
236 // A newer launch replaced it while we read, and forgets it itself.
237 if (scopeByThread.get(threadId) !== tracked) return;
238 scopeByThread.delete(threadId);
239 const status = state === undefined ? "running" : classifyScope(state);
240 if (status === "running" || status === "stopping") {
241 scopeByThread.set(threadId, tracked);
242 return;
243 }
244 yield* forget(systemctl, tracked.unit);
245 });
246​
247 // Records a thread's newest scope, or forgets the thread when `unit` is
248 // undefined. The replaced scope has its failed state cleared.
249 const track = (systemctl: string, threadId: string, unit: string | undefined) =>
250 Effect.gen(function* () {
251 const previous = scopeByThread.get(threadId);
252 scopeByThread.delete(threadId);
253 if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false });
254 if (previous !== undefined) yield* forget(systemctl, previous.unit);
255 if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);
256 });
257​
258 const oomKilled: AgentScopeShape["oomKilled"] = (threadId) =>
259 Effect.gen(function* () {
260 const tracked = scopeByThread.get(threadId);
261 if (tracked === undefined) return false;
262 if (tracked.oomKilled) return true;
263 const scope = yield* systemd;
264 if (scope === undefined) return false;
265 for (let attempt = 0; attempt < STOPPING_POLL_ATTEMPTS; attempt++) {
266 const state = yield* readScope(scope.systemctl, tracked.unit);
267 if (state === undefined) return false;
268 const status = classifyScope(state);
269 if (status === "running") return false;
270 if (status === "stopping") {
271 yield* Effect.sleep(STOPPING_POLL_INTERVAL);
272 continue;
273 }
274 yield* forget(scope.systemctl, tracked.unit);
275 if (status === "gone") return false;
276 yield* Effect.logWarning("Agent scope was killed: out of memory", {
277 threadId,
278 unit: tracked.unit,
279 });
280 tracked.oomKilled = true;
281 return true;
282 }
283 return false;
284 });
285​
286 const clear: AgentScopeShape["clear"] = (threadId) =>
287 Effect.gen(function* () {
288 if (!scopeByThread.has(threadId)) return;
289 const scope = yield* systemd;
290 if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);
291 });
292​
293 return {
294 wrap: Effect.fn("AgentScope.wrap")(function* ({ command, args, name, threadId, env }) {
295 const resolved = yield* resolve(command, env ?? hostEnvironment);
296 // Leave unresolved commands alone so the spawn reports the missing binary.
297 if (resolved._tag === "None") return { command, args };
298 const scope = yield* systemd;
299 if (scope === undefined) return agentScopeCommand({ command: resolved.value, args });
300 const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`;
301 if (threadId !== undefined) yield* track(scope.systemctl, threadId, unit);
302 const systemdScope: AgentSystemdScope = {
303 systemdRun: scope.systemdRun,
304 runtimeDir: scope.runtimeDir,
305 slice: AGENT_SLICE,
306 unit,
307 // Without a thread nothing reads the result, so let systemd unload
308 // the unit even when it fails.
309 options: threadId === undefined ? [...scope.scopeOptions, "--collect"] : scope.scopeOptions,
310 };
311 return agentScopeCommand({ command: resolved.value, args, scope: systemdScope });
312 }),
313 oomKilled,
314 clear,
315 } satisfies AgentScopeShape;
316});
317​
318export const layer = Layer.effect(AgentScope, make).pipe(Layer.provide(ProcessRunner.layer));