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

agentScope.ts

333 lines13.0 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 setpriv = yield* Effect.cached(
181 resolve("setpriv", hostEnvironment).pipe(
182 Effect.map((resolved) => (resolved._tag === "Some" ? resolved.value : undefined)),
183 ),
184 );
185​
186 const readCgroupFile = (controlGroup: string, file: string) =>
187 fileSystem
188 .readFileString(path.join("/sys/fs/cgroup", controlGroup, file))
189 .pipe(Effect.orElseSucceed(() => ""));
190​
191 const readScope = (systemctl: string, unit: string) =>
192 Effect.gen(function* () {
193 const shown = yield* run(systemctl, [
194 "--user",
195 "show",
196 unit,
197 "--property=LoadState,ActiveState,Result,ControlGroup",
198 ]);
199 // A failed query says nothing about the scope; the caller keeps the unit.
200 if (shown._tag === "None" || shown.value.code !== 0) return undefined;
201 const values = parseKeyValues(shown.value.stdout);
202 const controlGroup = values.get("ControlGroup") ?? "";
203 const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";
204 const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
205 const populated = parseCgroupCounter(cgroupEvents, "populated");
206 return {
207 loadState: values.get("LoadState") ?? "",
208 activeState: values.get("ActiveState") ?? "",
209 result: values.get("Result") ?? "",
210 oomKills: parseCgroupCounter(memoryEvents, "oom_kill") ?? 0,
211 populated: populated === undefined ? undefined : populated === 1,
212 } satisfies ScopeState;
213 });
214​
215 const clearFailed = (systemctl: string, unit: string) =>
216 Effect.gen(function* () {
217 for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {
218 const state = yield* readScope(systemctl, unit);
219 if (state === undefined) return;
220 if (state.activeState === "failed") {
221 yield* run(systemctl, ["--user", "reset-failed", unit]);
222 return;
223 }
224 if (state.activeState !== "deactivating") return;
225 yield* Effect.sleep(CLEAR_FAILED_INTERVAL);
226 }
227 });
228​
229 // Failed scopes stay loaded so we can read their result. Clear them once
230 // systemd finishes stopping them.
231 const forget = (systemctl: string, unit: string) =>
232 clearFailed(systemctl, unit).pipe(Effect.forkIn(layerScope), Effect.asVoid);
233​
234 // Drops the oldest thread's scope once it has ended. A scope that still
235 // runs moves to the back, so its thread keeps its OOM answer and cleanup.
236 const evictOldest = (systemctl: string) =>
237 Effect.gen(function* () {
238 const oldest = scopeByThread.entries().next();
239 if (oldest.done === true) return;
240 const [threadId, tracked] = oldest.value;
241 const state = yield* readScope(systemctl, tracked.unit);
242 // A newer launch replaced it while we read, and forgets it itself.
243 if (scopeByThread.get(threadId) !== tracked) return;
244 scopeByThread.delete(threadId);
245 const status = state === undefined ? "running" : classifyScope(state);
246 if (status === "running" || status === "stopping") {
247 scopeByThread.set(threadId, tracked);
248 return;
249 }
250 yield* forget(systemctl, tracked.unit);
251 });
252​
253 // Records a thread's newest scope, or forgets the thread when `unit` is
254 // undefined. The replaced scope has its failed state cleared.
255 const track = (systemctl: string, threadId: string, unit: string | undefined) =>
256 Effect.gen(function* () {
257 const previous = scopeByThread.get(threadId);
258 scopeByThread.delete(threadId);
259 if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false });
260 if (previous !== undefined) yield* forget(systemctl, previous.unit);
261 if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);
262 });
263​
264 const oomKilled: AgentScopeShape["oomKilled"] = (threadId) =>
265 Effect.gen(function* () {
266 const tracked = scopeByThread.get(threadId);
267 if (tracked === undefined) return false;
268 if (tracked.oomKilled) return true;
269 const scope = yield* systemd;
270 if (scope === undefined) return false;
271 for (let attempt = 0; attempt < STOPPING_POLL_ATTEMPTS; attempt++) {
272 const state = yield* readScope(scope.systemctl, tracked.unit);
273 if (state === undefined) return false;
274 const status = classifyScope(state);
275 if (status === "running") return false;
276 if (status === "stopping") {
277 yield* Effect.sleep(STOPPING_POLL_INTERVAL);
278 continue;
279 }
280 yield* forget(scope.systemctl, tracked.unit);
281 if (status === "gone") return false;
282 yield* Effect.logWarning("Agent scope was killed: out of memory", {
283 threadId,
284 unit: tracked.unit,
285 });
286 tracked.oomKilled = true;
287 return true;
288 }
289 return false;
290 });
291​
292 const clear: AgentScopeShape["clear"] = (threadId) =>
293 Effect.gen(function* () {
294 if (!scopeByThread.has(threadId)) return;
295 const scope = yield* systemd;
296 if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);
297 });
298​
299 return {
300 wrap: Effect.fn("AgentScope.wrap")(function* ({ command, args, name, threadId, env }) {
301 const resolved = yield* resolve(command, env ?? hostEnvironment);
302 // Leave unresolved commands alone so the spawn reports the missing binary.
303 if (resolved._tag === "None") return { command, args };
304 const scope = yield* systemd;
305 const dieWithServer = yield* setpriv;
306 if (scope === undefined) {
307 return agentScopeCommand({ command: resolved.value, args, setpriv: dieWithServer });
308 }
309 const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`;
310 if (threadId !== undefined) yield* track(scope.systemctl, threadId, unit);
311 const systemdScope: AgentSystemdScope = {
312 systemdRun: scope.systemdRun,
313 systemctl: scope.systemctl,
314 runtimeDir: scope.runtimeDir,
315 slice: AGENT_SLICE,
316 unit,
317 // Without a thread nothing reads the result, so let systemd unload
318 // the unit even when it fails.
319 options: threadId === undefined ? [...scope.scopeOptions, "--collect"] : scope.scopeOptions,
320 };
321 return agentScopeCommand({
322 command: resolved.value,
323 args,
324 scope: systemdScope,
325 setpriv: dieWithServer,
326 });
327 }),
328 oomKilled,
329 clear,
330 } satisfies AgentScopeShape;
331});
332​
333export const layer = Layer.effect(AgentScope, make).pipe(Layer.provide(ProcessRunner.layer));