From 34f1ca2f71bf8b7eb6251d74efb7a29068d4e945 Mon Sep 17 00:00:00 2001 From: A L F Y E <24563006+xt1990xt1990@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:13:00 +0800 Subject: [PATCH] fix(host-monitor): exclude reclaimable cache from macOS memory usage --- plugins/host-monitor/OVERVIEW.md | 2 +- plugins/host-monitor/server/sampler.test.mjs | 26 ++++++++++++++++++ plugins/host-monitor/server/sampler.ts | 29 ++++++++++++++++++-- 3 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 plugins/host-monitor/server/sampler.test.mjs diff --git a/plugins/host-monitor/OVERVIEW.md b/plugins/host-monitor/OVERVIEW.md index 174eb86..cd97822 100644 --- a/plugins/host-monitor/OVERVIEW.md +++ b/plugins/host-monitor/OVERVIEW.md @@ -4,6 +4,6 @@ The line reads like the built-in usage summary: an icon and percentage for CPU, The daemon samples the host every two seconds, disks every thirty, and keeps the history in memory. History resets when the plugin reloads or the daemon restarts. Each connected host reports its own numbers. -Percentages below 10 show one decimal, so a nearly idle host reads 0.4% rather than 0%. On Linux, CPU usage comes from `/proc/stat`; I/O wait counts as idle and steal time, which a VPS loses to its hypervisor, counts as busy. Memory uses the available-memory figure from `/proc/meminfo` on Linux, so the page cache is not counted as used. Network speed sums all interfaces except loopback and common virtual ones (veth, docker, bridge). Disks are the filesystems in `/proc/mounts` backed by a block device (plus ZFS), each device counted once; network mounts, memory-backed filesystems and read-only images such as snap packages are left out. Disk percentages follow `df`: space reserved for root counts as neither used nor free. Network speed and the disk list need Linux; on other systems only CPU, RAM and the root disk are shown. +Percentages below 10 show one decimal, so a nearly idle host reads 0.4% rather than 0%. On Linux, CPU usage comes from `/proc/stat`; I/O wait counts as idle and steal time, which a VPS loses to its hypervisor, counts as busy. Memory uses the available-memory figure from `/proc/meminfo` on Linux, so the page cache is not counted as used. On macOS, memory uses `vm_stat`: anonymous pages minus purgeable pages, plus wired pages and the physical pages occupied by the compressor, multiplied by the reported page size. This excludes file-backed cache and follows Activity Monitor’s app + wired + compressed memory accounting. Network speed sums all interfaces except loopback and common virtual ones (veth, docker, bridge). Disks are the filesystems in `/proc/mounts` backed by a block device (plus ZFS), each device counted once; network mounts, memory-backed filesystems and read-only images such as snap packages are left out. Disk percentages follow `df`: space reserved for root counts as neither used nor free. Network speed and the disk list need Linux; on other systems only CPU, RAM and the root disk are shown. The plugin only reads local system counters. The host name and these statistics are shown to every Paseo client connected to the daemon, including remote ones; the plugin contacts no other service. diff --git a/plugins/host-monitor/server/sampler.test.mjs b/plugins/host-monitor/server/sampler.test.mjs new file mode 100644 index 0000000..b4c90af --- /dev/null +++ b/plugins/host-monitor/server/sampler.test.mjs @@ -0,0 +1,26 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { parseDarwinUsedBytes } from "./sampler.ts"; + +for (const pageSize of [4096, 16384]) { + test(`macOS memory excludes cache and counts physical compression (${pageSize}-byte pages)`, () => { + const raw = `Mach Virtual Memory Statistics: (page size of ${pageSize} bytes) +Pages free: 200. +Pages wired down: 300. +Pages purgeable: 100. +File-backed pages: 2000. +Anonymous pages: 1000. +Pages stored in compressor: 800. +Pages occupied by compressor: 200. +`; + assert.equal(parseDarwinUsedBytes(raw), 1400 * pageSize); + }); +} + +test("incomplete vm_stat output reports the missing field instead of undercounting", () => { + assert.throws(() => parseDarwinUsedBytes(""), /missing page size/); + assert.throws( + () => parseDarwinUsedBytes("Mach Virtual Memory Statistics: (page size of 16384 bytes)"), + /missing Anonymous pages/, + ); +}); diff --git a/plugins/host-monitor/server/sampler.ts b/plugins/host-monitor/server/sampler.ts index 4a32ed5..3e2c387 100644 --- a/plugins/host-monitor/server/sampler.ts +++ b/plugins/host-monitor/server/sampler.ts @@ -1,3 +1,4 @@ +import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; import { statfs } from "node:fs/promises"; import os from "node:os"; @@ -57,8 +58,31 @@ function readCpuTimes(): CpuTimes { return { idle, total }; } +export function parseDarwinUsedBytes(raw: string): number { + const pageSize = /page size of (\d+) bytes/.exec(raw); + if (!pageSize || Number(pageSize[1]) === 0) throw new Error("vm_stat: missing page size"); + const pages = (name: string): number => { + const match = new RegExp(`^${name}:\\s+(\\d+)\\.`, "m").exec(raw); + if (!match) throw new Error(`vm_stat: missing ${name}`); + return Number(match[1]); + }; + // Activity Monitor: app (anonymous minus purgeable), wired, and physical compressed memory. + // File-backed cache is reclaimable; pages stored in the compressor are not physical bytes. + return (pages("Anonymous pages") - pages("Pages purgeable") + pages("Pages wired down") + + pages("Pages occupied by compressor")) * Number(pageSize[1]); +} + function readMemory(): { totalBytes: number; usedBytes: number } { const totalBytes = os.totalmem(); + if (os.platform() === "darwin") { + try { + const raw = execFileSync("/usr/bin/vm_stat", { encoding: "utf8", timeout: 1000 }); + return { totalBytes, usedBytes: parseDarwinUsedBytes(raw) }; + } catch (error) { + console.warn("host-monitor: failed to read macOS memory; using os.freemem", error); + return { totalBytes, usedBytes: totalBytes - os.freemem() }; + } + } try { const match = /^MemAvailable:\s+(\d+) kB/m.exec(readFileSync("/proc/meminfo", "utf8")); if (match) return { totalBytes, usedBytes: totalBytes - Number(match[1]) * 1024 }; @@ -158,6 +182,7 @@ export function startSampler(): { read(): HostStats; stop(): void } { let networkTotals = previousNet; let disks: DiskUsage[] = []; let diskRead: Promise | null = null; + let memory: ReturnType; const tick = () => { const now = Date.now(); @@ -166,7 +191,7 @@ export function startSampler(): { read(): HostStats; stop(): void } { const seconds = Math.max((now - previousAt) / 1000, 0.001); const totalDelta = cpu.total - previousCpu.total; const idleDelta = cpu.idle - previousCpu.idle; - const memory = readMemory(); + memory = readMemory(); const sample: HostSample = { at: now, @@ -214,7 +239,7 @@ export function startSampler(): { read(): HostStats; stop(): void } { cpuCount: cpus.length, cpuModel: cpus[0]?.model ?? "unknown", loadAverage: [one, five, fifteen], - memory: readMemory(), + memory, network: networkTotals ? { rxTotalBytes: networkTotals.rx, txTotalBytes: networkTotals.tx } : null,