Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- fake systemd binaries live in a temp dir.
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { assert, describe, expect, it } from "@effect/vitest";
8import { AgentScope } from "@t3tools/shared/AgentScope";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Logger from "effect/Logger";
14import { ChildProcess, ChildProcessSpawner } from "effect/process";
15
16import * as ServerConfig from "../config.ts";
17import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
18import * as ProcessRunner from "../processRunner.ts";
19import { classifyScope, make, ownedAgentSlice, type ScopeState } from "./agentScope.ts";
20
21const running: ScopeState = {
22 loadState: "loaded",
23 activeState: "active",
24 result: "success",
25 oomKills: 0,
26 populated: true,
27};
28
29describe("classifyScope", () => {
30 it("reports an OOM kill only once systemd records it", () => {
31 expect(classifyScope({ ...running, activeState: "failed", result: "oom-kill" })).toBe(
32 "oom-killed",
33 );
34 expect(classifyScope({ ...running, oomKills: 1 })).toBe("stopping");
35 expect(classifyScope({ ...running, populated: false })).toBe("stopping");
36 expect(classifyScope({ ...running, activeState: "deactivating" })).toBe("stopping");
37 });
38});
39
40interface FakeUnit {
41 activeState: string;
42 result: string;
43 controlGroup?: string;
44}
45
46const withFakeSystemd = <A, E>(
47 body: (input: {
48 readonly scope: Effect.Success<typeof make>;
49 readonly units: Map<string, FakeUnit>;
50 readonly calls: ReadonlyArray<ReadonlyArray<string>>;
51 readonly stateDir: string;
52 readonly cgroupRoot: string;
53 }) => Effect.Effect<A, E>,
54 // A user manager older than systemd 253 rejects OOMPolicy on scopes.
55 {
56 oomPolicy = true,
57 stopFails = false,
58 }: { readonly oomPolicy?: boolean; readonly stopFails?: boolean } = {},
59) =>
60 Effect.gen(function* () {
61 const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
62 for (const name of ["systemd-run", "systemctl", "agent"]) {
63 NodeFS.writeFileSync(NodePath.join(bin, name), "", { mode: 0o755 });
64 }
65 const cgroupRoot = NodePath.join(bin, "cgroup");
66 const units = new Map<string, FakeUnit>();
67 const calls: Array<ReadonlyArray<string>> = [];
68 const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({
69 stdout,
70 stderr: "",
71 code: ChildProcessSpawner.ExitCode(code),
72 timedOut: false,
73 stdoutTruncated: false,
74 stderrTruncated: false,
75 stdoutInvalidUtf8: false,
76 stderrInvalidUtf8: false,
77 });
78 const runner = ProcessRunner.ProcessRunner.of({
79 run: ({ args }) =>
80 Effect.sync(() => {
81 calls.push(args);
82 if (!oomPolicy && args.some((arg) => arg.startsWith("--property=OOMPolicy="))) {
83 return output("", 1);
84 }
85 const [, verb, unit = ""] = args;
86 if (stopFails && verb === "stop") {
87 return {
88 ...output(""),
89 stderr: `Failed to stop ${args.at(-1)}: Unit not loaded.`,
90 code: ChildProcessSpawner.ExitCode(5),
91 };
92 }
93 if (verb === "reset-failed") units.delete(unit);
94 if (verb !== "show") return output("");
95 const state = units.get(unit);
96 return output(
97 state === undefined
98 ? "LoadState=not-found\nActiveState=inactive\nResult=success\n"
99 : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n` +
100 `ControlGroup=${state.controlGroup ?? ""}\n`,
101 );
102 }),
103 });
104 const fileSystem = yield* FileSystem.FileSystem;
105 const scope = yield* make.pipe(
106 Effect.provideService(ProcessRunner.ProcessRunner, runner),
107 Effect.provideService(HostProcess.Platform, "linux"),
108 Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }),
109 Effect.provideService(FileSystem.FileSystem, {
110 ...fileSystem,
111 readFileString: (path, encoding) =>
112 fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding),
113 writeFileString: (path, data, options) =>
114 fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options),
115 }),
116 );
117 const { stateDir } = yield* ServerConfig.ServerConfig;
118 return yield* body({ scope, units, calls, stateDir, cgroupRoot }).pipe(
119 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))),
120 );
121 }).pipe(
122 Effect.scoped,
123 Effect.provide(
124 ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-scope-" }).pipe(
125 Layer.provideMerge(NodeServices.layer),
126 ),
127 ),
128 );
129
130const unitOf = (launch: { readonly args: ReadonlyArray<string> }) =>
131 launch.args.find((arg) => arg.startsWith("--unit="))?.slice("--unit=".length) ?? "";
132
133const sliceOf = (launch: { readonly args: ReadonlyArray<string> }) =>
134 launch.args.find((arg) => arg.startsWith("--slice="))?.slice("--slice=".length) ?? "";
135
136/** An active scope as systemd and the kernel report it, with the agent itself gone. */
137const exitedAgent = (
138 units: Map<string, FakeUnit>,
139 cgroupRoot: string,
140 unit: string,
141 { populated, oomKills }: { readonly populated: boolean; readonly oomKills: number | undefined },
142) => {
143 const controlGroup = `/${unit}`;
144 NodeFS.mkdirSync(NodePath.join(cgroupRoot, controlGroup), { recursive: true });
145 NodeFS.writeFileSync(
146 NodePath.join(cgroupRoot, controlGroup, "cgroup.events"),
147 `populated ${populated ? 1 : 0}\nfrozen 0\n`,
148 );
149 // An undefined count leaves memory.events unreadable.
150 if (oomKills !== undefined) {
151 NodeFS.writeFileSync(
152 NodePath.join(cgroupRoot, controlGroup, "memory.events"),
153 `low 0\nhigh 0\nmax 0\noom ${oomKills}\noom_kill ${oomKills}\noom_group_kill 0\n`,
154 );
155 }
156 units.set(unit, { activeState: "active", result: "success", controlGroup });
157};
158
159const stopsOf = (calls: ReadonlyArray<ReadonlyArray<string>>) =>
160 calls.filter(([, verb]) => verb === "stop");
161const launchCodex = (scope: Effect.Success<typeof make>, threadId: string) =>
162 makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId }).pipe(
163 Effect.provideService(AgentScope, scope),
164 Effect.provideService(HostProcess.Platform, "linux"),
165 Effect.map((command) => {
166 assert(ChildProcess.isStandardCommand(command));
167 return command;
168 }),
169 );
170
171describe("AgentScope service", () => {
172 it.effect("labels a thread from its newest scope until its next session clears it", () =>
173 withFakeSystemd(({ scope, units }) =>
174 Effect.gen(function* () {
175 const first = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
176 units.set(unitOf(first), { activeState: "failed", result: "oom-kill" });
177 const second = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
178 units.set(unitOf(second), { activeState: "active", result: "success" });
179 expect(yield* scope.oomKilled("a")).toBe(false);
180
181 units.set(unitOf(second), { activeState: "failed", result: "oom-kill" });
182 expect(yield* scope.oomKilled("a")).toBe(true);
183 units.delete(unitOf(second));
184 expect(yield* scope.oomKilled("a")).toBe(true);
185
186 yield* scope.clear("a");
187 expect(yield* scope.oomKilled("a")).toBe(false);
188 }),
189 ),
190 );
191
192 it.effect(
193 "keeps shared Codex scopes running without attributing their OOM to the launch thread",
194 () =>
195 withFakeSystemd(({ scope, units, calls }) =>
196 Effect.gen(function* () {
197 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
198 expect(agent.args).toContain("--property=OOMPolicy=stop");
199 units.set(unitOf(agent), { activeState: "failed", result: "oom-kill" });
200 expect(yield* scope.oomKilled("a")).toBe(true);
201
202 const codex = yield* launchCodex(scope, "a");
203 expect(codex.args).toContain("--property=OOMPolicy=continue");
204 expect(codex.args).not.toContain("--property=OOMPolicy=stop");
205 expect(codex.args).toContain("--property=TimeoutStopSec=10s");
206 expect(codex.args).toContain("--collect");
207 units.set(unitOf(codex), { activeState: "active", result: "success" });
208 expect(yield* scope.oomKilled("a")).toBe(false);
209 units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" });
210 expect(yield* scope.oomKilled("a")).toBe(false);
211 expect(
212 calls.filter(([, verb, unit]) => verb === "show" && unit === unitOf(codex)),
213 ).toEqual([]);
214 }),
215 ),
216 );
217
218 it.effect.each([{ oomPolicy: true }, { oomPolicy: false }])(
219 "Force stop kills a thread's own scope but never a shared Codex scope (OOM policy $oomPolicy)",
220 ({ oomPolicy }) =>
221 withFakeSystemd(
222 ({ scope, units, calls, cgroupRoot }) =>
223 Effect.gen(function* () {
224 const agent = yield* scope.wrap({
225 command: "agent",
226 args: [],
227 name: "t",
228 threadId: "a",
229 });
230 exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });
231 const codex = yield* launchCodex(scope, "b");
232 exitedAgent(units, cgroupRoot, unitOf(codex), { populated: true, oomKills: 0 });
233
234 expect(yield* scope.kill("a")).toBe(true);
235 expect(
236 NodeFS.readFileSync(NodePath.join(cgroupRoot, unitOf(agent), "cgroup.kill"), "utf8"),
237 ).toBe("1");
238 expect(yield* scope.kill("b")).toBe(false);
239 expect(NodeFS.existsSync(NodePath.join(cgroupRoot, unitOf(codex), "cgroup.kill"))).toBe(
240 false,
241 );
242 expect(calls.filter(([, verb]) => verb === "kill")).toEqual([]);
243 }),
244 { oomPolicy },
245 ),
246 );
247
248 it.effect("keeps a running scope while hundreds of other threads launch", () =>
249 withFakeSystemd(({ scope, units }) =>
250 Effect.gen(function* () {
251 const live = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "live" });
252 units.set(unitOf(live), { activeState: "active", result: "success" });
253 for (let index = 0; index < 600; index++) {
254 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: `other-${index}` });
255 }
256 units.set(unitOf(live), { activeState: "failed", result: "oom-kill" });
257 expect(yield* scope.oomKilled("live")).toBe(true);
258 }),
259 ),
260 );
261
262 it.effect("delegates every agent scope so rootless containers can manage their cgroups", () =>
263 withFakeSystemd(({ scope }) =>
264 Effect.gen(function* () {
265 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
266 const codex = yield* launchCodex(scope, "a");
267 const terminal = yield* scope.wrap({
268 command: "agent",
269 args: [],
270 name: "terminal",
271 survivesRestart: true,
272 });
273 for (const launch of [agent, codex, terminal]) {
274 expect(launch.args).toContain("--property=Delegate=yes");
275 }
276 }),
277 ),
278 );
279
280 it.effect("stops agents a killed server left before the first launch", () =>
281 withFakeSystemd(({ scope, units, calls, stateDir }) =>
282 Effect.gen(function* () {
283 units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
284 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
285 const stops = calls.filter(([, verb]) => verb === "stop");
286 expect(stops).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
287 expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
288 expect(agent.args).toContain("--property=TimeoutStopSec=10s");
289 const terminal = yield* scope.wrap({
290 command: "agent",
291 args: [],
292 name: "terminal",
293 survivesRestart: true,
294 });
295 expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
296 expect(calls.filter(([, verb]) => verb === "stop")).toHaveLength(1);
297 }),
298 ),
299 );
300
301 it.effect("stops leftover processes only in an active agent scope", () =>
302 withFakeSystemd(({ scope, units, calls, cgroupRoot }) =>
303 Effect.gen(function* () {
304 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
305 const unit = unitOf(agent);
306 expect(agent.unit).toBe(unit);
307
308 yield* scope.stop("session-2.scope");
309 expect(calls.some((args) => args.includes("session-2.scope"))).toBe(false);
310 yield* scope.stop(unit);
311 exitedAgent(units, cgroupRoot, unit, { populated: false, oomKills: 0 });
312 yield* scope.stop(unit);
313 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 0 });
314 units.get(unit)!.activeState = "deactivating";
315 yield* scope.stop(unit);
316 expect(stopsOf(calls)).toEqual([]);
317
318 units.get(unit)!.activeState = "active";
319 yield* scope.stop(unit);
320 expect(stopsOf(calls)).toEqual([["--user", "stop", "--no-block", unit]]);
321 expect(yield* scope.oomKilled("a")).toBe(false);
322 }),
323 ),
324 );
325
326 it.effect.each([true, false])(
327 "cleans up an OOM exit without losing its diagnosis (OOMPolicy=%s)",
328 (oomPolicy) =>
329 withFakeSystemd(
330 ({ scope, units, calls, cgroupRoot }) =>
331 Effect.gen(function* () {
332 const agent = yield* scope.wrap({
333 command: "agent",
334 args: [],
335 name: "t",
336 threadId: "a",
337 });
338 const unit = unitOf(agent);
339 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: undefined });
340 yield* scope.stop(unit);
341 expect(stopsOf(calls)).toEqual(
342 oomPolicy ? [] : [["--user", "stop", "--no-block", unit]],
343 );
344
345 // The kernel records the kill before systemd records the OOM result.
346 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 1 });
347 yield* scope.stop(unit);
348 expect(stopsOf(calls)).toHaveLength(oomPolicy ? 0 : 2);
349
350 if (oomPolicy) {
351 units.set(unit, { activeState: "failed", result: "oom-kill" });
352 expect(yield* scope.oomKilled("a")).toBe(true);
353 units.delete(unit);
354 expect(yield* scope.oomKilled("a")).toBe(true);
355 }
356 }),
357 { oomPolicy },
358 ),
359 );
360
361 it.effect("reports failed daemon cleanup without failing session teardown", () => {
362 const warnings: Array<unknown> = [];
363 const logger = Logger.make(({ message }) => {
364 warnings.push(message);
365 });
366 return withFakeSystemd(
367 ({ scope, units, cgroupRoot }) =>
368 Effect.gen(function* () {
369 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
370 exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });
371 yield* scope.stop(unitOf(agent));
372 expect(warnings.flat()).toContain("Could not stop an exited agent's scope");
373 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
374 { stopFails: true },
375 );
376 });
377
378 it.effect("leaves a quiet slice alone", () =>
379 withFakeSystemd(({ scope, calls }) =>
380 Effect.gen(function* () {
381 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
382 expect(calls.filter(([, verb]) => verb === "stop")).toEqual([]);
383 }),
384 ),
385 );
386});