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

agentScope.test.ts

336 lines13.7 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 }),
114 );
115 const { stateDir } = yield* ServerConfig.ServerConfig;
116 return yield* body({ scope, units, calls, stateDir, cgroupRoot }).pipe(
117 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))),
118 );
119 }).pipe(
120 Effect.scoped,
121 Effect.provide(
122 ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-scope-" }).pipe(
123 Layer.provideMerge(NodeServices.layer),
124 ),
125 ),
126 );
127​
128const unitOf = (launch: { readonly args: ReadonlyArray<string> }) =>
129 launch.args.find((arg) => arg.startsWith("--unit="))?.slice("--unit=".length) ?? "";
130​
131const sliceOf = (launch: { readonly args: ReadonlyArray<string> }) =>
132 launch.args.find((arg) => arg.startsWith("--slice="))?.slice("--slice=".length) ?? "";
133​
134/** An active scope as systemd and the kernel report it, with the agent itself gone. */
135const exitedAgent = (
136 units: Map<string, FakeUnit>,
137 cgroupRoot: string,
138 unit: string,
139 { populated, oomKills }: { readonly populated: boolean; readonly oomKills: number | undefined },
140) => {
141 const controlGroup = `/${unit}`;
142 NodeFS.mkdirSync(NodePath.join(cgroupRoot, controlGroup), { recursive: true });
143 NodeFS.writeFileSync(
144 NodePath.join(cgroupRoot, controlGroup, "cgroup.events"),
145 `populated ${populated ? 1 : 0}\nfrozen 0\n`,
146 );
147 // An undefined count leaves memory.events unreadable.
148 if (oomKills !== undefined) {
149 NodeFS.writeFileSync(
150 NodePath.join(cgroupRoot, controlGroup, "memory.events"),
151 `low 0\nhigh 0\nmax 0\noom ${oomKills}\noom_kill ${oomKills}\noom_group_kill 0\n`,
152 );
153 }
154 units.set(unit, { activeState: "active", result: "success", controlGroup });
155};
156​
157const stopsOf = (calls: ReadonlyArray<ReadonlyArray<string>>) =>
158 calls.filter(([, verb]) => verb === "stop");
159const launchCodex = (scope: Effect.Success<typeof make>, threadId: string) =>
160 makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId }).pipe(
161 Effect.provideService(AgentScope, scope),
162 Effect.provideService(HostProcess.Platform, "linux"),
163 Effect.map((command) => {
164 assert(ChildProcess.isStandardCommand(command));
165 return command;
166 }),
167 );
168​
169describe("AgentScope service", () => {
170 it.effect("labels a thread from its newest scope until its next session clears it", () =>
171 withFakeSystemd(({ scope, units }) =>
172 Effect.gen(function* () {
173 const first = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
174 units.set(unitOf(first), { activeState: "failed", result: "oom-kill" });
175 const second = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
176 units.set(unitOf(second), { activeState: "active", result: "success" });
177 expect(yield* scope.oomKilled("a")).toBe(false);
178​
179 units.set(unitOf(second), { activeState: "failed", result: "oom-kill" });
180 expect(yield* scope.oomKilled("a")).toBe(true);
181 units.delete(unitOf(second));
182 expect(yield* scope.oomKilled("a")).toBe(true);
183​
184 yield* scope.clear("a");
185 expect(yield* scope.oomKilled("a")).toBe(false);
186 }),
187 ),
188 );
189​
190 it.effect(
191 "keeps shared Codex scopes running without attributing their OOM to the launch thread",
192 () =>
193 withFakeSystemd(({ scope, units, calls }) =>
194 Effect.gen(function* () {
195 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
196 expect(agent.args).toContain("--property=OOMPolicy=stop");
197 units.set(unitOf(agent), { activeState: "failed", result: "oom-kill" });
198 expect(yield* scope.oomKilled("a")).toBe(true);
199​
200 const codex = yield* launchCodex(scope, "a");
201 expect(codex.args).toContain("--property=OOMPolicy=continue");
202 expect(codex.args).not.toContain("--property=OOMPolicy=stop");
203 expect(codex.args).toContain("--property=TimeoutStopSec=10s");
204 expect(codex.args).toContain("--collect");
205 units.set(unitOf(codex), { activeState: "active", result: "success" });
206 expect(yield* scope.oomKilled("a")).toBe(false);
207 units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" });
208 expect(yield* scope.oomKilled("a")).toBe(false);
209 expect(
210 calls.filter(([, verb, unit]) => verb === "show" && unit === unitOf(codex)),
211 ).toEqual([]);
212 }),
213 ),
214 );
215​
216 it.effect("keeps a running scope while hundreds of other threads launch", () =>
217 withFakeSystemd(({ scope, units }) =>
218 Effect.gen(function* () {
219 const live = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "live" });
220 units.set(unitOf(live), { activeState: "active", result: "success" });
221 for (let index = 0; index < 600; index++) {
222 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: `other-${index}` });
223 }
224 units.set(unitOf(live), { activeState: "failed", result: "oom-kill" });
225 expect(yield* scope.oomKilled("live")).toBe(true);
226 }),
227 ),
228 );
229​
230 it.effect("stops agents a killed server left before the first launch", () =>
231 withFakeSystemd(({ scope, units, calls, stateDir }) =>
232 Effect.gen(function* () {
233 units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
234 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
235 const stops = calls.filter(([, verb]) => verb === "stop");
236 expect(stops).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
237 expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
238 expect(agent.args).toContain("--property=TimeoutStopSec=10s");
239 const terminal = yield* scope.wrap({
240 command: "agent",
241 args: [],
242 name: "terminal",
243 survivesRestart: true,
244 });
245 expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
246 expect(calls.filter(([, verb]) => verb === "stop")).toHaveLength(1);
247 }),
248 ),
249 );
250​
251 it.effect("stops leftover processes only in an active agent scope", () =>
252 withFakeSystemd(({ scope, units, calls, cgroupRoot }) =>
253 Effect.gen(function* () {
254 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
255 const unit = unitOf(agent);
256 expect(agent.unit).toBe(unit);
257​
258 yield* scope.stop("session-2.scope");
259 expect(calls.some((args) => args.includes("session-2.scope"))).toBe(false);
260 yield* scope.stop(unit);
261 exitedAgent(units, cgroupRoot, unit, { populated: false, oomKills: 0 });
262 yield* scope.stop(unit);
263 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 0 });
264 units.get(unit)!.activeState = "deactivating";
265 yield* scope.stop(unit);
266 expect(stopsOf(calls)).toEqual([]);
267​
268 units.get(unit)!.activeState = "active";
269 yield* scope.stop(unit);
270 expect(stopsOf(calls)).toEqual([["--user", "stop", "--no-block", unit]]);
271 expect(yield* scope.oomKilled("a")).toBe(false);
272 }),
273 ),
274 );
275​
276 it.effect.each([true, false])(
277 "cleans up an OOM exit without losing its diagnosis (OOMPolicy=%s)",
278 (oomPolicy) =>
279 withFakeSystemd(
280 ({ scope, units, calls, cgroupRoot }) =>
281 Effect.gen(function* () {
282 const agent = yield* scope.wrap({
283 command: "agent",
284 args: [],
285 name: "t",
286 threadId: "a",
287 });
288 const unit = unitOf(agent);
289 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: undefined });
290 yield* scope.stop(unit);
291 expect(stopsOf(calls)).toEqual(
292 oomPolicy ? [] : [["--user", "stop", "--no-block", unit]],
293 );
294​
295 // The kernel records the kill before systemd records the OOM result.
296 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 1 });
297 yield* scope.stop(unit);
298 expect(stopsOf(calls)).toHaveLength(oomPolicy ? 0 : 2);
299​
300 if (oomPolicy) {
301 units.set(unit, { activeState: "failed", result: "oom-kill" });
302 expect(yield* scope.oomKilled("a")).toBe(true);
303 units.delete(unit);
304 expect(yield* scope.oomKilled("a")).toBe(true);
305 }
306 }),
307 { oomPolicy },
308 ),
309 );
310​
311 it.effect("reports failed daemon cleanup without failing session teardown", () => {
312 const warnings: Array<unknown> = [];
313 const logger = Logger.make(({ message }) => {
314 warnings.push(message);
315 });
316 return withFakeSystemd(
317 ({ scope, units, cgroupRoot }) =>
318 Effect.gen(function* () {
319 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
320 exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });
321 yield* scope.stop(unitOf(agent));
322 expect(warnings.flat()).toContain("Could not stop an exited agent's scope");
323 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
324 { stopFails: true },
325 );
326 });
327​
328 it.effect("leaves a quiet slice alone", () =>
329 withFakeSystemd(({ scope, calls }) =>
330 Effect.gen(function* () {
331 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
332 expect(calls.filter(([, verb]) => verb === "stop")).toEqual([]);
333 }),
334 ),
335 );
336});