Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { afterEach, assert, describe, expect, it } from "@effect/vitest";
3import type * as NodeOS from "node:os";
4import * as AgentScope from "@t3tools/shared/AgentScope";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as PlatformError from "effect/PlatformError";
11import * as Stream from "effect/Stream";
12import { ChildProcessSpawner } from "effect/process";
13import * as TestClock from "effect/testing/TestClock";
14import { vi } from "vite-plus/test";
15
16import * as Config from "../config.ts";
17import * as HostResources from "./HostResources.ts";
18import * as NativeTelemetryClient from "./NativeTelemetryClient.ts";
19
20// An 8-CPU host; every cpus() call advances each CPU by 100 ms at `host.busy` utilization.
21const host = vi.hoisted(() => ({
22 busy: 0,
23 reads: 0,
24 load: 0,
25 disk: { bavail: 512 * 1024 * 1024, blocks: 1024 * 1024 * 1024, bsize: 512 },
26 worktreesDisk: null as { bavail: number; blocks: number; bsize: number } | null,
27 hangStatfs: false,
28 statfsCalls: 0,
29}));
30vi.mock("node:fs/promises", async (importOriginal) => ({
31 ...(await importOriginal<object>()),
32 statfs: (path: string) => {
33 host.statfsCalls++;
34 if (host.hangStatfs) return new Promise(() => {});
35 const disk = path.endsWith("/worktrees") && host.worktreesDisk ? host.worktreesDisk : host.disk;
36 return Promise.resolve({ ...disk });
37 },
38}));
39vi.mock("node:os", async (importOriginal) => {
40 const actual = await importOriginal<typeof NodeOS>();
41 return {
42 ...actual,
43 totalmem: () => 4 * 1024 ** 3,
44 loadavg: () => [host.load, host.load, host.load],
45 availableParallelism: () => 8,
46 cpus: () => {
47 const elapsed = 100 * host.reads++;
48 const times = {
49 user: elapsed * host.busy,
50 nice: 0,
51 sys: 0,
52 idle: elapsed * (1 - host.busy),
53 irq: 0,
54 };
55 return Array.from({ length: 8 }, () => ({ model: "test", speed: 1, times }));
56 },
57 };
58});
59const setup = (busy = 0) => {
60 host.busy = busy;
61 host.reads = 0;
62 host.load = 0;
63 host.disk = { bavail: 512 * 1024 * 1024, blocks: 1024 * 1024 * 1024, bsize: 512 };
64 host.worktreesDisk = null;
65 host.hangStatfs = false;
66 host.statfsCalls = 0;
67};
68
69afterEach(() => {
70 host.hangStatfs = false;
71});
72
73const layerConfig = Config.layerTest(process.cwd(), { prefix: "host-resources-" }).pipe(
74 Layer.provide(NodeServices.layer),
75);
76
77const GiB = 1024 ** 3;
78const MiB = 1024 ** 2;
79const cgroup = "/sys/fs/cgroup/t3.slice/server.scope";
80const unlimitedCgroup = {
81 "/proc/self/cgroup": ["0::/t3.slice/server.scope\n"],
82 "/proc/meminfo": [`MemTotal: ${4 * 1024 * 1024} kB\nMemAvailable: ${2 * 1024 * 1024} kB\n`],
83 [`${cgroup}/cpu.max`]: ["max 100000\n"],
84 [`${cgroup}/cpu.stat`]: ["usage_usec 5000000\n"],
85 [`${cgroup}/memory.max`]: ["max\n"],
86 [`${cgroup}/memory.current`]: [`${600 * MiB}\n`],
87 [`${cgroup}/memory.stat`]: [`anon ${450 * MiB}\ninactive_file ${100 * MiB}\n`],
88};
89
90// Each path serves its values in order and repeats the last one.
91const linuxHost = (files: Record<string, ReadonlyArray<string>>) => {
92 const reads = new Map<string, number>();
93 return HostResources.layer.pipe(
94 Layer.provide(
95 Layer.mergeAll(
96 FileSystem.layerNoop({
97 readFileString: (path) => {
98 const values = files[path];
99 if (!values) {
100 return Effect.fail(
101 PlatformError.systemError({
102 _tag: "NotFound",
103 module: "FileSystem",
104 method: "readFileString",
105 pathOrDescriptor: path,
106 }),
107 );
108 }
109 const index = reads.get(path) ?? 0;
110 reads.set(path, index + 1);
111 return Effect.succeed(values[Math.min(index, values.length - 1)]!);
112 },
113 }),
114 Layer.succeed(HostProcess.Platform, "linux"),
115 NativeTelemetryClient.layerTest(),
116 layerConfig,
117 Layer.succeed(
118 ChildProcessSpawner.ChildProcessSpawner,
119 ChildProcessSpawner.make(() => Effect.die("HostResources spawned on linux")),
120 ),
121 ),
122 ),
123 );
124};
125
126const read = Effect.gen(function* () {
127 const host = yield* HostResources.HostResources;
128 const fiber = yield* Effect.forkChild(host.read);
129 yield* TestClock.adjust("200 millis");
130 return yield* Fiber.join(fiber);
131});
132
133describe("HostResources.layer", () => {
134 it.effect("reports the CPU quota and usage of the server's cgroup", () =>
135 Effect.gen(function* () {
136 setup();
137 const snapshot = yield* read;
138
139 // One CPU of quota, 150 ms of it used during the 200 ms sample.
140 assert.strictEqual(snapshot.cpuCount, 1);
141 assert.strictEqual(snapshot.cpuUtilization, 0.75);
142 }).pipe(
143 Effect.provide(
144 linuxHost({
145 ...unlimitedCgroup,
146 [`${cgroup}/cpu.max`]: ["100000 100000\n"],
147 [`${cgroup}/cpu.stat`]: [
148 "usage_usec 5000000\nuser_usec 4000000\nsystem_usec 1000000\n",
149 "usage_usec 5150000\nuser_usec 4100000\nsystem_usec 1050000\n",
150 ],
151 }),
152 ),
153 ),
154 );
155
156 it.effect("reports memory against the server cgroup's memory.max", () =>
157 Effect.gen(function* () {
158 setup();
159 const snapshot = yield* read;
160
161 assert.strictEqual(snapshot.totalMemoryBytes, GiB);
162 // 600 MiB charged, of which 100 MiB is reclaimable page cache.
163 assert.strictEqual(snapshot.availableMemoryBytes, GiB - 500 * MiB);
164 }).pipe(
165 Effect.provide(
166 linuxHost({
167 ...unlimitedCgroup,
168 [`${cgroup}/memory.max`]: [`${GiB}\n`],
169 }),
170 ),
171 ),
172 );
173
174 it.effect("counts a busy host against an idle, quota-limited server cgroup", () =>
175 Effect.gen(function* () {
176 // Agents in sibling cgroups keep the host 90% busy; the server's own cgroup is idle.
177 setup(0.9);
178 const snapshot = yield* read;
179
180 assert.strictEqual(snapshot.cpuCount, 2);
181 // Only 0.8 of 8 host CPUs are free, which is 60% of the 2-CPU quota in use.
182 assert.closeTo(snapshot.cpuUtilization ?? Number.NaN, 0.6, 1e-9);
183 }).pipe(
184 Effect.provide(
185 linuxHost({
186 ...unlimitedCgroup,
187 [`${cgroup}/cpu.max`]: ["200000 100000\n"],
188 }),
189 ),
190 ),
191 );
192
193 it.effect("samples the CPUs the server is pinned to by id, not by os.cpus() index", () =>
194 Effect.gen(function* () {
195 setup();
196 const snapshot = yield* read;
197
198 assert.strictEqual(snapshot.cpuCount, 1);
199 assert.strictEqual(snapshot.cpuUtilization, 1);
200 }).pipe(
201 Effect.provide(
202 linuxHost({
203 ...unlimitedCgroup,
204 "/proc/self/status": ["Name:\tnode\nCpus_allowed_list:\t4\n"],
205 // CPU 1 is offline; the server's CPU 4 is saturated, everything else is idle.
206 "/proc/stat": [0, 100].map((elapsed) =>
207 [0, 2, 3, 4, 5, 6, 7]
208 .map((id) =>
209 id === 4
210 ? `cpu${id} ${elapsed} 0 0 0 0 0 0 0`
211 : `cpu${id} 0 0 0 ${elapsed} 0 0 0 0`,
212 )
213 .join("\n"),
214 ),
215 }),
216 ),
217 ),
218 );
219
220 it.effect("keeps host memory when the cgroup's memory.current is unreadable", () =>
221 Effect.gen(function* () {
222 setup();
223 const snapshot = yield* read;
224
225 assert.strictEqual(snapshot.totalMemoryBytes, 4 * GiB);
226 assert.strictEqual(snapshot.availableMemoryBytes, 2 * GiB);
227 }).pipe(
228 Effect.provide(
229 linuxHost({
230 ...unlimitedCgroup,
231 [`${cgroup}/memory.max`]: [`${GiB}\n`],
232 [`${cgroup}/memory.current`]: [""],
233 }),
234 ),
235 ),
236 );
237
238 it.effect("keeps host values when the cgroup has no limits", () =>
239 Effect.gen(function* () {
240 setup(0.25);
241 const snapshot = yield* read;
242
243 assert.strictEqual(snapshot.cpuCount, 8);
244 assert.closeTo(snapshot.cpuUtilization ?? Number.NaN, 0.25, 1e-9);
245 assert.strictEqual(snapshot.availableMemoryBytes, 2 * GiB);
246 }).pipe(Effect.provide(linuxHost(unlimitedCgroup))),
247 );
248
249 it.effect("falls back to host load when the cgroup's cpu.stat is unreadable", () =>
250 Effect.gen(function* () {
251 setup(0.9);
252 const snapshot = yield* read;
253
254 assert.strictEqual(snapshot.cpuCount, 2);
255 assert.closeTo(snapshot.cpuUtilization ?? Number.NaN, 0.6, 1e-9);
256 }).pipe(
257 Effect.provide(
258 linuxHost({
259 ...unlimitedCgroup,
260 [`${cgroup}/cpu.max`]: ["200000 100000\n"],
261 [`${cgroup}/cpu.stat`]: [""],
262 }),
263 ),
264 ),
265 );
266});
267
268const quiet: HostResources.PressureSample = {
269 memorySome: 0,
270 memoryFull: 0,
271 agentsMemoryFull: 0,
272 memoryAvailableShare: 0.6,
273 darwinMemoryLevel: null,
274 cpuSome: 0,
275 ioFull: 0,
276 loadPerCpu: null,
277 cpuIdle: null,
278 diskFreeBytes: 500 * GiB,
279 diskTotalBytes: 1000 * GiB,
280};
281const unread: HostResources.PressureSample = {
282 memorySome: null,
283 memoryFull: null,
284 agentsMemoryFull: null,
285 memoryAvailableShare: null,
286 darwinMemoryLevel: null,
287 cpuSome: null,
288 ioFull: null,
289 loadPerCpu: null,
290 cpuIdle: null,
291 diskFreeBytes: null,
292 diskTotalBytes: null,
293};
294const levels = (overrides: Partial<HostResources.PressureLevels>) => ({
295 ...HostResources.CALM,
296 ...overrides,
297});
298
299describe("pressure levels", () => {
300 it("reads PSI averages", () => {
301 const text =
302 "some avg10=12.50 avg60=3.10 avg300=0.80 total=1\nfull avg10=4.00 avg60=1.00 avg300=0.10 total=1\n";
303 expect(HostResources.psiAverage(text, "some", "avg10")).toBe(12.5);
304 expect(HostResources.psiAverage(text, "full", "avg60")).toBe(1);
305 expect(HostResources.psiAverage("", "full", "avg10")).toBeNull();
306 });
307
308 it("keeps small agents listed while rounding large ones coarsely", () => {
309 expect(HostResources.roundCoarsely(27_648_000)).toBe(28 * MiB);
310 expect(HostResources.roundCoarsely(3_200 * MiB + 1)).toBe(3_328 * MiB);
311 expect(HostResources.roundCoarsely(0)).toBe(0);
312 });
313
314 it("keeps a listed agent's small CPU use above zero cores", () => {
315 const agents = [
316 { threadId: null, agent: "codex", memoryBytes: 900 * MiB, cpuCores: 3.2 },
317 { threadId: null, agent: "preview-browser", memoryBytes: 400 * MiB, cpuCores: 0.2 },
318 ];
319 expect(HostResources.heaviestAgents(agents, "cpu").map((agent) => agent.cpuCores)).toEqual([
320 3, 0.5,
321 ]);
322 });
323
324 it("ranks agents by exact size, so close ones cannot push out the largest", () => {
325 // All four round to 3,328 MiB; the largest comes last.
326 const agents = [3_201, 3_202, 3_203, 3_204].map((size) => ({
327 threadId: null,
328 agent: `agent-${size}`,
329 memoryBytes: size * MiB,
330 cpuCores: 5_000 - size,
331 }));
332 expect(HostResources.heaviestAgents(agents, "memory").map((agent) => agent.agent)).toEqual([
333 "agent-3204",
334 "agent-3203",
335 "agent-3202",
336 ]);
337 expect(HostResources.heaviestAgents(agents, "cpu").map((agent) => agent.agent)).toEqual([
338 "agent-3201",
339 "agent-3202",
340 "agent-3203",
341 ]);
342 });
343
344 it.each([
345 { name: "a quiet host", previous: {}, sample: quiet, expected: {} },
346 {
347 name: "throttled agents, as in the 4 h freeze",
348 previous: {},
349 sample: { ...quiet, memorySome: 30, memoryFull: 3, agentsMemoryFull: 85 },
350 expected: { memory: "severe" },
351 },
352 {
353 name: "brief memory stalls",
354 previous: {},
355 sample: { ...quiet, memorySome: 12, memoryAvailableShare: 0.05 },
356 expected: { memory: "elevated" },
357 },
358 {
359 name: "severe memory pressure easing but not gone",
360 previous: { memory: "severe" },
361 sample: { ...quiet, memoryFull: 5, memoryAvailableShare: 0.05 },
362 expected: { memory: "severe" },
363 },
364 {
365 name: "severe memory pressure easing to stalls",
366 previous: { memory: "severe" },
367 sample: { ...quiet, memoryFull: 1, memoryAvailableShare: 0.05 },
368 expected: { memory: "elevated" },
369 },
370 {
371 name: "elevated memory pressure fading below its entry threshold",
372 previous: { memory: "elevated" },
373 sample: { ...quiet, memorySome: 5, memoryAvailableShare: 0.05 },
374 expected: { memory: "elevated" },
375 },
376 {
377 name: "elevated memory pressure gone",
378 previous: { memory: "elevated" },
379 sample: { ...quiet, memorySome: 1, memoryAvailableShare: 0.05 },
380 expected: {},
381 },
382 {
383 name: "macOS critical memory pressure",
384 previous: {},
385 sample: { ...unread, darwinMemoryLevel: 4 },
386 expected: { memory: "severe" },
387 },
388 {
389 name: "a busy CPU whose work rarely waits",
390 previous: {},
391 sample: { ...quiet, cpuSome: 10 },
392 expected: {},
393 },
394 {
395 name: "work waiting for a CPU most of the last minute",
396 previous: {},
397 sample: { ...quiet, cpuSome: 70 },
398 expected: { cpu: "severe" },
399 },
400 {
401 name: "a load average three times the CPUs, without PSI",
402 previous: {},
403 sample: { ...unread, loadPerCpu: 3.2, cpuIdle: 0.02 },
404 expected: { cpu: "severe" },
405 },
406 {
407 name: "a load average three times the CPUs while they sit mostly idle",
408 previous: {},
409 sample: { ...unread, loadPerCpu: 3.2, cpuIdle: 0.85 },
410 expected: {},
411 },
412 {
413 name: "an overload easing while the CPUs stay busy",
414 previous: { cpu: "severe" },
415 sample: { ...unread, loadPerCpu: 1.3, cpuIdle: 0.2 },
416 expected: { cpu: "severe" },
417 },
418 {
419 name: "an overload whose CPUs went mostly idle, as on macOS under memory pressure",
420 previous: { cpu: "severe" },
421 sample: { ...unread, loadPerCpu: 1.2, cpuIdle: 0.85 },
422 expected: {},
423 },
424 {
425 name: "storage stalling every task",
426 previous: {},
427 sample: { ...quiet, ioFull: 12 },
428 expected: { io: "elevated" },
429 },
430 {
431 name: "a disk under 20 GiB free",
432 previous: {},
433 sample: { ...quiet, diskFreeBytes: 15 * GiB },
434 expected: { disk: "elevated" },
435 },
436 {
437 name: "a disk under 5 GiB free",
438 previous: {},
439 sample: { ...quiet, diskFreeBytes: 4 * GiB },
440 expected: { disk: "severe" },
441 },
442 {
443 name: "a nearly full disk just back above its threshold",
444 previous: { disk: "severe" },
445 sample: { ...quiet, diskFreeBytes: 6 * GiB },
446 expected: { disk: "severe" },
447 },
448 {
449 name: "a small disk judged by its share free",
450 previous: {},
451 sample: { ...quiet, diskFreeBytes: 12 * GiB, diskTotalBytes: 100 * GiB },
452 expected: { disk: "elevated" },
453 },
454 {
455 name: "a sample where nothing could be read",
456 previous: { memory: "severe", cpu: "elevated", io: "elevated", disk: "severe" },
457 sample: unread,
458 expected: { memory: "severe", cpu: "elevated", io: "elevated", disk: "severe" },
459 },
460 ] as const)("reads $name", ({ previous, sample, expected }) => {
461 expect(HostResources.nextPressureLevels(levels(previous), sample)).toEqual(levels(expected));
462 });
463
464 it("does not say memory is slowing agents while only a job outside T3 stalls at its own limit", () => {
465 // Host-wide `full` tracks one cgroup throttled at its own limit while the agents never wait.
466 const sample = { ...quiet, memorySome: 35, memoryFull: 33, agentsMemoryFull: 0 };
467 expect(HostResources.nextPressureLevels(levels({}), sample).memory).not.toBe("severe");
468 });
469
470 it("does not call the CPU overloaded while only a job outside T3 waits on its own cpu.max", () => {
471 // Host CPU PSI counts tasks held back by one cgroup's quota while most cores sit idle.
472 const capped = { ...quiet, cpuSome: 59.5, cpuIdle: 0.78 };
473 expect(HostResources.nextPressureLevels(levels({}), capped).cpu).toBe("none");
474 expect(HostResources.nextPressureLevels(levels({ cpu: "severe" }), capped).cpu).toBe("none");
475 });
476
477 it("stops blaming memory once the agents recover while a job outside T3 keeps stalling", () => {
478 const outside = { ...quiet, memorySome: 35, memoryFull: 33, memoryAvailableShare: 0.18 };
479 let current = HostResources.nextPressureLevels(levels({}), {
480 ...outside,
481 agentsMemoryFull: 25,
482 });
483 expect(current.memory).toBe("severe");
484 for (let sample = 0; sample < 3; sample++) {
485 current = HostResources.nextPressureLevels(current, outside);
486 }
487 expect(current.memory).toBe("none");
488 });
489});
490
491describe("HostResources pressure on Linux", () => {
492 const scope = "/agents/owned/t3code-claude-0123abcd.scope";
493 const pressured = (overrides: Record<string, ReadonlyArray<string>>) =>
494 linuxHost({
495 "/proc/pressure/memory": ["some avg10=0.00 avg60=0.00\nfull avg10=0.00 avg60=0.00\n"],
496 "/proc/pressure/cpu": ["some avg10=90.00 avg60=75.00\nfull avg10=0.00 avg60=0.00\n"],
497 "/proc/pressure/io": ["some avg10=0.00 avg60=0.00\nfull avg10=0.00 avg60=0.00\n"],
498 "/sys/fs/cgroup/agents/memory.pressure": ["some avg10=0.00\nfull avg10=0.00\n"],
499 [`/sys/fs/cgroup${scope}/memory.current`]: [`${900 * MiB}\n`],
500 [`/sys/fs/cgroup${scope}/cpu.stat`]: ["usage_usec 0\n", "usage_usec 15000000\n"],
501 ...overrides,
502 }).pipe(
503 Layer.provide(
504 Layer.succeed(AgentScope.AgentScope, {
505 ...AgentScope.AgentScope.defaultValue(),
506 controlGroups: Effect.succeed({
507 slice: "/agents",
508 scopes: [{ path: scope, threadId: "thread-1", agent: "claude" }],
509 }),
510 }),
511 ),
512 );
513
514 // A level CPU PSI would raise is checked against CPU time, read twice 200 ms apart at first.
515 const readPressure = Effect.gen(function* () {
516 const fiber = yield* Effect.forkChild((yield* HostResources.HostResources).readPressure);
517 yield* TestClock.adjust("200 millis");
518 return yield* Fiber.join(fiber);
519 });
520
521 it.effect("names the agents using the most CPU while work waits for one", () =>
522 Effect.gen(function* () {
523 setup(0.98);
524 const hostResources = yield* HostResources.HostResources;
525 const samples = yield* Stream.take(hostResources.pressure, 2).pipe(
526 Stream.runCollect,
527 Effect.forkScoped,
528 );
529 yield* TestClock.adjust("6 seconds");
530 const [first, second] = yield* Fiber.join(samples);
531 expect(first).toMatchObject({ cpu: "severe", memory: "none", disk: "none" });
532 // One reading cannot tell CPU use; the next one, 15 s of CPU in 5 s, can.
533 expect(first?.heaviestAgents).toEqual([]);
534 expect(second?.heaviestAgents).toEqual([
535 { threadId: "thread-1", agent: "claude", memoryBytes: 960 * MiB, cpuCores: 3 },
536 ]);
537 }).pipe(Effect.provide(pressured({}))),
538 );
539
540 it.effect("stamps when each severe episode began, so a new one is told apart", () =>
541 Effect.gen(function* () {
542 setup(0.98);
543 const starts: Array<number | undefined> = [];
544 for (let sample = 0; sample < 4; sample++) {
545 yield* TestClock.adjust("5 seconds");
546 starts.push((yield* readPressure).severeSince?.cpu);
547 }
548 expect(starts).toEqual([5_200, 5_200, undefined, 20_800]);
549 }).pipe(
550 Effect.provide(
551 pressured({
552 "/proc/pressure/cpu": [
553 "some avg10=90.00 avg60=75.00\nfull avg10=0.00 avg60=0.00\n",
554 "some avg10=90.00 avg60=75.00\nfull avg10=0.00 avg60=0.00\n",
555 "some avg10=0.00 avg60=0.00\nfull avg10=0.00 avg60=0.00\n",
556 "some avg10=90.00 avg60=75.00\nfull avg10=0.00 avg60=0.00\n",
557 ],
558 }),
559 ),
560 ),
561 );
562
563 it.effect("starts a new episode after a gap nobody sampled", () =>
564 Effect.gen(function* () {
565 setup(0.98);
566 yield* TestClock.adjust("5 seconds");
567 const first = (yield* readPressure).severeSince?.cpu;
568 yield* TestClock.adjust("1 minute");
569 const afterGap = (yield* readPressure).severeSince?.cpu;
570 expect([first, afterGap]).toEqual([5_200, 65_400]);
571 }).pipe(Effect.provide(pressured({}))),
572 );
573
574 it.effect("ignores CPU pressure from a cgroup outside T3 while the CPUs sit mostly idle", () =>
575 Effect.gen(function* () {
576 setup(0.25);
577 expect((yield* readPressure).cpu).toBe("none");
578 yield* TestClock.adjust("5 seconds");
579 expect((yield* readPressure).cpu).toBe("none");
580 }).pipe(Effect.provide(pressured(unlimitedCgroup))),
581 );
582
583 // A 2-CPU limit on an 8-CPU host: /proc/stat is the host's and stays mostly idle.
584 it.effect.each([
585 { capped: "the server's own cgroup", at: cgroup },
586 { capped: "a cgroup above the server's unlimited one", at: "/sys/fs/cgroup/t3.slice" },
587 ])("keeps the CPU warning while $capped is the one at its cpu.max", ({ at }) =>
588 Effect.gen(function* () {
589 setup(0.25);
590 expect((yield* readPressure).cpu).toBe("severe");
591 yield* TestClock.adjust("5 seconds");
592 expect((yield* readPressure).cpu).toBe("severe");
593 }).pipe(
594 Effect.provide(
595 pressured({
596 ...unlimitedCgroup,
597 [`${at}/cpu.max`]: ["200000 100000\n"],
598 // Both CPUs of quota used: 0.4 s in the first 200 ms, 10 s in the next 5 s.
599 [`${at}/cpu.stat`]: ["usage_usec 0\n", "usage_usec 400000\n", "usage_usec 10400000\n"],
600 }),
601 ),
602 ),
603 );
604
605 it.effect("reports a nearly full disk with its free space", () =>
606 Effect.gen(function* () {
607 setup();
608 host.disk = { bavail: 3 * 1024 * 1024 * 2, blocks: 1024 * 1024 * 1024, bsize: 512 };
609 const pressure = yield* (yield* HostResources.HostResources).readPressure;
610 expect(pressure).toMatchObject({ disk: "severe", diskFreeBytes: 3 * GiB });
611 }).pipe(
612 Effect.provide(
613 pressured({
614 "/proc/pressure/cpu": ["some avg10=0.00 avg60=0.00\nfull avg10=0.00 avg60=0.00\n"],
615 }),
616 ),
617 ),
618 );
619
620 it.effect("warns about a small volume that is nearly full beside a large roomy one", () =>
621 Effect.gen(function* () {
622 setup();
623 // 1 GiB of 10 GiB is only elevated; 2 GiB of 1 TiB is severe.
624 host.disk = { bavail: 2 * 1024 * 1024, blocks: 20 * 1024 * 1024, bsize: 512 };
625 host.worktreesDisk = { bavail: 4 * 1024 * 1024, blocks: 2048 * 1024 * 1024, bsize: 512 };
626 const pressure = yield* (yield* HostResources.HostResources).readPressure;
627 expect(pressure).toMatchObject({ disk: "severe", diskFreeBytes: 2 * GiB });
628 }).pipe(
629 Effect.provide(
630 pressured({
631 "/proc/pressure/cpu": ["some avg10=0.00 avg60=0.00\nfull avg10=0.00 avg60=0.00\n"],
632 }),
633 ),
634 ),
635 );
636
637 it.effect("keeps one statfs in flight per directory while a mount hangs", () =>
638 Effect.gen(function* () {
639 setup();
640 host.hangStatfs = true;
641 const hostResources = yield* HostResources.HostResources;
642 for (let sample = 0; sample < 3; sample++) {
643 const fiber = yield* Effect.forkChild(hostResources.readPressure);
644 yield* TestClock.adjust("1 second");
645 yield* Fiber.join(fiber);
646 }
647 // The data and worktree directories, once each.
648 expect(host.statfsCalls).toBe(2);
649 }).pipe(
650 Effect.provide(
651 pressured({
652 "/proc/pressure/cpu": ["some avg10=0.00 avg60=0.00\nfull avg10=0.00 avg60=0.00\n"],
653 }),
654 ),
655 ),
656 );
657
658 it.effect("keeps agent-slice memory pressure while host memory PSI is unreadable", () =>
659 Effect.gen(function* () {
660 setup();
661 const hostResources = yield* HostResources.HostResources;
662 let pressure = yield* hostResources.readPressure;
663 for (let sample = 0; sample < 7; sample++) pressure = yield* hostResources.readPressure;
664 expect(pressure.memory).toBe("severe");
665 }).pipe(
666 Effect.provide(
667 pressured({
668 "/proc/pressure/memory": [""],
669 "/proc/pressure/cpu": ["some avg10=0.00 avg60=0.00\nfull avg10=0.00 avg60=0.00\n"],
670 "/sys/fs/cgroup/agents/memory.pressure": ["some avg10=90.00\nfull avg10=85.00\n"],
671 }),
672 ),
673 ),
674 );
675});
676
677const answersOnce = (level: number) => {
678 let answered = false;
679 return Effect.sync(() => {
680 if (answered) return null;
681 answered = true;
682 return level;
683 });
684};
685
686const layerDarwin = (memoryPressureLevel: Effect.Effect<number | null>) =>
687 HostResources.layer.pipe(
688 Layer.provide(
689 Layer.mergeAll(
690 NativeTelemetryClient.layerTest({ memoryPressureLevel }),
691 Layer.succeed(HostProcess.Platform, "darwin"),
692 FileSystem.layerNoop({}),
693 layerConfig,
694 // Under pressure a new process may never start, so sampling must not spawn one.
695 Layer.succeed(
696 ChildProcessSpawner.ChildProcessSpawner,
697 ChildProcessSpawner.make(() => Effect.die("sampling spawned a process")),
698 ),
699 ),
700 ),
701 );
702
703describe("HostResources pressure on macOS", () => {
704 it.effect("reads the level from the running sidecar instead of spawning sysctl", () =>
705 Effect.gen(function* () {
706 setup();
707 const hostResources = yield* HostResources.HostResources;
708 const [first] = yield* Stream.take(hostResources.pressure, 1).pipe(Stream.runCollect);
709 expect(first?.memory).toBe("severe");
710 const later = yield* Stream.take(hostResources.pressure, 2).pipe(
711 Stream.runCollect,
712 Effect.forkScoped,
713 );
714 // The sidecar stops answering: the warning must not outlive the pressure.
715 yield* TestClock.adjust("30 seconds");
716 expect((yield* Fiber.join(later)).map((pressure) => pressure.memory)).toEqual([
717 "severe",
718 "none",
719 ]);
720 }).pipe(Effect.provide(layerDarwin(answersOnce(4)))),
721 );
722
723 it.effect("reads a high load average as overload only while the CPUs are busy", () =>
724 Effect.gen(function* () {
725 setup(0.15);
726 host.load = 32;
727 const hostResources = yield* HostResources.HostResources;
728 yield* hostResources.readPressure;
729 expect((yield* hostResources.readPressure).cpu).toBe("none");
730 host.busy = 0.98;
731 yield* hostResources.readPressure;
732 expect((yield* hostResources.readPressure).cpu).toBe("severe");
733 }).pipe(Effect.provide(layerDarwin(Effect.succeed(1)))),
734 );
735});