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

agentScope.test.ts

264 lines10.8 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 Layer from "effect/Layer";
12import { ChildProcess, ChildProcessSpawner } from "effect/process";
13​
14import * as ServerConfig from "../config.ts";
15import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
16import * as ProcessRunner from "../processRunner.ts";
17import {
18 agentSliceMemoryLimits,
19 classifyScope,
20 make,
21 ownedAgentSlice,
22 type ScopeState,
23} from "./agentScope.ts";
24​
25const GiB = 1024 ** 3;
26​
27const running: ScopeState = {
28 loadState: "loaded",
29 activeState: "active",
30 result: "success",
31 oomKills: 0,
32 populated: true,
33};
34​
35describe("classifyScope", () => {
36 it("reports an OOM kill only once systemd records it", () => {
37 expect(classifyScope({ ...running, activeState: "failed", result: "oom-kill" })).toBe(
38 "oom-killed",
39 );
40 expect(classifyScope({ ...running, oomKills: 1 })).toBe("stopping");
41 expect(classifyScope({ ...running, populated: false })).toBe("stopping");
42 expect(classifyScope({ ...running, activeState: "deactivating" })).toBe("stopping");
43 });
44​
45 it("does not wait on a live agent or a scope that ended for another reason", () => {
46 expect(classifyScope(running)).toBe("running");
47 expect(classifyScope({ ...running, activeState: "inactive", populated: undefined })).toBe(
48 "gone",
49 );
50 expect(classifyScope({ ...running, loadState: "not-found", activeState: "inactive" })).toBe(
51 "gone",
52 );
53 });
54});
55​
56describe("agentSliceMemoryLimits", () => {
57 it("leaves 6 GB before throttling and 4 GB before a kill on large machines", () => {
58 expect(agentSliceMemoryLimits(64 * GiB)).toEqual({ high: 58 * GiB, max: 60 * GiB });
59 });
60​
61 it("still gives agents most of a small machine", () => {
62 expect(agentSliceMemoryLimits(8 * GiB)).toEqual({ high: 4 * GiB, max: 6 * GiB });
63 });
64});
65​
66const withFakeSystemd = <A, E>(
67 body: (input: {
68 readonly scope: Effect.Success<typeof make>;
69 readonly units: Map<string, { activeState: string; result: string }>;
70 readonly calls: ReadonlyArray<ReadonlyArray<string>>;
71 readonly stateDir: string;
72 }) => Effect.Effect<A, E>,
73 { oomPolicy = true }: { readonly oomPolicy?: boolean } = {},
74) =>
75 Effect.gen(function* () {
76 const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
77 for (const name of ["systemd-run", "systemctl", "agent"]) {
78 NodeFS.writeFileSync(NodePath.join(bin, name), "", { mode: 0o755 });
79 }
80 const units = new Map<string, { activeState: string; result: string }>();
81 const calls: Array<ReadonlyArray<string>> = [];
82 const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({
83 stdout,
84 stderr: "",
85 code: ChildProcessSpawner.ExitCode(code),
86 timedOut: false,
87 stdoutTruncated: false,
88 stderrTruncated: false,
89 stdoutInvalidUtf8: false,
90 stderrInvalidUtf8: false,
91 });
92 const runner = ProcessRunner.ProcessRunner.of({
93 run: ({ args }) =>
94 Effect.sync(() => {
95 calls.push(args);
96 if (!oomPolicy && args.some((arg) => arg.startsWith("--property=OOMPolicy="))) {
97 return output("", 1);
98 }
99 const [, verb, unit = ""] = args;
100 if (verb === "reset-failed") units.delete(unit);
101 if (verb !== "show") return output("");
102 const state = units.get(unit);
103 return output(
104 state === undefined
105 ? "LoadState=not-found\nActiveState=inactive\nResult=success\n"
106 : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n`,
107 );
108 }),
109 });
110 const scope = yield* make.pipe(
111 Effect.provideService(ProcessRunner.ProcessRunner, runner),
112 Effect.provideService(HostProcess.Platform, "linux"),
113 Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }),
114 );
115 const { stateDir } = yield* ServerConfig.ServerConfig;
116 return yield* body({ scope, units, calls, stateDir }).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​
134const launchCodex = (scope: Effect.Success<typeof make>, threadId: string) =>
135 makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId }).pipe(
136 Effect.provideService(AgentScope, scope),
137 Effect.provideService(HostProcess.Platform, "linux"),
138 Effect.map((command) => {
139 assert(ChildProcess.isStandardCommand(command));
140 return command;
141 }),
142 );
143​
144describe("AgentScope service", () => {
145 it.effect("labels a thread from its newest scope until its next session clears it", () =>
146 withFakeSystemd(({ scope, units }) =>
147 Effect.gen(function* () {
148 const first = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
149 units.set(unitOf(first), { activeState: "failed", result: "oom-kill" });
150 const second = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
151 units.set(unitOf(second), { activeState: "active", result: "success" });
152 expect(yield* scope.oomKilled("a")).toBe(false);
153​
154 units.set(unitOf(second), { activeState: "failed", result: "oom-kill" });
155 expect(yield* scope.oomKilled("a")).toBe(true);
156 units.delete(unitOf(second));
157 expect(yield* scope.oomKilled("a")).toBe(true);
158​
159 yield* scope.clear("a");
160 expect(yield* scope.oomKilled("a")).toBe(false);
161 }),
162 ),
163 );
164​
165 it.effect(
166 "keeps shared Codex scopes running without attributing their OOM to the launch thread",
167 () =>
168 withFakeSystemd(({ scope, units, calls }) =>
169 Effect.gen(function* () {
170 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
171 expect(agent.args).toContain("--property=OOMPolicy=stop");
172 units.set(unitOf(agent), { activeState: "failed", result: "oom-kill" });
173 expect(yield* scope.oomKilled("a")).toBe(true);
174​
175 const codex = yield* launchCodex(scope, "a");
176 expect(codex.args).toContain("--property=OOMPolicy=continue");
177 expect(codex.args).not.toContain("--property=OOMPolicy=stop");
178 expect(codex.args).toContain("--property=TimeoutStopSec=10s");
179 expect(codex.args).toContain("--collect");
180 units.set(unitOf(codex), { activeState: "active", result: "success" });
181 expect(yield* scope.oomKilled("a")).toBe(false);
182 units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" });
183 expect(yield* scope.oomKilled("a")).toBe(false);
184 expect(
185 calls.filter(([, verb, unit]) => verb === "show" && unit === unitOf(codex)),
186 ).toEqual([]);
187 }),
188 ),
189 );
190​
191 it.effect("labels the shared Codex app-server's OOM kill on systemd without OOMPolicy", () =>
192 withFakeSystemd(
193 ({ scope, units }) =>
194 Effect.gen(function* () {
195 const codex = yield* launchCodex(scope, "a");
196 units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" });
197 expect(yield* scope.oomKilled("a")).toBe(true);
198 expect(codex.args.filter((arg) => arg.includes("OOMPolicy"))).toEqual([]);
199 expect(codex.args).not.toContain("--collect");
200 expect(codex.args).toContain("--property=TimeoutStopSec=10s");
201 }),
202 { oomPolicy: false },
203 ),
204 );
205​
206 it.effect("keeps a running scope while hundreds of other threads launch", () =>
207 withFakeSystemd(({ scope, units }) =>
208 Effect.gen(function* () {
209 const live = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "live" });
210 units.set(unitOf(live), { activeState: "active", result: "success" });
211 for (let index = 0; index < 600; index++) {
212 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: `other-${index}` });
213 }
214 units.set(unitOf(live), { activeState: "failed", result: "oom-kill" });
215 expect(yield* scope.oomKilled("live")).toBe(true);
216 }),
217 ),
218 );
219​
220 it.effect("stops agents a killed server left before the first launch", () =>
221 withFakeSystemd(({ scope, units, calls, stateDir }) =>
222 Effect.gen(function* () {
223 units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
224 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
225 const stops = calls.filter(([, verb]) => verb === "stop");
226 expect(stops).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
227 expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
228 expect(agent.args).toContain("--property=TimeoutStopSec=10s");
229 const terminal = yield* scope.wrap({
230 command: "agent",
231 args: [],
232 name: "terminal",
233 survivesRestart: true,
234 });
235 expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
236 expect(calls.filter(([, verb]) => verb === "stop")).toHaveLength(1);
237 }),
238 ),
239 );
240​
241 it.effect("requests OOM continuation only for shared scopes when systemd supports it", () =>
242 withFakeSystemd(({ scope }) =>
243 Effect.gen(function* () {
244 const server = yield* scope.wrap({ command: "agent", args: [], name: "s", shared: true });
245 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
246 expect(server.args.filter((arg) => arg.startsWith("--property=OOMPolicy="))).toEqual([
247 "--property=OOMPolicy=continue",
248 ]);
249 expect(agent.args.filter((arg) => arg.startsWith("--property=OOMPolicy="))).toEqual([
250 "--property=OOMPolicy=stop",
251 ]);
252 }),
253 ),
254 );
255​
256 it.effect("leaves a quiet slice alone", () =>
257 withFakeSystemd(({ scope, calls }) =>
258 Effect.gen(function* () {
259 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
260 expect(calls.filter(([, verb]) => verb === "stop")).toEqual([]);
261 }),
262 ),
263 );
264});