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

agentScope.test.ts

192 lines7.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 { describe, expect, it } from "@effect/vitest";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import { ChildProcessSpawner } from "effect/process";
12​
13import * as ServerConfig from "../config.ts";
14import * as ProcessRunner from "../processRunner.ts";
15import {
16 agentSliceMemoryLimits,
17 classifyScope,
18 make,
19 ownedAgentSlice,
20 type ScopeState,
21} from "./agentScope.ts";
22​
23const GiB = 1024 ** 3;
24​
25const running: ScopeState = {
26 loadState: "loaded",
27 activeState: "active",
28 result: "success",
29 oomKills: 0,
30 populated: true,
31};
32​
33describe("classifyScope", () => {
34 it("reports an OOM kill only once systemd records it", () => {
35 expect(classifyScope({ ...running, activeState: "failed", result: "oom-kill" })).toBe(
36 "oom-killed",
37 );
38 expect(classifyScope({ ...running, oomKills: 1 })).toBe("stopping");
39 expect(classifyScope({ ...running, populated: false })).toBe("stopping");
40 expect(classifyScope({ ...running, activeState: "deactivating" })).toBe("stopping");
41 });
42​
43 it("does not wait on a live agent or a scope that ended for another reason", () => {
44 expect(classifyScope(running)).toBe("running");
45 expect(classifyScope({ ...running, activeState: "inactive", populated: undefined })).toBe(
46 "gone",
47 );
48 expect(classifyScope({ ...running, loadState: "not-found", activeState: "inactive" })).toBe(
49 "gone",
50 );
51 });
52});
53​
54describe("agentSliceMemoryLimits", () => {
55 it("leaves 6 GB before throttling and 4 GB before a kill on large machines", () => {
56 expect(agentSliceMemoryLimits(64 * GiB)).toEqual({ high: 58 * GiB, max: 60 * GiB });
57 });
58​
59 it("still gives agents most of a small machine", () => {
60 expect(agentSliceMemoryLimits(8 * GiB)).toEqual({ high: 4 * GiB, max: 6 * GiB });
61 });
62});
63​
64const withFakeSystemd = <A, E>(
65 body: (input: {
66 readonly scope: Effect.Success<typeof make>;
67 readonly units: Map<string, { activeState: string; result: string }>;
68 readonly calls: ReadonlyArray<ReadonlyArray<string>>;
69 readonly stateDir: string;
70 }) => Effect.Effect<A, E>,
71) =>
72 Effect.gen(function* () {
73 const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
74 for (const name of ["systemd-run", "systemctl", "agent"]) {
75 NodeFS.writeFileSync(NodePath.join(bin, name), "", { mode: 0o755 });
76 }
77 const units = new Map<string, { activeState: string; result: string }>();
78 const calls: Array<ReadonlyArray<string>> = [];
79 const output = (stdout: string): ProcessRunner.ProcessRunOutput => ({
80 stdout,
81 stderr: "",
82 code: ChildProcessSpawner.ExitCode(0),
83 timedOut: false,
84 stdoutTruncated: false,
85 stderrTruncated: false,
86 stdoutInvalidUtf8: false,
87 stderrInvalidUtf8: false,
88 });
89 const runner = ProcessRunner.ProcessRunner.of({
90 run: ({ args }) =>
91 Effect.sync(() => {
92 calls.push(args);
93 const [, verb, unit = ""] = args;
94 if (verb === "reset-failed") units.delete(unit);
95 if (verb !== "show") return output("");
96 const state = units.get(unit);
97 return output(
98 state === undefined
99 ? "LoadState=not-found\nActiveState=inactive\nResult=success\n"
100 : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n`,
101 );
102 }),
103 });
104 const scope = yield* make.pipe(
105 Effect.provideService(ProcessRunner.ProcessRunner, runner),
106 Effect.provideService(HostProcess.Platform, "linux"),
107 Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }),
108 );
109 const { stateDir } = yield* ServerConfig.ServerConfig;
110 return yield* body({ scope, units, calls, stateDir }).pipe(
111 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))),
112 );
113 }).pipe(
114 Effect.scoped,
115 Effect.provide(
116 ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-scope-" }).pipe(
117 Layer.provideMerge(NodeServices.layer),
118 ),
119 ),
120 );
121​
122const unitOf = (launch: { readonly args: ReadonlyArray<string> }) =>
123 launch.args.find((arg) => arg.startsWith("--unit="))?.slice("--unit=".length) ?? "";
124​
125const sliceOf = (launch: { readonly args: ReadonlyArray<string> }) =>
126 launch.args.find((arg) => arg.startsWith("--slice="))?.slice("--slice=".length) ?? "";
127​
128describe("AgentScope service", () => {
129 it.effect("labels a thread from its newest scope until its next session clears it", () =>
130 withFakeSystemd(({ scope, units }) =>
131 Effect.gen(function* () {
132 const first = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
133 units.set(unitOf(first), { activeState: "failed", result: "oom-kill" });
134 const second = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
135 units.set(unitOf(second), { activeState: "active", result: "success" });
136 expect(yield* scope.oomKilled("a")).toBe(false);
137​
138 units.set(unitOf(second), { activeState: "failed", result: "oom-kill" });
139 expect(yield* scope.oomKilled("a")).toBe(true);
140 units.delete(unitOf(second));
141 expect(yield* scope.oomKilled("a")).toBe(true);
142​
143 yield* scope.clear("a");
144 expect(yield* scope.oomKilled("a")).toBe(false);
145 }),
146 ),
147 );
148​
149 it.effect("keeps a running scope while hundreds of other threads launch", () =>
150 withFakeSystemd(({ scope, units }) =>
151 Effect.gen(function* () {
152 const live = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "live" });
153 units.set(unitOf(live), { activeState: "active", result: "success" });
154 for (let index = 0; index < 600; index++) {
155 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: `other-${index}` });
156 }
157 units.set(unitOf(live), { activeState: "failed", result: "oom-kill" });
158 expect(yield* scope.oomKilled("live")).toBe(true);
159 }),
160 ),
161 );
162​
163 it.effect("stops agents a killed server left before the first launch", () =>
164 withFakeSystemd(({ scope, units, calls, stateDir }) =>
165 Effect.gen(function* () {
166 units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
167 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
168 const stops = calls.filter(([, verb]) => verb === "stop");
169 expect(stops).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
170 expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
171 expect(agent.args).toContain("--property=TimeoutStopSec=10s");
172 const terminal = yield* scope.wrap({
173 command: "agent",
174 args: [],
175 name: "terminal",
176 survivesRestart: true,
177 });
178 expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
179 expect(calls.filter(([, verb]) => verb === "stop")).toHaveLength(1);
180 }),
181 ),
182 );
183​
184 it.effect("leaves a quiet slice alone", () =>
185 withFakeSystemd(({ scope, calls }) =>
186 Effect.gen(function* () {
187 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
188 expect(calls.filter(([, verb]) => verb === "stop")).toEqual([]);
189 }),
190 ),
191 );
192});