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