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

agentScope.test.ts

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