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

agentScope.test.ts

145 lines6.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 { describe, expect, it } from "@effect/vitest";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import * as Effect from "effect/Effect";
10import { ChildProcessSpawner } from "effect/process";
11​
12import * as ProcessRunner from "../processRunner.ts";
13import { agentSliceMemoryLimits, classifyScope, make, type ScopeState } from "./agentScope.ts";
14​
15const GiB = 1024 ** 3;
16​
17const running: ScopeState = {
18 loadState: "loaded",
19 activeState: "active",
20 result: "success",
21 oomKills: 0,
22 populated: true,
23};
24​
25describe("classifyScope", () => {
26 it("reports an OOM kill only once systemd records it", () => {
27 expect(classifyScope({ ...running, activeState: "failed", result: "oom-kill" })).toBe(
28 "oom-killed",
29 );
30 // The agent pipe can close before systemd handles the kill.
31 expect(classifyScope({ ...running, oomKills: 1 })).toBe("stopping");
32 expect(classifyScope({ ...running, populated: false })).toBe("stopping");
33 expect(classifyScope({ ...running, activeState: "deactivating" })).toBe("stopping");
34 });
35​
36 it("does not wait on a live agent or a scope that ended for another reason", () => {
37 expect(classifyScope(running)).toBe("running");
38 expect(classifyScope({ ...running, activeState: "inactive", populated: undefined })).toBe(
39 "gone",
40 );
41 expect(classifyScope({ ...running, loadState: "not-found", activeState: "inactive" })).toBe(
42 "gone",
43 );
44 });
45});
46​
47describe("agentSliceMemoryLimits", () => {
48 it("leaves 6 GB before throttling and 4 GB before a kill on large machines", () => {
49 expect(agentSliceMemoryLimits(64 * GiB)).toEqual({ high: 58 * GiB, max: 60 * GiB });
50 });
51​
52 it("still gives agents most of a small machine", () => {
53 expect(agentSliceMemoryLimits(8 * GiB)).toEqual({ high: 4 * GiB, max: 6 * GiB });
54 });
55});
56​
57// Runs the real service against a fake user manager. `units` holds the
58// ActiveState and Result that `systemctl show` reports for each scope.
59const withFakeSystemd = <A, E>(
60 body: (input: {
61 readonly scope: Effect.Success<typeof make>;
62 readonly units: Map<string, { activeState: string; result: string }>;
63 }) => Effect.Effect<A, E>,
64) =>
65 Effect.gen(function* () {
66 const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
67 for (const name of ["systemd-run", "systemctl", "agent"]) {
68 NodeFS.writeFileSync(NodePath.join(bin, name), "", { mode: 0o755 });
69 }
70 const units = new Map<string, { activeState: string; result: string }>();
71 const output = (stdout: string): ProcessRunner.ProcessRunOutput => ({
72 stdout,
73 stderr: "",
74 code: ChildProcessSpawner.ExitCode(0),
75 timedOut: false,
76 stdoutTruncated: false,
77 stderrTruncated: false,
78 stdoutInvalidUtf8: false,
79 stderrInvalidUtf8: false,
80 });
81 const runner = ProcessRunner.ProcessRunner.of({
82 run: ({ args }) =>
83 Effect.sync(() => {
84 const [, verb, unit = ""] = args;
85 if (verb === "reset-failed") units.delete(unit);
86 if (verb !== "show") return output("");
87 const state = units.get(unit);
88 return output(
89 state === undefined
90 ? "LoadState=not-found\nActiveState=inactive\nResult=success\n"
91 : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n`,
92 );
93 }),
94 });
95 const scope = yield* make.pipe(
96 Effect.provideService(ProcessRunner.ProcessRunner, runner),
97 Effect.provideService(HostProcess.Platform, "linux"),
98 Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }),
99 );
100 return yield* body({ scope, units }).pipe(
101 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))),
102 );
103 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
104​
105const unitOf = (launch: { readonly args: ReadonlyArray<string> }) =>
106 launch.args.find((arg) => arg.startsWith("--unit="))?.slice("--unit=".length) ?? "";
107​
108describe("AgentScope service", () => {
109 it.effect("labels a thread from its newest scope until its next session clears it", () =>
110 withFakeSystemd(({ scope, units }) =>
111 Effect.gen(function* () {
112 const first = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
113 units.set(unitOf(first), { activeState: "failed", result: "oom-kill" });
114 const second = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
115 units.set(unitOf(second), { activeState: "active", result: "success" });
116 // The older scope was OOM-killed, but the newest one is still running.
117 expect(yield* scope.oomKilled("a")).toBe(false);
118​
119 units.set(unitOf(second), { activeState: "failed", result: "oom-kill" });
120 expect(yield* scope.oomKilled("a")).toBe(true);
121 // A retried failure reads the same, even after the failed unit is reset.
122 units.delete(unitOf(second));
123 expect(yield* scope.oomKilled("a")).toBe(true);
124​
125 // The next session may run without a scope, for example on Cursor.
126 yield* scope.clear("a");
127 expect(yield* scope.oomKilled("a")).toBe(false);
128 }),
129 ),
130 );
131​
132 it.effect("keeps a running scope while hundreds of other threads launch", () =>
133 withFakeSystemd(({ scope, units }) =>
134 Effect.gen(function* () {
135 const live = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "live" });
136 units.set(unitOf(live), { activeState: "active", result: "success" });
137 for (let index = 0; index < 600; index++) {
138 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: `other-${index}` });
139 }
140 units.set(unitOf(live), { activeState: "failed", result: "oom-kill" });
141 expect(yield* scope.oomKilled("live")).toBe(true);
142 }),
143 ),
144 );
145});