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

agentScope.test.ts

529 lines21.0 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 { symlinksSupported } from "@t3tools/shared/testing/symlinks";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Logger from "effect/Logger";
15import { ChildProcess, ChildProcessSpawner } from "effect/process";
16import { vi } from "vite-plus/test";
17​
18import * as ServerConfig from "../config.ts";
19import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
20import * as ProcessRunner from "../processRunner.ts";
21import * as ProviderProcesses from "./providerProcesses.ts";
22import { classifyScope, make, ownedAgentSlice, type ScopeState } from "./agentScope.ts";
23​
24const GiB = 1024 ** 3;
25const memory = vi.hoisted(() => ({ total: 16 * 1024 ** 3, swapKb: 2 * 1024 ** 2 }));
26vi.mock("node:os", async (importOriginal) => ({
27 ...(await importOriginal<typeof import("node:os")>()),
28 totalmem: () => memory.total,
29}));
30​
31const running: ScopeState = {
32 loadState: "loaded",
33 activeState: "active",
34 result: "success",
35 oomKills: 0,
36 populated: true,
37};
38​
39describe("classifyScope", () => {
40 it("reports an OOM kill only once systemd records it", () => {
41 expect(classifyScope({ ...running, activeState: "failed", result: "oom-kill" })).toBe(
42 "oom-killed",
43 );
44 expect(classifyScope({ ...running, oomKills: 1 })).toBe("stopping");
45 expect(classifyScope({ ...running, populated: false })).toBe("stopping");
46 expect(classifyScope({ ...running, activeState: "deactivating" })).toBe("stopping");
47 });
48});
49​
50interface FakeUnit {
51 activeState: string;
52 result: string;
53 controlGroup?: string;
55​
56const withFakeSystemd = <A, E>(
57 body: (input: {
58 readonly scope: Effect.Success<typeof make>;
59 readonly units: Map<string, FakeUnit>;
60 readonly calls: ReadonlyArray<ReadonlyArray<string>>;
61 readonly failingVerbs: Set<string>;
62 readonly stateDir: string;
63 readonly cgroupRoot: string;
64 }) => Effect.Effect<A, E>,
65 // A user manager older than systemd 253 rejects OOMPolicy on scopes.
66 {
67 oomPolicy = true,
68 stopFails = false,
69 leftovers = false,
70 liveOwner = false,
71 }: {
72 readonly oomPolicy?: boolean;
73 readonly stopFails?: boolean;
74 readonly leftovers?: boolean;
75 readonly liveOwner?: boolean;
76 } = {},
77) =>
78 Effect.gen(function* () {
79 const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
80 for (const name of ["systemd-run", "systemctl", "agent"]) {
81 NodeFS.writeFileSync(NodePath.join(bin, name), "", { mode: 0o755 });
82 }
83 const cgroupRoot = NodePath.join(bin, "cgroup");
84 const units = new Map<string, FakeUnit>();
85 const calls: Array<ReadonlyArray<string>> = [];
86 const failingVerbs = new Set<string>();
87 const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({
88 stdout,
89 stderr: "",
90 code: ChildProcessSpawner.ExitCode(code),
91 timedOut: false,
92 stdoutTruncated: false,
93 stderrTruncated: false,
94 stdoutInvalidUtf8: false,
95 stderrInvalidUtf8: false,
96 });
97 const runner = ProcessRunner.ProcessRunner.of({
98 run: ({ args }) =>
99 Effect.sync(() => {
100 calls.push(args);
101 if (!oomPolicy && args.some((arg) => arg.startsWith("--property=OOMPolicy="))) {
102 return output("", 1);
103 }
104 const [, verb, unit = ""] = args;
105 if (failingVerbs.has(verb!)) return output("", 1);
106 if (stopFails && verb === "stop") {
107 return {
108 ...output(""),
109 stderr: `Failed to stop ${args.at(-1)}: Unit not loaded.`,
110 code: ChildProcessSpawner.ExitCode(5),
111 };
112 }
113 if (verb === "reset-failed") units.delete(unit);
114 if (verb !== "show") return output("");
115 const state = units.get(unit);
116 return output(
117 state === undefined
118 ? "LoadState=not-found\nActiveState=inactive\nResult=success\n"
119 : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n` +
120 `ControlGroup=${state.controlGroup ?? ""}\n`,
121 );
122 }),
123 });
124 const fileSystem = yield* FileSystem.FileSystem;
125 const { stateDir } = yield* ServerConfig.ServerConfig;
126 if (leftovers) {
127 units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
128 }
129 const scope = yield* make.pipe(
130 Effect.provideService(ProviderProcesses.ProviderProcesses, { hasOtherLiveOwner: liveOwner }),
131 Effect.provideService(ProcessRunner.ProcessRunner, runner),
132 Effect.provideService(HostProcess.Platform, "linux"),
133 Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }),
134 Effect.provideService(FileSystem.FileSystem, {
135 ...fileSystem,
136 readFileString: (path, encoding) =>
137 path === "/proc/meminfo"
138 ? Effect.sync(() => `MemTotal: 16384 kB\nSwapTotal: ${memory.swapKb} kB\n`)
139 : fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding),
140 writeFileString: (path, data, options) =>
141 fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options),
142 }),
143 );
144 return yield* body({ scope, units, calls, failingVerbs, stateDir, cgroupRoot }).pipe(
145 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))),
146 );
147 }).pipe(
148 Effect.scoped,
149 Effect.provide(
150 ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-scope-" }).pipe(
151 Layer.provideMerge(NodeServices.layer),
152 ),
153 ),
154 );
155​
156const unitOf = (launch: Pick<ChildProcess.StandardCommand, "args">) =>
157 launch.args
158 .map(String)
159 .find((arg) => arg.startsWith("--unit="))
160 ?.slice("--unit=".length) ?? "";
161​
162const sliceOf = (launch: { readonly args: ReadonlyArray<string> }) =>
163 launch.args.find((arg) => arg.startsWith("--slice="))?.slice("--slice=".length) ?? "";
164​
165/** An active scope as systemd and the kernel report it, with the agent itself gone. */
166const exitedAgent = (
167 units: Map<string, FakeUnit>,
168 cgroupRoot: string,
169 unit: string,
170 { populated, oomKills }: { readonly populated: boolean; readonly oomKills: number | undefined },
171) => {
172 const controlGroup = `/${unit}`;
173 NodeFS.mkdirSync(NodePath.join(cgroupRoot, controlGroup), { recursive: true });
174 NodeFS.writeFileSync(
175 NodePath.join(cgroupRoot, controlGroup, "cgroup.events"),
176 `populated ${populated ? 1 : 0}\nfrozen 0\n`,
177 );
178 // An undefined count leaves memory.events unreadable.
179 if (oomKills !== undefined) {
180 NodeFS.writeFileSync(
181 NodePath.join(cgroupRoot, controlGroup, "memory.events"),
182 `low 0\nhigh 0\nmax 0\noom ${oomKills}\noom_kill ${oomKills}\noom_group_kill 0\n`,
183 );
184 }
185 units.set(unit, { activeState: "active", result: "success", controlGroup });
186};
187​
188const stopsOf = (calls: ReadonlyArray<ReadonlyArray<string>>) =>
189 calls.filter(([, verb]) => verb === "stop");
190const launchCodex = (
191 scope: Effect.Success<typeof make>,
192 threadId: string,
193 env?: NodeJS.ProcessEnv,
194) =>
195 makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId, env }).pipe(
196 Effect.provideService(AgentScope, scope),
197 Effect.provideService(HostProcess.Platform, "linux"),
198 Effect.map((command) => {
199 assert(ChildProcess.isStandardCommand(command));
200 return command;
201 }),
202 );
203​
204describe("AgentScope service", () => {
205 it.effect("labels a thread from its newest scope until its next session clears it", () =>
206 withFakeSystemd(({ scope, units }) =>
207 Effect.gen(function* () {
208 const first = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
209 units.set(unitOf(first), { activeState: "failed", result: "oom-kill" });
210 const second = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
211 units.set(unitOf(second), { activeState: "active", result: "success" });
212 expect(yield* scope.oomKilled("a")).toBe(false);
213​
214 units.set(unitOf(second), { activeState: "failed", result: "oom-kill" });
215 expect(yield* scope.oomKilled("a")).toBe(true);
216 units.delete(unitOf(second));
217 expect(yield* scope.oomKilled("a")).toBe(true);
218​
219 yield* scope.clear("a");
220 expect(yield* scope.oomKilled("a")).toBe(false);
221 }),
222 ),
223 );
224​
225 it.effect(
226 "keeps shared Codex scopes running without attributing their OOM to the launch thread",
227 () =>
228 withFakeSystemd(({ scope, units, calls }) =>
229 Effect.gen(function* () {
230 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
231 expect(agent.args).toContain("--property=OOMPolicy=stop");
232 units.set(unitOf(agent), { activeState: "failed", result: "oom-kill" });
233 expect(yield* scope.oomKilled("a")).toBe(true);
234​
235 const executable = String(agent.args.at(-1));
236 const codex = yield* launchCodex(scope, "a", {
237 PATH: NodePath.relative(process.cwd(), NodePath.dirname(executable)),
238 });
239 // Anchored to the cwd for systemd-run, with its ".." kept; it names the same file.
240 const anchored = String(codex.args.at(-2));
241 expect(NodePath.isAbsolute(anchored)).toBe(true);
242 expect(NodePath.resolve(anchored)).toBe(executable);
243 expect(codex.args).toContain("--property=OOMPolicy=continue");
244 expect(codex.args).not.toContain("--property=OOMPolicy=stop");
245 expect(codex.args).toContain("--property=TimeoutStopSec=10s");
246 expect(codex.args).toContain("--collect");
247 units.set(unitOf(codex), { activeState: "active", result: "success" });
248 expect(yield* scope.oomKilled("a")).toBe(false);
249 units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" });
250 expect(yield* scope.oomKilled("a")).toBe(false);
251 expect(
252 calls.filter(([, verb, unit]) => verb === "show" && unit === unitOf(codex)),
253 ).toEqual([]);
254 }),
255 ),
256 );
257​
258 it.effect.skipIf(!symlinksSupported)(
259 "keeps a symlinked parent in absolute and relative executable paths",
260 () =>
261 withFakeSystemd(({ scope }) =>
262 Effect.gen(function* () {
263 const plain = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "s" });
264 const bin = NodePath.dirname(String(plain.args.at(-1)));
265 NodeFS.mkdirSync(NodePath.join(bin, "real", "sub"), { recursive: true });
266 NodeFS.writeFileSync(NodePath.join(bin, "real", "agent"), "", { mode: 0o755 });
267 NodeFS.symlinkSync(NodePath.join(bin, "real", "sub"), NodePath.join(bin, "link"));
268 // The kernel follows the link before "..", so this names real/agent, not bin/agent.
269 const command = `${NodePath.join(bin, "link")}/../agent`;
270 const wrapped = yield* scope.wrap({ command, args: [], name: "t", threadId: "s" });
271 expect(wrapped.args.at(-1)).toBe(command);
272 // A relative path is anchored to the cwd the same way, without collapsing "..".
273 const relative = `${NodePath.relative(process.cwd(), NodePath.join(bin, "link"))}/../agent`;
274 const anchored = yield* scope.wrap({
275 command: relative,
276 args: [],
277 name: "t",
278 threadId: "s",
279 });
280 expect(anchored.args.at(-1)).toBe(`${process.cwd()}${NodePath.sep}${relative}`);
281 }),
282 ),
283 );
284​
285 it.effect.each([{ oomPolicy: true }, { oomPolicy: false }])(
286 "Force stop kills a thread's own scope but never a shared Codex scope (OOM policy $oomPolicy)",
287 ({ oomPolicy }) =>
288 withFakeSystemd(
289 ({ scope, units, calls, cgroupRoot }) =>
290 Effect.gen(function* () {
291 const agent = yield* scope.wrap({
292 command: "agent",
293 args: [],
294 name: "t",
295 threadId: "a",
296 });
297 exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });
298 const codex = yield* launchCodex(scope, "b");
299 exitedAgent(units, cgroupRoot, unitOf(codex), { populated: true, oomKills: 0 });
300​
301 expect(yield* scope.kill("a")).toBe(true);
302 expect(
303 NodeFS.readFileSync(NodePath.join(cgroupRoot, unitOf(agent), "cgroup.kill"), "utf8"),
304 ).toBe("1");
305 expect(yield* scope.kill("b")).toBe(false);
306 expect(NodeFS.existsSync(NodePath.join(cgroupRoot, unitOf(codex), "cgroup.kill"))).toBe(
307 false,
308 );
309 expect(calls.filter(([, verb]) => verb === "kill")).toEqual([]);
310 }),
311 { oomPolicy },
312 ),
313 );
314​
315 it.effect("keeps a running scope while hundreds of other threads launch", () =>
316 withFakeSystemd(({ scope, units }) =>
317 Effect.gen(function* () {
318 const live = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "live" });
319 units.set(unitOf(live), { activeState: "active", result: "success" });
320 for (let index = 0; index < 600; index++) {
321 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: `other-${index}` });
322 }
323 units.set(unitOf(live), { activeState: "failed", result: "oom-kill" });
324 expect(yield* scope.oomKilled("live")).toBe(true);
325 }),
326 ),
327 );
328​
329 it.effect("delegates every agent scope so rootless containers can manage their cgroups", () =>
330 withFakeSystemd(({ scope }) =>
331 Effect.gen(function* () {
332 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
333 const codex = yield* launchCodex(scope, "a");
334 const terminal = yield* scope.wrap({
335 command: "agent",
336 args: [],
337 name: "terminal",
338 survivesRestart: true,
339 });
340 for (const launch of [agent, codex, terminal]) {
341 expect(launch.args).toContain("--property=Delegate=yes");
342 }
343 }),
344 ),
345 );
346​
347 it.effect("caps agent memory and yields CPU, disk, and tasks to the server", () =>
348 withFakeSystemd(({ scope, calls }) =>
349 Effect.gen(function* () {
350 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
351 const setProperties = calls.filter(([, verb]) => verb === "set-property");
352 expect(setProperties).toEqual([
353 [
354 "--user",
355 "set-property",
356 "--runtime",
357 "app-t3code-agents.slice",
358 expect.stringMatching(/^MemoryHigh=\d+$/),
359 expect.stringMatching(/^MemoryMax=\d+$/),
360 ],
361 [
362 "--user",
363 "set-property",
364 "--runtime",
365 "app-t3code.slice",
366 "CPUWeight=10",
367 "IOWeight=10",
368 "TasksMax=25%",
369 ],
370 ]);
371 }),
372 ),
373 );
374​
375 it.effect("follows a live memory or swap change at the next launch", () => {
376 memory.total = 16 * GiB;
377 memory.swapKb = 2 * 1024 ** 2;
378 return withFakeSystemd(({ scope, calls, failingVerbs }) =>
379 Effect.gen(function* () {
380 const launch = scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
381 const memoryLimits = () =>
382 calls
383 .filter(
384 ([, verb, , slice]) => verb === "set-property" && slice === "app-t3code-agents.slice",
385 )
386 .map((args) => args.slice(4));
387 yield* launch;
388 yield* launch;
389 expect(memoryLimits()).toEqual([[`MemoryHigh=${10 * GiB}`, `MemoryMax=${12 * GiB}`]]);
390​
391 // A VM balloon or `pct set --memory` grows RAM while the server keeps running.
392 memory.total = 22 * GiB;
393 failingVerbs.add("set-property");
394 yield* launch;
395 yield* launch;
396 failingVerbs.delete("set-property");
397 yield* launch;
398 yield* launch;
399 const grown = [`MemoryHigh=${16 * GiB}`, `MemoryMax=${18 * GiB}`];
400 expect(memoryLimits()).toEqual([
401 [`MemoryHigh=${10 * GiB}`, `MemoryMax=${12 * GiB}`],
402 grown,
403 grown,
404 grown,
405 ]);
406​
407 // Without swap, MemoryHigh only throttles; MemoryMax must OOM-kill the runaway.
408 memory.swapKb = 0;
409 yield* launch;
410 expect(memoryLimits().at(-1)).toEqual(["MemoryHigh=infinity", `MemoryMax=${18 * GiB}`]);
411 memory.swapKb = 2 * 1024 ** 2;
412 }),
413 );
414 });
415​
416 it.effect("stops agents a killed server left before startup completes", () =>
417 withFakeSystemd(
418 ({ scope, calls, stateDir }) =>
419 Effect.gen(function* () {
420 expect(stopsOf(calls)).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
421 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
422 expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
423 expect(agent.args).toContain("--property=TimeoutStopSec=10s");
424 const terminal = yield* scope.wrap({
425 command: "agent",
426 args: [],
427 name: "terminal",
428 survivesRestart: true,
429 });
430 expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
431 expect(stopsOf(calls)).toHaveLength(1);
432 }),
433 { leftovers: true },
434 ),
435 );
436​
437 it.effect("leaves the slice to another live server sharing this home", () =>
438 withFakeSystemd(({ calls }) => Effect.sync(() => expect(stopsOf(calls)).toEqual([])), {
439 leftovers: true,
440 liveOwner: true,
441 }),
442 );
443​
444 it.effect("stops leftover processes only in an active agent scope", () =>
445 withFakeSystemd(({ scope, units, calls, cgroupRoot }) =>
446 Effect.gen(function* () {
447 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
448 const unit = unitOf(agent);
449 expect(agent.unit).toBe(unit);
450​
451 yield* scope.stop("session-2.scope");
452 expect(calls.some((args) => args.includes("session-2.scope"))).toBe(false);
453 yield* scope.stop(unit);
454 exitedAgent(units, cgroupRoot, unit, { populated: false, oomKills: 0 });
455 yield* scope.stop(unit);
456 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 0 });
457 units.get(unit)!.activeState = "deactivating";
458 yield* scope.stop(unit);
459 expect(stopsOf(calls)).toEqual([]);
460​
461 units.get(unit)!.activeState = "active";
462 yield* scope.stop(unit);
463 expect(stopsOf(calls)).toEqual([["--user", "stop", "--no-block", unit]]);
464 expect(yield* scope.oomKilled("a")).toBe(false);
465 }),
466 ),
467 );
468​
469 it.effect.each([true, false])(
470 "cleans up an OOM exit without losing its diagnosis (OOMPolicy=%s)",
471 (oomPolicy) =>
472 withFakeSystemd(
473 ({ scope, units, calls, cgroupRoot }) =>
474 Effect.gen(function* () {
475 const agent = yield* scope.wrap({
476 command: "agent",
477 args: [],
478 name: "t",
479 threadId: "a",
480 });
481 const unit = unitOf(agent);
482 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: undefined });
483 yield* scope.stop(unit);
484 expect(stopsOf(calls)).toEqual(
485 oomPolicy ? [] : [["--user", "stop", "--no-block", unit]],
486 );
487​
488 // The kernel records the kill before systemd records the OOM result.
489 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 1 });
490 yield* scope.stop(unit);
491 expect(stopsOf(calls)).toHaveLength(oomPolicy ? 0 : 2);
492​
493 if (oomPolicy) {
494 units.set(unit, { activeState: "failed", result: "oom-kill" });
495 expect(yield* scope.oomKilled("a")).toBe(true);
496 units.delete(unit);
497 expect(yield* scope.oomKilled("a")).toBe(true);
498 }
499 }),
500 { oomPolicy },
501 ),
502 );
503​
504 it.effect("reports failed daemon cleanup without failing session teardown", () => {
505 const warnings: Array<unknown> = [];
506 const logger = Logger.make(({ message }) => {
507 warnings.push(message);
508 });
509 return withFakeSystemd(
510 ({ scope, units, cgroupRoot }) =>
511 Effect.gen(function* () {
512 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
513 exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });
514 yield* scope.stop(unitOf(agent));
515 expect(warnings.flat()).toContain("Could not stop an exited agent's scope");
516 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
517 { stopFails: true },
518 );
519 });
520​
521 it.effect("leaves a quiet slice alone", () =>
522 withFakeSystemd(({ scope, calls }) =>
523 Effect.gen(function* () {
524 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
525 expect(calls.filter(([, verb]) => verb === "stop")).toEqual([]);
526 }),
527 ),
528 );
529});