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

agentScope.test.ts

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