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

agentScope.test.ts

414 lines16.5 KB

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;
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("caps agent memory and yields CPU, disk, and tasks to the server", () =>
281 withFakeSystemd(({ scope, calls }) =>
282 Effect.gen(function* () {
283 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
284 const setProperties = calls.filter(([, verb]) => verb === "set-property");
285 expect(setProperties).toEqual([
286 [
287 "--user",
288 "set-property",
289 "--runtime",
290 "app-t3code-agents.slice",
291 expect.stringMatching(/^MemoryHigh=\d+$/),
292 expect.stringMatching(/^MemoryMax=\d+$/),
293 ],
294 [
295 "--user",
296 "set-property",
297 "--runtime",
298 "app-t3code.slice",
299 "CPUWeight=10",
300 "IOWeight=10",
301 "TasksMax=25%",
302 ],
303 ]);
304 }),
305 ),
306 );
307​
308 it.effect("stops agents a killed server left before the first launch", () =>
309 withFakeSystemd(({ scope, units, calls, stateDir }) =>
310 Effect.gen(function* () {
311 units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
312 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
313 const stops = calls.filter(([, verb]) => verb === "stop");
314 expect(stops).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
315 expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
316 expect(agent.args).toContain("--property=TimeoutStopSec=10s");
317 const terminal = yield* scope.wrap({
318 command: "agent",
319 args: [],
320 name: "terminal",
321 survivesRestart: true,
322 });
323 expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
324 expect(calls.filter(([, verb]) => verb === "stop")).toHaveLength(1);
325 }),
326 ),
327 );
328​
329 it.effect("stops leftover processes only in an active agent scope", () =>
330 withFakeSystemd(({ scope, units, calls, cgroupRoot }) =>
331 Effect.gen(function* () {
332 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
333 const unit = unitOf(agent);
334 expect(agent.unit).toBe(unit);
335​
336 yield* scope.stop("session-2.scope");
337 expect(calls.some((args) => args.includes("session-2.scope"))).toBe(false);
338 yield* scope.stop(unit);
339 exitedAgent(units, cgroupRoot, unit, { populated: false, oomKills: 0 });
340 yield* scope.stop(unit);
341 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 0 });
342 units.get(unit)!.activeState = "deactivating";
343 yield* scope.stop(unit);
344 expect(stopsOf(calls)).toEqual([]);
345​
346 units.get(unit)!.activeState = "active";
347 yield* scope.stop(unit);
348 expect(stopsOf(calls)).toEqual([["--user", "stop", "--no-block", unit]]);
349 expect(yield* scope.oomKilled("a")).toBe(false);
350 }),
351 ),
352 );
353​
354 it.effect.each([true, false])(
355 "cleans up an OOM exit without losing its diagnosis (OOMPolicy=%s)",
356 (oomPolicy) =>
357 withFakeSystemd(
358 ({ scope, units, calls, cgroupRoot }) =>
359 Effect.gen(function* () {
360 const agent = yield* scope.wrap({
361 command: "agent",
362 args: [],
363 name: "t",
364 threadId: "a",
365 });
366 const unit = unitOf(agent);
367 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: undefined });
368 yield* scope.stop(unit);
369 expect(stopsOf(calls)).toEqual(
370 oomPolicy ? [] : [["--user", "stop", "--no-block", unit]],
371 );
372​
373 // The kernel records the kill before systemd records the OOM result.
374 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 1 });
375 yield* scope.stop(unit);
376 expect(stopsOf(calls)).toHaveLength(oomPolicy ? 0 : 2);
377​
378 if (oomPolicy) {
379 units.set(unit, { activeState: "failed", result: "oom-kill" });
380 expect(yield* scope.oomKilled("a")).toBe(true);
381 units.delete(unit);
382 expect(yield* scope.oomKilled("a")).toBe(true);
383 }
384 }),
385 { oomPolicy },
386 ),
387 );
388​
389 it.effect("reports failed daemon cleanup without failing session teardown", () => {
390 const warnings: Array<unknown> = [];
391 const logger = Logger.make(({ message }) => {
392 warnings.push(message);
393 });
394 return withFakeSystemd(
395 ({ scope, units, cgroupRoot }) =>
396 Effect.gen(function* () {
397 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
398 exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });
399 yield* scope.stop(unitOf(agent));
400 expect(warnings.flat()).toContain("Could not stop an exited agent's scope");
401 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
402 { stopFails: true },
403 );
404 });
405​
406 it.effect("leaves a quiet slice alone", () =>
407 withFakeSystemd(({ scope, calls }) =>
408 Effect.gen(function* () {
409 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
410 expect(calls.filter(([, verb]) => verb === "stop")).toEqual([]);
411 }),
412 ),
413 );
414});