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

agentScope.test.ts

594 lines23.6 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 { symlinksSupported } from "@t3tools/shared/testing/symlinks";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Logger from "effect/Logger";
15import { ChildProcess, ChildProcessSpawner } from "effect/process";
16import { vi } from "vite-plus/test";
17​
18import * as ServerConfig from "../config.ts";
19import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
20import * as ProcessRunner from "../processRunner.ts";
21import * as ProviderProcesses from "./providerProcesses.ts";
22import { classifyScope, make, ownedAgentSlice, type ScopeState } from "./agentScope.ts";
23​
24const GiB = 1024 ** 3;
25const memory = vi.hoisted(() => ({ total: 16 * 1024 ** 3, swapKb: 2 * 1024 ** 2 }));
26vi.mock("node:os", async (importOriginal) => ({
27 ...(await importOriginal<typeof import("node:os")>()),
28 totalmem: () => memory.total,
29}));
30​
31const running: ScopeState = {
32 loadState: "loaded",
33 activeState: "active",
34 result: "success",
35 oomKills: 0,
36 populated: true,
37};
38​
39describe("classifyScope", () => {
40 it("reports an OOM kill only once systemd records it", () => {
41 expect(classifyScope({ ...running, activeState: "failed", result: "oom-kill" })).toBe(
42 "oom-killed",
43 );
44 expect(classifyScope({ ...running, oomKills: 1 })).toBe("stopping");
45 expect(classifyScope({ ...running, populated: false })).toBe("stopping");
46 expect(classifyScope({ ...running, activeState: "deactivating" })).toBe("stopping");
47 });
48});
49​
50interface FakeUnit {
51 activeState: string;
52 result: string;
53 controlGroup?: string;
55​
56const withFakeSystemd = <A, E>(
57 body: (input: {
58 readonly scope: Effect.Success<typeof make>;
59 readonly units: Map<string, FakeUnit>;
60 readonly calls: ReadonlyArray<ReadonlyArray<string>>;
61 readonly failingVerbs: Set<string>;
62 readonly stateDir: string;
63 readonly cgroupRoot: string;
64 }) => Effect.Effect<A, E>,
65 // A user manager older than systemd 253 rejects OOMPolicy on scopes.
66 {
67 oomPolicy = true,
68 stopFails = false,
69 leftovers = false,
70 liveOwner = false,
71 noBinSh = false,
72 noScopes = false,
73 }: {
74 readonly oomPolicy?: boolean;
75 readonly stopFails?: boolean;
76 readonly leftovers?: boolean;
77 readonly liveOwner?: boolean;
78 readonly noBinSh?: boolean;
79 readonly noScopes?: boolean;
80 } = {},
81) =>
82 Effect.gen(function* () {
83 const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
84 for (const name of ["systemd-run", "systemctl", "agent", "sh"]) {
85 NodeFS.writeFileSync(NodePath.join(bin, name), "", { mode: 0o755 });
86 }
87 const cgroupRoot = NodePath.join(bin, "cgroup");
88 const units = new Map<string, FakeUnit>();
89 const calls: Array<ReadonlyArray<string>> = [];
90 const failingVerbs = new Set<string>();
91 const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({
92 stdout,
93 stderr: "",
94 code: ChildProcessSpawner.ExitCode(code),
95 timedOut: false,
96 stdoutTruncated: false,
97 stderrTruncated: false,
98 stdoutInvalidUtf8: false,
99 stderrInvalidUtf8: false,
100 });
101 const runner = ProcessRunner.ProcessRunner.of({
102 run: ({ args }) =>
103 Effect.sync(() => {
104 calls.push(args);
105 if (!oomPolicy && args.some((arg) => arg.startsWith("--property=OOMPolicy="))) {
106 return output("", 1);
107 }
108 const [, verb, unit = ""] = args;
109 if (failingVerbs.has(verb!)) return output("", 1);
110 if (stopFails && verb === "stop") {
111 return {
112 ...output(""),
113 stderr: `Failed to stop ${args.at(-1)}: Unit not loaded.`,
114 code: ChildProcessSpawner.ExitCode(5),
115 };
116 }
117 if (verb === "reset-failed") units.delete(unit);
118 if (verb !== "show") return output("");
119 const state = units.get(unit);
120 return output(
121 state === undefined
122 ? "LoadState=not-found\nActiveState=inactive\nResult=success\n"
123 : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n` +
124 `ControlGroup=${state.controlGroup ?? ""}\n`,
125 );
126 }),
127 });
128 const fileSystem = yield* FileSystem.FileSystem;
129 const { stateDir } = yield* ServerConfig.ServerConfig;
130 if (leftovers) {
131 units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
132 }
133 const scope = yield* make.pipe(
134 Effect.provideService(ProviderProcesses.ProviderProcesses, { hasOtherLiveOwner: liveOwner }),
135 Effect.provideService(ProcessRunner.ProcessRunner, runner),
136 Effect.provideService(HostProcess.Platform, "linux"),
137 Effect.provideService(
138 HostProcess.Environment,
139 noScopes ? { PATH: bin } : { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" },
140 ),
141 Effect.provideService(FileSystem.FileSystem, {
142 ...fileSystem,
143 exists: (path) =>
144 noBinSh && path === "/bin/sh" ? Effect.succeed(false) : fileSystem.exists(path),
145 readFileString: (path, encoding) =>
146 path === "/proc/meminfo"
147 ? Effect.sync(() => `MemTotal: 16384 kB\nSwapTotal: ${memory.swapKb} kB\n`)
148 : fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding),
149 readDirectory: (path, options) =>
150 fileSystem.readDirectory(path.replace("/sys/fs/cgroup", cgroupRoot), options),
151 writeFileString: (path, data, options) =>
152 fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options),
153 }),
154 );
155 return yield* body({ scope, units, calls, failingVerbs, stateDir, cgroupRoot }).pipe(
156 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))),
157 );
158 }).pipe(
159 Effect.scoped,
160 Effect.provide(
161 ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-scope-" }).pipe(
162 Layer.provideMerge(NodeServices.layer),
163 ),
164 ),
165 );
166​
167const unitOf = (launch: Pick<ChildProcess.StandardCommand, "args">) =>
168 launch.args
169 .map(String)
170 .find((arg) => arg.startsWith("--unit="))
171 ?.slice("--unit=".length) ?? "";
172​
173const sliceOf = (launch: { readonly args: ReadonlyArray<string> }) =>
174 launch.args.find((arg) => arg.startsWith("--slice="))?.slice("--slice=".length) ?? "";
175​
176/** An active scope as systemd and the kernel report it, with the agent itself gone. */
177const exitedAgent = (
178 units: Map<string, FakeUnit>,
179 cgroupRoot: string,
180 unit: string,
181 { populated, oomKills }: { readonly populated: boolean; readonly oomKills: number | undefined },
182) => {
183 const controlGroup = `/${unit}`;
184 NodeFS.mkdirSync(NodePath.join(cgroupRoot, controlGroup), { recursive: true });
185 NodeFS.writeFileSync(
186 NodePath.join(cgroupRoot, controlGroup, "cgroup.events"),
187 `populated ${populated ? 1 : 0}\nfrozen 0\n`,
188 );
189 // An undefined count leaves memory.events unreadable.
190 if (oomKills !== undefined) {
191 NodeFS.writeFileSync(
192 NodePath.join(cgroupRoot, controlGroup, "memory.events"),
193 `low 0\nhigh 0\nmax 0\noom ${oomKills}\noom_kill ${oomKills}\noom_group_kill 0\n`,
194 );
195 }
196 units.set(unit, { activeState: "active", result: "success", controlGroup });
197};
198​
199const stopsOf = (calls: ReadonlyArray<ReadonlyArray<string>>) =>
200 calls.filter(([, verb]) => verb === "stop");
201const launchCodex = (
202 scope: Effect.Success<typeof make>,
203 threadId: string,
204 env?: NodeJS.ProcessEnv,
205) =>
206 makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId, env }).pipe(
207 Effect.provideService(AgentScope, scope),
208 Effect.provideService(HostProcess.Platform, "linux"),
209 Effect.map((command) => {
210 assert(ChildProcess.isStandardCommand(command));
211 return command;
212 }),
213 );
214​
215describe("AgentScope service", () => {
216 it.effect("launches through sh from PATH when the host has no /bin/sh", () =>
217 Effect.gen(function* () {
218 const withScopes = yield* withFakeSystemd(({ scope }) =>
219 scope.wrap({ command: "agent", args: [], name: "t" }),
220 );
221 expect(withScopes.command).toBe("/bin/sh");
222 const scoped = yield* withFakeSystemd(
223 ({ scope }) => scope.wrap({ command: "agent", args: [], name: "t" }),
224 { noBinSh: true },
225 );
226 const unscoped = yield* withFakeSystemd(
227 ({ scope }) => scope.wrap({ command: "agent", args: [], name: "t" }),
228 { noBinSh: true, noScopes: true },
229 );
230 for (const launch of [scoped, unscoped]) {
231 expect(NodePath.basename(launch.command)).toBe("sh");
232 expect(launch.command).not.toBe("/bin/sh");
233 expect(NodePath.basename(String(launch.args.at(-1)))).toBe("agent");
234 }
235 expect(unscoped.args).not.toContain("--scope");
236 }),
237 );
238​
239 it.effect("labels a thread from its newest scope until its next session clears it", () =>
240 withFakeSystemd(({ scope, units }) =>
241 Effect.gen(function* () {
242 const first = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
243 units.set(unitOf(first), { activeState: "failed", result: "oom-kill" });
244 const second = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
245 units.set(unitOf(second), { activeState: "active", result: "success" });
246 expect(yield* scope.oomKilled("a")).toBe(false);
247​
248 units.set(unitOf(second), { activeState: "failed", result: "oom-kill" });
249 expect(yield* scope.oomKilled("a")).toBe(true);
250 units.delete(unitOf(second));
251 expect(yield* scope.oomKilled("a")).toBe(true);
252​
253 yield* scope.clear("a");
254 expect(yield* scope.oomKilled("a")).toBe(false);
255 }),
256 ),
257 );
258​
259 it.effect(
260 "keeps shared Codex scopes running without attributing their OOM to the launch thread",
261 () =>
262 withFakeSystemd(({ scope, units, calls }) =>
263 Effect.gen(function* () {
264 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
265 expect(agent.args).toContain("--property=OOMPolicy=stop");
266 units.set(unitOf(agent), { activeState: "failed", result: "oom-kill" });
267 expect(yield* scope.oomKilled("a")).toBe(true);
268​
269 const executable = String(agent.args.at(-1));
270 const codex = yield* launchCodex(scope, "a", {
271 PATH: NodePath.relative(process.cwd(), NodePath.dirname(executable)),
272 });
273 // Anchored to the cwd for systemd-run, with its ".." kept; it names the same file.
274 const anchored = String(codex.args.at(-2));
275 expect(NodePath.isAbsolute(anchored)).toBe(true);
276 expect(NodePath.resolve(anchored)).toBe(executable);
277 expect(codex.args).toContain("--property=OOMPolicy=continue");
278 expect(codex.args).not.toContain("--property=OOMPolicy=stop");
279 expect(codex.args).toContain("--property=TimeoutStopSec=10s");
280 expect(codex.args).toContain("--collect");
281 units.set(unitOf(codex), { activeState: "active", result: "success" });
282 expect(yield* scope.oomKilled("a")).toBe(false);
283 units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" });
284 expect(yield* scope.oomKilled("a")).toBe(false);
285 expect(
286 calls.filter(([, verb, unit]) => verb === "show" && unit === unitOf(codex)),
287 ).toEqual([]);
288 }),
289 ),
290 );
291​
292 it.effect.skipIf(!symlinksSupported)(
293 "keeps a symlinked parent in absolute and relative executable paths",
294 () =>
295 withFakeSystemd(({ scope }) =>
296 Effect.gen(function* () {
297 const plain = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "s" });
298 const bin = NodePath.dirname(String(plain.args.at(-1)));
299 NodeFS.mkdirSync(NodePath.join(bin, "real", "sub"), { recursive: true });
300 NodeFS.writeFileSync(NodePath.join(bin, "real", "agent"), "", { mode: 0o755 });
301 NodeFS.symlinkSync(NodePath.join(bin, "real", "sub"), NodePath.join(bin, "link"));
302 // The kernel follows the link before "..", so this names real/agent, not bin/agent.
303 const command = `${NodePath.join(bin, "link")}/../agent`;
304 const wrapped = yield* scope.wrap({ command, args: [], name: "t", threadId: "s" });
305 expect(wrapped.args.at(-1)).toBe(command);
306 // A relative path is anchored to the cwd the same way, without collapsing "..".
307 const relative = `${NodePath.relative(process.cwd(), NodePath.join(bin, "link"))}/../agent`;
308 const anchored = yield* scope.wrap({
309 command: relative,
310 args: [],
311 name: "t",
312 threadId: "s",
313 });
314 expect(anchored.args.at(-1)).toBe(`${process.cwd()}${NodePath.sep}${relative}`);
315 }),
316 ),
317 );
318​
319 it.effect.each([{ oomPolicy: true }, { oomPolicy: false }])(
320 "Force stop kills a thread's own scope but never a shared Codex scope (OOM policy $oomPolicy)",
321 ({ oomPolicy }) =>
322 withFakeSystemd(
323 ({ scope, units, calls, cgroupRoot }) =>
324 Effect.gen(function* () {
325 const agent = yield* scope.wrap({
326 command: "agent",
327 args: [],
328 name: "t",
329 threadId: "a",
330 });
331 exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });
332 const codex = yield* launchCodex(scope, "b");
333 exitedAgent(units, cgroupRoot, unitOf(codex), { populated: true, oomKills: 0 });
334​
335 expect(yield* scope.kill("a")).toBe(true);
336 expect(
337 NodeFS.readFileSync(NodePath.join(cgroupRoot, unitOf(agent), "cgroup.kill"), "utf8"),
338 ).toBe("1");
339 expect(yield* scope.kill("b")).toBe(false);
340 expect(NodeFS.existsSync(NodePath.join(cgroupRoot, unitOf(codex), "cgroup.kill"))).toBe(
341 false,
342 );
343 expect(calls.filter(([, verb]) => verb === "kill")).toEqual([]);
344 }),
345 { oomPolicy },
346 ),
347 );
348​
349 it.effect("reports each live agent scope's cgroup with the thread that owns it", () =>
350 withFakeSystemd(({ scope, units, cgroupRoot, stateDir }) =>
351 Effect.gen(function* () {
352 expect(yield* scope.controlGroups).toBeUndefined();
353 units.set("app-t3code-agents.slice", {
354 activeState: "active",
355 result: "success",
356 controlGroup: "/agents",
357 });
358 const agent = yield* scope.wrap({
359 command: "agent",
360 args: [],
361 name: "claude",
362 threadId: "a",
363 });
364 const codex = yield* launchCodex(scope, "b");
365 const owned = NodePath.join("/agents", ownedAgentSlice(stateDir));
366 for (const unit of [unitOf(agent), unitOf(codex)]) {
367 NodeFS.mkdirSync(NodePath.join(cgroupRoot, owned, unit), { recursive: true });
368 }
369​
370 const groups = yield* scope.controlGroups;
371 expect(groups?.slice).toBe("/agents");
372 expect(groups?.scopes.toSorted((a, b) => a.agent.localeCompare(b.agent))).toEqual([
373 { path: NodePath.join(owned, unitOf(agent)), threadId: "a", agent: "claude" },
374 { path: NodePath.join(owned, unitOf(codex)), threadId: undefined, agent: "codex" },
375 ]);
376 }),
377 ),
378 );
379​
380 it.effect("keeps a running scope while hundreds of other threads launch", () =>
381 withFakeSystemd(({ scope, units }) =>
382 Effect.gen(function* () {
383 const live = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "live" });
384 units.set(unitOf(live), { activeState: "active", result: "success" });
385 for (let index = 0; index < 600; index++) {
386 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: `other-${index}` });
387 }
388 units.set(unitOf(live), { activeState: "failed", result: "oom-kill" });
389 expect(yield* scope.oomKilled("live")).toBe(true);
390 }),
391 ),
392 );
393​
394 it.effect("delegates every agent scope so rootless containers can manage their cgroups", () =>
395 withFakeSystemd(({ scope }) =>
396 Effect.gen(function* () {
397 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
398 const codex = yield* launchCodex(scope, "a");
399 const terminal = yield* scope.wrap({
400 command: "agent",
401 args: [],
402 name: "terminal",
403 survivesRestart: true,
404 });
405 for (const launch of [agent, codex, terminal]) {
406 expect(launch.args).toContain("--property=Delegate=yes");
407 }
408 }),
409 ),
410 );
411​
412 it.effect("caps agent memory and yields CPU, disk, and tasks to the server", () =>
413 withFakeSystemd(({ scope, calls }) =>
414 Effect.gen(function* () {
415 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
416 const setProperties = calls.filter(([, verb]) => verb === "set-property");
417 expect(setProperties).toEqual([
418 [
419 "--user",
420 "set-property",
421 "--runtime",
422 "app-t3code-agents.slice",
423 expect.stringMatching(/^MemoryHigh=\d+$/),
424 expect.stringMatching(/^MemoryMax=\d+$/),
425 ],
426 [
427 "--user",
428 "set-property",
429 "--runtime",
430 "app-t3code.slice",
431 "CPUWeight=10",
432 "IOWeight=10",
433 "TasksMax=25%",
434 ],
435 ]);
436 }),
437 ),
438 );
439​
440 it.effect("follows a live memory or swap change at the next launch", () => {
441 memory.total = 16 * GiB;
442 memory.swapKb = 2 * 1024 ** 2;
443 return withFakeSystemd(({ scope, calls, failingVerbs }) =>
444 Effect.gen(function* () {
445 const launch = scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
446 const memoryLimits = () =>
447 calls
448 .filter(
449 ([, verb, , slice]) => verb === "set-property" && slice === "app-t3code-agents.slice",
450 )
451 .map((args) => args.slice(4));
452 yield* launch;
453 yield* launch;
454 expect(memoryLimits()).toEqual([[`MemoryHigh=${10 * GiB}`, `MemoryMax=${12 * GiB}`]]);
455​
456 // A VM balloon or `pct set --memory` grows RAM while the server keeps running.
457 memory.total = 22 * GiB;
458 failingVerbs.add("set-property");
459 yield* launch;
460 yield* launch;
461 failingVerbs.delete("set-property");
462 yield* launch;
463 yield* launch;
464 const grown = [`MemoryHigh=${16 * GiB}`, `MemoryMax=${18 * GiB}`];
465 expect(memoryLimits()).toEqual([
466 [`MemoryHigh=${10 * GiB}`, `MemoryMax=${12 * GiB}`],
467 grown,
468 grown,
469 grown,
470 ]);
471​
472 // Without swap, MemoryHigh only throttles; MemoryMax must OOM-kill the runaway.
473 memory.swapKb = 0;
474 yield* launch;
475 expect(memoryLimits().at(-1)).toEqual(["MemoryHigh=infinity", `MemoryMax=${18 * GiB}`]);
476 memory.swapKb = 2 * 1024 ** 2;
477 }),
478 );
479 });
480​
481 it.effect("stops agents a killed server left before startup completes", () =>
482 withFakeSystemd(
483 ({ scope, calls, stateDir }) =>
484 Effect.gen(function* () {
485 expect(stopsOf(calls)).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
486 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
487 expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
488 expect(agent.args).toContain("--property=TimeoutStopSec=10s");
489 const terminal = yield* scope.wrap({
490 command: "agent",
491 args: [],
492 name: "terminal",
493 survivesRestart: true,
494 });
495 expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
496 expect(stopsOf(calls)).toHaveLength(1);
497 }),
498 { leftovers: true },
499 ),
500 );
501​
502 it.effect("leaves the slice to another live server sharing this home", () =>
503 withFakeSystemd(({ calls }) => Effect.sync(() => expect(stopsOf(calls)).toEqual([])), {
504 leftovers: true,
505 liveOwner: true,
506 }),
507 );
508​
509 it.effect("stops leftover processes only in an active agent scope", () =>
510 withFakeSystemd(({ scope, units, calls, cgroupRoot }) =>
511 Effect.gen(function* () {
512 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
513 const unit = unitOf(agent);
514 expect(agent.unit).toBe(unit);
515​
516 yield* scope.stop("session-2.scope");
517 expect(calls.some((args) => args.includes("session-2.scope"))).toBe(false);
518 yield* scope.stop(unit);
519 exitedAgent(units, cgroupRoot, unit, { populated: false, oomKills: 0 });
520 yield* scope.stop(unit);
521 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 0 });
522 units.get(unit)!.activeState = "deactivating";
523 yield* scope.stop(unit);
524 expect(stopsOf(calls)).toEqual([]);
525​
526 units.get(unit)!.activeState = "active";
527 yield* scope.stop(unit);
528 expect(stopsOf(calls)).toEqual([["--user", "stop", "--no-block", unit]]);
529 expect(yield* scope.oomKilled("a")).toBe(false);
530 }),
531 ),
532 );
533​
534 it.effect.each([true, false])(
535 "cleans up an OOM exit without losing its diagnosis (OOMPolicy=%s)",
536 (oomPolicy) =>
537 withFakeSystemd(
538 ({ scope, units, calls, cgroupRoot }) =>
539 Effect.gen(function* () {
540 const agent = yield* scope.wrap({
541 command: "agent",
542 args: [],
543 name: "t",
544 threadId: "a",
545 });
546 const unit = unitOf(agent);
547 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: undefined });
548 yield* scope.stop(unit);
549 expect(stopsOf(calls)).toEqual(
550 oomPolicy ? [] : [["--user", "stop", "--no-block", unit]],
551 );
552​
553 // The kernel records the kill before systemd records the OOM result.
554 exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 1 });
555 yield* scope.stop(unit);
556 expect(stopsOf(calls)).toHaveLength(oomPolicy ? 0 : 2);
557​
558 if (oomPolicy) {
559 units.set(unit, { activeState: "failed", result: "oom-kill" });
560 expect(yield* scope.oomKilled("a")).toBe(true);
561 units.delete(unit);
562 expect(yield* scope.oomKilled("a")).toBe(true);
563 }
564 }),
565 { oomPolicy },
566 ),
567 );
568​
569 it.effect("reports failed daemon cleanup without failing session teardown", () => {
570 const warnings: Array<unknown> = [];
571 const logger = Logger.make(({ message }) => {
572 warnings.push(message);
573 });
574 return withFakeSystemd(
575 ({ scope, units, cgroupRoot }) =>
576 Effect.gen(function* () {
577 const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
578 exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });
579 yield* scope.stop(unitOf(agent));
580 expect(warnings.flat()).toContain("Could not stop an exited agent's scope");
581 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
582 { stopFails: true },
583 );
584 });
585​
586 it.effect("leaves a quiet slice alone", () =>
587 withFakeSystemd(({ scope, calls }) =>
588 Effect.gen(function* () {
589 yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
590 expect(calls.filter(([, verb]) => verb === "stop")).toEqual([]);
591 }),
592 ),
593 );
594});