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

HostResources.ts

704 lines28.0 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect has no free-space query.
2import * as NodeFSP from "node:fs/promises";
3import * as NodeOS from "node:os";
4import type {
5 HostPressure,
6 HostPressureAgent,
7 HostPressureLevel,
8 HostPressureSevereSince,
9 HostResourcesSnapshot,
10} from "@t3tools/contracts";
11import { CALM_HOST_PRESSURE, HOST_PRESSURE_KINDS, ThreadId } from "@t3tools/contracts";
12import * as AgentScope from "@t3tools/shared/AgentScope";
13import * as HostProcess from "@t3tools/shared/HostProcess";
14import * as Cache from "effect/Cache";
15import * as Clock from "effect/Clock";
16import * as Context from "effect/Context";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Ref from "effect/Ref";
22import * as Schedule from "effect/Schedule";
23import * as Stream from "effect/Stream";
24import { ChildProcess, ChildProcessSpawner } from "effect/process";
25​
26import * as Config from "../config.ts";
27import * as NativeTelemetryClient from "./NativeTelemetryClient.ts";
28​
29export class HostResources extends Context.Service<
30 HostResources,
31 {
32 readonly read: Effect.Effect<HostResourcesSnapshot>;
33 /** Changes only; samples while someone listens. */
34 readonly pressure: Stream.Stream<HostPressure>;
35 /** The latest pressure, sampling once when nobody listens. */
36 readonly readPressure: Effect.Effect<HostPressure>;
37 }
38>()("t3/resourceTelemetry/HostResources") {}
39​
40// Linux CPU list syntax, as in Cpus_allowed_list: "0-3,8,10-11".
41function parseCpuList(list: string): ReadonlySet<number> | null {
42 const cpus = new Set<number>();
43 for (const range of list.split(",")) {
44 const match = /^(\d+)(?:-(\d+))?$/.exec(range.trim());
45 if (!match) return null;
46 for (let cpu = Number(match[1]); cpu <= Number(match[2] ?? match[1]); cpu++) cpus.add(cpu);
47 }
48 return cpus;
50​
51// os.cpus() compacts online CPUs, so its indices are not CPU ids; /proc/stat lines are keyed.
52function pinnedCpu(stat: string, allowed: ReadonlySet<number>) {
53 const cpu = { idle: 0, total: 0, count: 0 };
54 for (const [, id, fields] of stat.matchAll(/^cpu(\d+) (.+)$/gm)) {
55 if (!allowed.has(Number(id))) continue;
56 const counters = (fields ?? "").trim().split(/\s+/).map(Number);
57 const at = (index: number) => counters[index] ?? 0;
58 // user nice system idle iowait irq softirq steal
59 const idle = at(3) + at(4);
60 cpu.idle += idle;
61 cpu.total += idle + at(0) + at(1) + at(2) + at(5) + at(6) + at(7);
62 cpu.count++;
63 }
64 return cpu.count > 0 ? cpu : null;
66​
67function readCpu() {
68 const cpus = NodeOS.cpus();
69 const cpu = cpus.reduce(
70 (sum, { times }) => ({
71 idle: sum.idle + times.idle,
72 total: sum.total + times.user + times.nice + times.sys + times.idle + times.irq,
73 }),
74 { idle: 0, total: 0 },
75 );
76 return { ...cpu, count: cpus.length };
78​
79interface CpuLimit {
80 /** CPUs the cgroup's cpu.max allows, and the cgroup's usage_usec. */
81 readonly quota: number | null;
82 readonly usage: number | null;
84​
85/** CPU time so far on the CPUs the server may use, and what its own cgroup has used of its quota. */
86type CpuReading = ReturnType<typeof readCpu> &
87 CpuLimit & {
88 /** Cgroups above the server's that have a cpu.max, by path: their limit holds the server too. */
89 readonly ancestors: ReadonlyMap<string, CpuLimit>;
90 readonly at: number;
91 };
92​
93/**
94 * Share of CPU time idle between two readings. A cgroup at its quota has none left however idle
95 * the host is, so the smallest share among the host, the server's cgroup and those above it counts.
96 */
97function cpuIdleBetween(before: CpuReading | null, after: CpuReading | null): number | null {
98 if (
99 before === null ||
100 after === null ||
101 after.at - before.at > CPU_SAMPLE_MAX_AGE_MS ||
102 before.count !== after.count ||
103 after.total <= before.total ||
104 after.idle < before.idle
105 ) {
106 return null;
107 }
108 const elapsedMicros = (after.at - before.at) * 1000;
109 const idleUnder = (earlier: CpuLimit | undefined, limit: CpuLimit) =>
110 limit.quota === null ||
111 limit.usage === null ||
112 earlier === undefined ||
113 earlier.usage === null ||
114 elapsedMicros <= 0
115 ? 1
116 : 1 - (limit.usage - earlier.usage) / elapsedMicros / Math.min(limit.quota, after.count);
117 return Math.max(
118 0,
119 Math.min(
120 (after.idle - before.idle) / (after.total - before.total),
121 idleUnder(before, after),
122 ...Array.from(after.ancestors, ([path, limit]) =>
123 idleUnder(before.ancestors.get(path), limit),
124 ),
125 ),
126 );
128​
129function darwinAvailableMemory(output: string): number | null {
130 const pageSize = /page size of (\d+) bytes/.exec(output)?.[1];
131 const free = /^Pages free:\s+(\d+)\./m.exec(output)?.[1];
132 const inactive = /^Pages inactive:\s+(\d+)\./m.exec(output)?.[1];
133 const speculative = /^Pages speculative:\s+(\d+)\./m.exec(output)?.[1];
134 if (!pageSize || !free || !inactive || !speculative) return null;
135 // vm_stat excludes speculative from free; add it once, without overlapping purgeable pages.
136 const available = (Number(free) + Number(inactive) + Number(speculative)) * Number(pageSize);
137 return Number.isSafeInteger(available) && Number(pageSize) > 0 ? available : null;
139​
140/** A PSI file's `some` or `full` average over 10 or 60 s, in percent. */
141export function psiAverage(
142 text: string,
143 kind: "some" | "full",
144 window: "avg10" | "avg60",
145): number | null {
146 const value = new RegExp(`^${kind} .*\\b${window}=(\\d+(?:\\.\\d+)?)`, "m").exec(text)?.[1];
147 return value === undefined ? null : Number(value);
149​
150export interface PressureSample {
151 /** Linux PSI avg10 percentages for memory. */
152 readonly memorySome: number | null;
153 readonly memoryFull: number | null;
154 readonly agentsMemoryFull: number | null;
155 /** Linux MemAvailable over MemTotal. */
156 readonly memoryAvailableShare: number | null;
157 /** macOS `kern.memorystatus_vm_pressure_level`: 1 normal, 2 warning, 4 critical. */
158 readonly darwinMemoryLevel: number | null;
159 /** Linux PSI avg60 percentages; a minute, so a build's burst is not an overload. */
160 readonly cpuSome: number | null;
161 readonly ioFull: number | null;
162 /** One-minute load average per CPU, where PSI is missing. */
163 readonly loadPerCpu: number | null;
164 /** Share of CPU time idle since the previous sample. */
165 readonly cpuIdle: number | null;
166 readonly diskFreeBytes: number | null;
167 readonly diskTotalBytes: number | null;
169​
170export interface PressureLevels {
171 readonly memory: HostPressureLevel;
172 readonly cpu: HostPressureLevel;
173 readonly io: HostPressureLevel;
174 readonly disk: HostPressureLevel;
176​
177export const CALM: PressureLevels = { memory: "none", cpu: "none", io: "none", disk: "none" };
178​
179const RANK = { none: 0, elevated: 1, severe: 2 } as const;
180// A level is left only well below where it was entered, so it does not flicker.
181const EXIT_RATIO = 0.4;
182const SATURATED_CPU_IDLE = 0.1;
183const SHORT_MEMORY_SHARE = 0.1;
184const GiB = 1024 ** 3;
185​
186const worst = (levels: ReadonlyArray<HostPressureLevel>): HostPressureLevel =>
187 levels.reduce((left, right) => (RANK[right] > RANK[left] ? right : left), "none");
188​
189function grade(
190 previous: HostPressureLevel,
191 value: number | null,
192 elevated: number,
193 severe: number,
194): HostPressureLevel {
195 if (value === null) return "none";
196 const holds = (level: HostPressureLevel, threshold: number) =>
197 value >= (RANK[previous] >= RANK[level] ? threshold * EXIT_RATIO : threshold);
198 if (holds("severe", severe)) return "severe";
199 return holds("elevated", elevated) ? "elevated" : "none";
201​
202const cpuPsiLevel = (previous: HostPressureLevel, cpuSome: number) =>
203 grade(previous, cpuSome, 25, 60);
204​
205/**
206 * Waiting work counts as CPU overload only while the CPUs are nearly all busy, with the same
207 * hysteresis. Load also counts disk waits, and host PSI also counts a cgroup outside T3 held at
208 * its own cpu.max.
209 */
210function whileCpusBusy(
211 previous: HostPressureLevel,
212 level: HostPressureLevel,
213 idle: number,
214): HostPressureLevel {
215 const busy = (at: HostPressureLevel) =>
216 idle < (RANK[previous] >= RANK[at] ? SATURATED_CPU_IDLE / EXIT_RATIO : SATURATED_CPU_IDLE);
217 if (level === "severe" && busy("severe")) return "severe";
218 return level !== "none" && busy("elevated") ? "elevated" : "none";
220​
221function diskLevel(previous: HostPressureLevel, free: number, total: number): HostPressureLevel {
222 const below = (level: HostPressureLevel, limit: number) =>
223 free < (RANK[previous] >= RANK[level] ? limit * 1.25 : limit);
224 if (below("severe", Math.min(5 * GiB, total * 0.05))) return "severe";
225 return below("elevated", Math.min(20 * GiB, total * 0.15)) ? "elevated" : "none";
227​
228/**
229 * `full` means every task waited. The agents slice is throttled first, so it gets looser
230 * thresholds. Host PSI also rises for a cgroup outside T3 stalled at its own limit, so beside
231 * the slice it counts only while memory is short. An unreadable kind keeps its level.
232 */
233export function nextPressureLevels(
234 previous: PressureLevels,
235 sample: PressureSample,
236): PressureLevels {
237 const memoryRead =
238 sample.memorySome !== null ||
239 sample.memoryFull !== null ||
240 sample.agentsMemoryFull !== null ||
241 sample.darwinMemoryLevel !== null;
242 // No hysteresis: the memory level also follows the agents slice, so it cannot hold this gate open.
243 const hostMemoryCounts =
244 sample.agentsMemoryFull === null ||
245 sample.memoryAvailableShare === null ||
246 sample.memoryAvailableShare < SHORT_MEMORY_SHARE;
247 const memory = memoryRead
248 ? worst([
249 hostMemoryCounts
250 ? grade(previous.memory, sample.memorySome, 10, Number.POSITIVE_INFINITY)
251 : "none",
252 hostMemoryCounts ? grade(previous.memory, sample.memoryFull, 2, 10) : "none",
253 grade(previous.memory, sample.agentsMemoryFull, 5, 20),
254 sample.darwinMemoryLevel === null
255 ? "none"
256 : sample.darwinMemoryLevel >= 4
257 ? "severe"
258 : sample.darwinMemoryLevel >= 2
259 ? "elevated"
260 : "none",
261 ])
262 : previous.memory;
263 const cpu =
264 sample.cpuSome !== null
265 ? sample.cpuIdle === null
266 ? cpuPsiLevel(previous.cpu, sample.cpuSome)
267 : whileCpusBusy(previous.cpu, cpuPsiLevel(previous.cpu, sample.cpuSome), sample.cpuIdle)
268 : sample.loadPerCpu !== null && sample.cpuIdle !== null
269 ? whileCpusBusy(
270 previous.cpu,
271 grade(previous.cpu, sample.loadPerCpu, 1.5, 3),
272 sample.cpuIdle,
273 )
274 : previous.cpu;
275 const io = sample.ioFull === null ? previous.io : grade(previous.io, sample.ioFull, 10, 30);
276 const disk =
277 sample.diskFreeBytes === null || sample.diskTotalBytes === null
278 ? previous.disk
279 : diskLevel(previous.disk, sample.diskFreeBytes, sample.diskTotalBytes);
280 return { memory, cpu, io, disk };
282​
283const PRESSURE_INTERVAL = "5 seconds";
284// Sampling stops while nobody listens; after a longer gap a problem may have cleared and returned.
285const EPISODE_GAP_MS = 30_000;
286const MAX_UNREAD_PRESSURE_SAMPLES = 6;
287const HEAVIEST_AGENT_COUNT = 3;
288const CPU_SAMPLE_MAX_AGE_MS = 30_000;
289​
290/** Up to about an eighth coarser, so ordinary growth does not push an update every sample. */
291export function roundCoarsely(bytes: number): number {
292 if (!Number.isFinite(bytes) || bytes <= 0) return 0;
293 const step = 2 ** Math.max(20, Math.floor(Math.log2(bytes)) - 3);
294 return Math.ceil(bytes / step) * step;
296​
297/** Half a core below two cores, whole cores above; a busy agent never reads as 0 cores. */
298function roundCores(cores: number): number {
299 if (!Number.isFinite(cores) || cores <= 0) return 0;
300 return cores < 2 ? Math.max(0.5, Math.round(cores * 2) / 2) : Math.round(cores);
302​
303/** Ranked by exact size: rounding first would tie close agents and could drop the largest. */
304export function heaviestAgents(
305 agents: ReadonlyArray<HostPressureAgent>,
306 by: "memory" | "cpu",
307): ReadonlyArray<HostPressureAgent> {
308 const size = (agent: HostPressureAgent) =>
309 by === "memory" ? agent.memoryBytes : (agent.cpuCores ?? 0);
310 return agents
311 .filter((agent) => size(agent) > 0)
312 .toSorted((left, right) => size(right) - size(left))
313 .slice(0, HEAVIEST_AGENT_COUNT)
314 .map((agent) => ({
315 ...agent,
316 memoryBytes: roundCoarsely(agent.memoryBytes),
317 cpuCores: agent.cpuCores === null ? null : roundCores(agent.cpuCores),
318 }));
320​
321const CGROUP_ROOT = "/sys/fs/cgroup";
322​
323function cgroupNumber(text: string, pattern: RegExp): number | null {
324 const value = pattern.exec(text)?.[1];
325 return value === undefined ? null : Number(value);
327​
328const make = Effect.fn("makeHostResources")(function* () {
329 const fs = yield* FileSystem.FileSystem;
330 const platform = yield* HostProcess.Platform;
331 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
332 const agentScope = yield* AgentScope.AgentScope;
333 const nativeTelemetry = yield* NativeTelemetryClient.NativeTelemetryClient;
334 const config = yield* Config.ServerConfig;
335 const levels = yield* Ref.make(CALM);
336 const severeSince = yield* Ref.make<HostPressureSevereSince>({});
337 const lastSampledAt = yield* Ref.make<number | null>(null);
338 const unreadSamples = yield* Ref.make({ memory: 0, cpu: 0, io: 0, disk: 0 });
339 const lastHostCpu = yield* Ref.make<CpuReading | null>(null);
340 const lastAgentCpu = yield* Ref.make<{
341 readonly at: number;
342 readonly usage: ReadonlyMap<string, number>;
343 } | null>(null);
344​
345 const readFile = (path: string) => fs.readFileString(path).pipe(Effect.orElseSucceed(() => ""));
346​
347 // cgroup v2 only; the server's own cgroup, which is `/` inside a container.
348 const serverCgroup = Effect.gen(function* () {
349 const path =
350 platform === "linux"
351 ? /^0::(\/.*)$/m.exec(yield* readFile("/proc/self/cgroup"))?.[1]
352 : undefined;
353 return path === undefined ? null : `${CGROUP_ROOT}${path.replace(/\/$/, "")}`;
354 });
355​
356 const readCpuLimit = Effect.fnUntraced(function* (cgroup: string | null) {
357 const cpuMax = cgroup
358 ? /^(\d+) (\d+)$/.exec((yield* readFile(`${cgroup}/cpu.max`)).trim())
359 : null;
360 return {
361 quota: cpuMax ? Number(cpuMax[1]) / Number(cpuMax[2]) : null,
362 usage: cpuMax
363 ? cgroupNumber(yield* readFile(`${cgroup}/cpu.stat`), /^usage_usec (\d+)$/m)
364 : null,
365 } satisfies CpuLimit;
366 });
367​
368 const readServerCpu = Effect.fnUntraced(function* (
369 cgroup: string | null,
370 options?: { readonly ancestors: boolean },
371 ) {
372 // Affinity (cpuset) pins the server to some CPUs; idle CPUs outside it are of no use.
373 const allowedCpus =
374 platform === "linux"
375 ? parseCpuList(
376 /^Cpus_allowed_list:\s*(\S+)$/m.exec(yield* readFile("/proc/self/status"))?.[1] ?? "",
377 )
378 : null;
379 const cpu =
380 (allowedCpus ? pinnedCpu(yield* readFile("/proc/stat"), allowedCpus) : null) ?? readCpu();
381 const ancestors = new Map<string, CpuLimit>();
382 if (cgroup !== null && options?.ancestors) {
383 for (
384 let parent = cgroup.slice(0, cgroup.lastIndexOf("/"));
385 parent.length >= CGROUP_ROOT.length;
386 parent = parent.slice(0, parent.lastIndexOf("/"))
387 ) {
388 const limit = yield* readCpuLimit(parent);
389 if (limit.quota !== null) ancestors.set(parent, limit);
390 }
391 }
392 return {
393 ...cpu,
394 ...(yield* readCpuLimit(cgroup)),
395 ancestors,
396 at: yield* Clock.currentTimeMillis,
397 } satisfies CpuReading;
398 });
399​
400 // libuv cannot cancel a started `statfs`, so a hung mount gets at most one in flight.
401 const pendingStatfs = new Set<string>();
402 const readDiskSpace = (directory: string) =>
403 Effect.promise(() => {
404 if (pendingStatfs.has(directory)) return Promise.resolve(null);
405 pendingStatfs.add(directory);
406 // An unreadable volume is reported as unknown, not as an error.
407 return NodeFSP.statfs(directory)
408 .catch(() => null)
409 .finally(() => pendingStatfs.delete(directory));
410 }).pipe(
411 // A hung network mount must not hold the sample.
412 Effect.timeoutOption("1 second"),
413 Effect.map((stats) =>
414 stats._tag === "Some" && stats.value !== null
415 ? {
416 free: stats.value.bavail * stats.value.bsize,
417 total: stats.value.blocks * stats.value.bsize,
418 }
419 : null,
420 ),
421 );
422​
423 // The volume under the most pressure decides, so a severe small volume is not hidden by a larger one.
424 const diskSpace = Effect.gen(function* () {
425 const previous = (yield* Ref.get(levels)).disk;
426 const volumes = yield* Effect.forEach(
427 [...new Set([config.baseDir, config.worktreesDir])],
428 readDiskSpace,
429 { concurrency: "unbounded" },
430 );
431 const rank = (volume: { free: number; total: number }) =>
432 RANK[diskLevel(previous, volume.free, volume.total)];
433 return volumes.reduce<{ free: number; total: number } | null>(
434 (chosen, volume) =>
435 volume !== null &&
436 (chosen === null ||
437 rank(volume) > rank(chosen) ||
438 (rank(volume) === rank(chosen) && volume.free < chosen.free))
439 ? volume
440 : chosen,
441 null,
442 );
443 });
444​
445 // Untraced: it runs every few seconds while a client listens.
446 const samplePressure = Effect.fnUntraced(function* () {
447 const linux = platform === "linux";
448 const agents = linux ? yield* agentScope.controlGroups : undefined;
449 const memoryPsi = linux ? yield* readFile("/proc/pressure/memory") : "";
450 const cpuPsi = linux ? yield* readFile("/proc/pressure/cpu") : "";
451 const ioPsi = linux ? yield* readFile("/proc/pressure/io") : "";
452 const agentsPsi =
453 agents === undefined ? "" : yield* readFile(`/sys/fs/cgroup${agents.slice}/memory.pressure`);
454 const meminfo = agents === undefined ? "" : yield* readFile("/proc/meminfo");
455 const memoryAvailable = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(meminfo)?.[1];
456 const memoryTotal = /^MemTotal:\s+(\d+)\s+kB$/m.exec(meminfo)?.[1];
457 // The running sidecar reads it: under pressure a newly spawned `sysctl` may never start.
458 const darwinMemoryLevel =
459 platform === "darwin"
460 ? yield* nativeTelemetry.memoryPressureLevel.pipe(Effect.orElseSucceed(() => null))
461 : null;
462 const cpuSome = psiAverage(cpuPsi, "some", "avg60");
463 // Windows reports a zero load average, which would read as calm.
464 const loadPerCpu =
465 cpuSome === null && platform !== "win32"
466 ? NodeOS.loadavg()[0]! / Math.max(1, NodeOS.availableParallelism())
467 : null;
468 const previous = yield* Ref.get(levels);
469 // Host PSI also counts tasks a cgroup outside T3 holds back at its own cpu.max, so a level it
470 // would raise is checked against the CPUs and the quotas the server itself has.
471 const cgroup =
472 cpuSome !== null && cpuPsiLevel(previous.cpu, cpuSome) !== "none"
473 ? yield* serverCgroup
474 : undefined;
475 // Load can far exceed busy CPUs (Linux counts disk waits; a swapping Mac read 9.6 on 8 cores
476 // at 85% idle), so it means work waits for a CPU only while the CPUs are nearly all busy.
477 let hostCpu =
478 loadPerCpu !== null
479 ? {
480 ...readCpu(),
481 quota: null,
482 usage: null,
483 ancestors: new Map<string, CpuLimit>(),
484 at: yield* Clock.currentTimeMillis,
485 }
486 : cgroup !== undefined
487 ? yield* readServerCpu(cgroup, { ancestors: true })
488 : null;
489 let cpuIdle = cpuIdleBetween(yield* Ref.get(lastHostCpu), hostCpu);
490 if (cgroup !== undefined && cpuIdle === null) {
491 // No recent reading to compare with, as on the first sample: take a second one now.
492 const earlier = hostCpu;
493 yield* Effect.sleep("200 millis");
494 hostCpu = yield* readServerCpu(cgroup, { ancestors: true });
495 cpuIdle = cpuIdleBetween(earlier, hostCpu);
496 }
497 yield* Ref.set(lastHostCpu, hostCpu);
498 const disk = yield* diskSpace;
499 const sample: PressureSample = {
500 memorySome: psiAverage(memoryPsi, "some", "avg10"),
501 memoryFull: psiAverage(memoryPsi, "full", "avg10"),
502 agentsMemoryFull: psiAverage(agentsPsi, "full", "avg10"),
503 memoryAvailableShare:
504 memoryAvailable === undefined || memoryTotal === undefined || Number(memoryTotal) === 0
505 ? null
506 : Number(memoryAvailable) / Number(memoryTotal),
507 darwinMemoryLevel,
508 cpuSome,
509 ioFull: psiAverage(ioPsi, "full", "avg60"),
510 loadPerCpu,
511 cpuIdle,
512 diskFreeBytes: disk?.free ?? null,
513 diskTotalBytes: disk?.total ?? null,
514 };
515 const unread = yield* Ref.updateAndGet(unreadSamples, (counts) => ({
516 memory:
517 sample.memorySome === null &&
518 sample.memoryFull === null &&
519 sample.agentsMemoryFull === null &&
520 darwinMemoryLevel === null
521 ? counts.memory + 1
522 : 0,
523 cpu: cpuSome === null && (loadPerCpu === null || cpuIdle === null) ? counts.cpu + 1 : 0,
524 io: sample.ioFull === null ? counts.io + 1 : 0,
525 disk: disk === null ? counts.disk + 1 : 0,
526 }));
527 const graded = nextPressureLevels(previous, sample);
528 // A dead sidecar or a vanished mount must not leave a warning up long after it ended.
529 const next = {
530 memory: unread.memory >= MAX_UNREAD_PRESSURE_SAMPLES ? "none" : graded.memory,
531 cpu: unread.cpu >= MAX_UNREAD_PRESSURE_SAMPLES ? "none" : graded.cpu,
532 io: unread.io >= MAX_UNREAD_PRESSURE_SAMPLES ? "none" : graded.io,
533 disk: unread.disk >= MAX_UNREAD_PRESSURE_SAMPLES ? "none" : graded.disk,
534 } satisfies PressureLevels;
535 yield* Ref.set(levels, next);
536 const now = yield* Clock.currentTimeMillis;
537 const sampledBefore = yield* Ref.getAndSet(lastSampledAt, now);
538 const unwatched = sampledBefore === null || now - sampledBefore > EPISODE_GAP_MS;
539 const since = yield* Ref.updateAndGet(severeSince, (previous) =>
540 Object.fromEntries(
541 HOST_PRESSURE_KINDS.flatMap((kind) =>
542 next[kind] === "severe"
543 ? [[kind, (unwatched ? undefined : previous[kind]) ?? now] as const]
544 : [],
545 ),
546 ),
547 );
548​
549 // CPU use is a difference of two readings, so it is read every sample while the scopes exist.
550 const cpuUsage = new Map(
551 agents === undefined
552 ? []
553 : yield* Effect.forEach(agents.scopes, (scope) =>
554 readFile(`/sys/fs/cgroup${scope.path}/cpu.stat`).pipe(
555 Effect.map(
556 (stat) => [scope.path, cgroupNumber(stat, /^usage_usec (\d+)$/m)] as const,
557 ),
558 ),
559 ),
560 );
561 const previousCpu = yield* Ref.getAndSet(lastAgentCpu, {
562 at: now,
563 usage: new Map(
564 [...cpuUsage].flatMap(([path, usage]) => (usage === null ? [] : [[path, usage] as const])),
565 ),
566 });
567 const elapsedMicros =
568 previousCpu === null || now - previousCpu.at > CPU_SAMPLE_MAX_AGE_MS
569 ? null
570 : (now - previousCpu.at) * 1000;
571 // The more pressured resource names the culprits; `hostPressureRanking` mirrors this.
572 const rankBy =
573 next.memory === "none" && next.cpu === "none"
574 ? null
575 : RANK[next.cpu] > RANK[next.memory]
576 ? "cpu"
577 : "memory";
578 const agentUsage =
579 rankBy === null || agents === undefined
580 ? []
581 : yield* Effect.forEach(agents.scopes, (scope) =>
582 readFile(`/sys/fs/cgroup${scope.path}/memory.current`).pipe(
583 Effect.map((text): HostPressureAgent => {
584 const usage = cpuUsage.get(scope.path);
585 const before = previousCpu?.usage.get(scope.path);
586 return {
587 threadId: scope.threadId === undefined ? null : ThreadId.make(scope.threadId),
588 agent: scope.agent,
589 memoryBytes: Number(text.trim()) || 0,
590 cpuCores:
591 elapsedMicros === null ||
592 elapsedMicros <= 0 ||
593 usage === null ||
594 usage === undefined ||
595 before === undefined
596 ? null
597 : Math.max(0, usage - before) / elapsedMicros,
598 };
599 }),
600 ),
601 );
602 return {
603 ...next,
604 diskFreeBytes: next.disk === "none" || disk === null ? null : roundCoarsely(disk.free),
605 heaviestAgents: rankBy === null ? [] : heaviestAgents(agentUsage, rankBy),
606 severeSince: since,
607 } satisfies HostPressure;
608 });
609​
610 const sample = Effect.fn("HostResources.sample")(function* () {
611 const cgroup = yield* serverCgroup;
612 const previousCpu = yield* readServerCpu(cgroup);
613 yield* Effect.sleep("200 millis");
614 const cpu = yield* readServerCpu(cgroup);
615 const elapsedMicros = (cpu.at - previousCpu.at) * 1000;
616 const totalDelta = cpu.total - previousCpu.total;
617 const idleDelta = cpu.idle - previousCpu.idle;
618 let cpuCount = cpu.count;
619 const hostUtilization =
620 previousCpu.count === cpu.count && totalDelta > 0 && idleDelta >= 0
621 ? Math.min(1, Math.max(0, 1 - idleDelta / totalDelta))
622 : null;
623 let cpuUtilization = hostUtilization;
624 if (cpu.quota !== null) {
625 const capacity = Math.min(cpu.quota, cpu.count);
626 cpuCount = Math.max(1, Math.floor(capacity));
627 const cgroupIdle =
628 previousCpu.usage !== null && cpu.usage !== null && elapsedMicros > 0
629 ? capacity - (cpu.usage - previousCpu.usage) / elapsedMicros
630 : null;
631 // Agents can run in sibling cgroups (agentScope.ts), so a busy host still counts.
632 const hostIdle = hostUtilization === null ? null : cpu.count * (1 - hostUtilization);
633 const idle =
634 cgroupIdle === null || hostIdle === null
635 ? (cgroupIdle ?? hostIdle)
636 : Math.min(cgroupIdle, hostIdle);
637 cpuUtilization = idle === null ? null : Math.min(1, Math.max(0, 1 - idle / capacity));
638 }
639​
640 let totalMemoryBytes = NodeOS.totalmem();
641 // On Windows libuv returns GlobalMemoryStatusEx.ullAvailPhys, including standby memory.
642 let availableMemoryBytes = NodeOS.freemem();
643 if (platform === "linux") {
644 const meminfo = yield* readFile("/proc/meminfo");
645 const available = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(meminfo)?.[1];
646 if (available) availableMemoryBytes = Number(available) * 1024;
647 } else if (platform === "darwin") {
648 const output = yield* spawner
649 .string(ChildProcess.make("/usr/bin/vm_stat", [], { stdin: "ignore", stderr: "ignore" }))
650 .pipe(
651 Effect.timeout("1 second"),
652 Effect.orElseSucceed(() => ""),
653 );
654 availableMemoryBytes = darwinAvailableMemory(output) ?? availableMemoryBytes;
655 }
656 const memoryMax = cgroup
657 ? cgroupNumber(yield* readFile(`${cgroup}/memory.max`), /^(\d+)$/m)
658 : null;
659 const memoryCurrent =
660 memoryMax === null
661 ? null
662 : cgroupNumber(yield* readFile(`${cgroup}/memory.current`), /^(\d+)$/m);
663 // Without usage, a capped total would read as a near-empty cgroup; keep host values instead.
664 if (memoryMax !== null && memoryCurrent !== null) {
665 totalMemoryBytes = Math.min(totalMemoryBytes, memoryMax);
666 // inactive_file is page cache the kernel reclaims before hitting memory.max.
667 const stat = yield* readFile(`${cgroup}/memory.stat`);
668 const reclaimable = cgroupNumber(stat, /^inactive_file (\d+)$/m) ?? 0;
669 availableMemoryBytes = Math.min(
670 availableMemoryBytes,
671 memoryMax - (memoryCurrent - reclaimable),
672 );
673 }
674 const disk = yield* diskSpace;
675 return {
676 sampledAt: DateTime.toEpochMillis(yield* DateTime.now),
677 cpuUtilization,
678 cpuCount,
679 availableMemoryBytes: Math.min(totalMemoryBytes, Math.max(0, availableMemoryBytes)),
680 totalMemoryBytes,
681 diskFreeBytes: disk?.free ?? null,
682 diskTotalBytes: disk?.total ?? null,
683 };
684 });
685​
686 const cache = yield* Cache.make({
687 capacity: 1,
688 lookup: (_key: "host") => sample(),
689 timeToLive: "5 seconds",
690 });
691 const pressure = yield* Stream.fromEffectSchedule(
692 samplePressure(),
693 Schedule.spaced(PRESSURE_INTERVAL),
694 ).pipe(
695 Stream.changesWith((previous, next) => JSON.stringify(previous) === JSON.stringify(next)),
696 Stream.share({ capacity: 1, strategy: "sliding", replay: 1 }),
697 );
698 const readPressure = Stream.runHead(pressure).pipe(
699 Effect.map((latest) => (latest._tag === "Some" ? latest.value : CALM_HOST_PRESSURE)),
700 );
701 return HostResources.of({ read: Cache.get(cache, "host"), pressure, readPressure });
702});
703​
704export const layer = Layer.effect(HostResources, make());