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