@nredd/pi-resource-sampler 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -17
- package/dist/collect.d.ts +57 -5
- package/dist/collect.js +113 -11
- package/dist/counters.d.ts +90 -7
- package/dist/counters.js +138 -12
- package/dist/darwin.d.ts +95 -0
- package/dist/darwin.js +254 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +40 -8
- package/dist/types.d.ts +19 -0
- package/package.json +34 -9
package/README.md
CHANGED
|
@@ -2,7 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
Pi-independent, dependency-free ESM library for passive host resource dashboards and snapshots.
|
|
4
4
|
`@nredd/pi-resource-sampler` is not a Pi extension. No tools, timers, hooks, output or policy are
|
|
5
|
-
registered.
|
|
5
|
+
registered. Runs on Node >=22.14 and Bun.
|
|
6
|
+
|
|
7
|
+
Unreleased source (planned `0.2.0`): native Darwin interval CPU/footprint and host used/swap metrics.
|
|
8
|
+
Published `0.1.1` still lacks them; release and consumer-pin steps remain owner-gated.
|
|
9
|
+
|
|
10
|
+
Upgrade from `0.1.0`, which is unsafe: on Darwin it reported `ps -c -o comm`, the basename of argv[0],
|
|
11
|
+
so a launcher-chosen argv[0] or Node `process.title` (e.g. `npm exec <package> mcp`) leaked into
|
|
12
|
+
`processes[].name`. On Bun, host `cpu` read lazily populated `os.cpus()` objects, so the second sample
|
|
13
|
+
was `warming` and the third could be a fictional 0 or 100. `0.1.1` keeps the same TypeScript interface.
|
|
6
14
|
|
|
7
15
|
```ts
|
|
8
16
|
import { createResourceSampler } from '@nredd/pi-resource-sampler';
|
|
@@ -24,31 +32,84 @@ Semantics:
|
|
|
24
32
|
- `cpu`: aggregate host CPU counter delta, 0..100. Core count/model changes, individual counter
|
|
25
33
|
rollback, initial samples, invalid intervals and counters that have not advanced are `warming`,
|
|
26
34
|
never fabricated zero. Uses Node's native `os.cpus()` counters, not load average.
|
|
27
|
-
- `processes[].cpu`:
|
|
35
|
+
- `processes[].cpu`: cumulative user+system counter delta divided by monotonic elapsed milliseconds.
|
|
28
36
|
100 means one logical core, multi-threaded processes can exceed 100. Linux `CLK_TCK` is read
|
|
29
37
|
once with fixed `/usr/bin/getconf CLK_TCK`; no assumed tick rate or RSS page size.
|
|
30
|
-
- Linux identity includes the exact `/proc/PID/stat` start tick string. Read stat/status/stat and
|
|
38
|
+
- Linux identity includes the exact `/proc/PID/stat` start tick string. Read stat/exe/status/stat and
|
|
31
39
|
reject identity changes during RSS collection. Missing or inaccessible processes are skipped and
|
|
32
40
|
invalidate their old baselines. New/reused PIDs and counter resets warm rather than showing zero.
|
|
33
|
-
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
41
|
+
- `cpu` copies every `os.cpus()` counter when sampled. Bun returns lazy placeholders that read native
|
|
42
|
+
counters on first property access; an unread stored baseline would describe a later instant.
|
|
43
|
+
- Darwin enumerates metadata with fixed `/bin/ps -A -o pid=,ppid=,lstart=,time=,rss=,ucomm=`
|
|
44
|
+
and `LC_ALL=C`. Builtin FFI (Node >=26.1, Bun; toolchain pin in root `.bun-version`) then reads fixed symbols
|
|
45
|
+
`proc_pidinfo`, `proc_pid_rusage` and `mach_timebase_info` from `/usr/lib/libproc.dylib`, without
|
|
46
|
+
root, a compiler, addon or new binary/package dependency. Import/construction does not load FFI.
|
|
47
|
+
Node emits its builtin experimental-FFI warning on first use; Bun does not. Node 22-25 keeps
|
|
48
|
+
metadata/RSS but explicitly unavailable CPU/footprint. ABI access is restricted to Darwin arm64/x64.
|
|
49
|
+
- Native Darwin identity includes PID, kernel process-start absolute ticks, microsecond start time,
|
|
50
|
+
PPID and exact `p_comm` bytes. Rusage reads bracket metadata; changed start/exit state or counter
|
|
51
|
+
rollback rejects the native read. Same-second PID reuse cannot authenticate an old baseline even
|
|
52
|
+
with identical parent/name and nondecreasing CPU. Each observation has its own monotonic timestamp.
|
|
53
|
+
Identity/parent/name changes, negative deltas, nonpositive/nonfinite intervals and native intervals
|
|
54
|
+
over 60s warm instead of fabricating CPU. Native CPU counters are Mach ticks converted using the
|
|
55
|
+
kernel timebase (125/3 ns per tick on this Apple Silicon Mac), NOT assumed nanoseconds.
|
|
56
|
+
- `processes[].footprint` is an optional Darwin metric from `ri_phys_footprint`, including compressed
|
|
57
|
+
memory. Native `rssBytes` comes from `ri_resident_size`. Inaccessible/exited/reused PIDs or exhausted
|
|
58
|
+
native budgets retain the enumerated metadata/RSS row with unavailable CPU/footprint; unsupported
|
|
59
|
+
runtimes do the same. No failed footprint is encoded as zero. `ps` fallback identity has only
|
|
60
|
+
whole-second precision, so it NEVER supplies interval CPU. No decaying `%cpu` is relabelled.
|
|
38
61
|
- `wallTimeMs` labels the start; `monotonicTimeMs` controls intervals. Per-process reads have their own
|
|
39
62
|
monotonic timestamps internally; the scan is not atomic. `durationMs` includes collection.
|
|
40
|
-
- `memory.freeBytes` means free, NOT available or pressure.
|
|
63
|
+
- `memory.freeBytes` means free, NOT available or pressure. Darwin adds optional v1 `memory.usage`
|
|
64
|
+
and `memory.swap` metrics. `usage.value.usedBytes` estimates resident App + Wired + Compressed RAM:
|
|
65
|
+
`(Anonymous pages - Pages purgeable + Pages wired down + Pages occupied by compressor) * page size`
|
|
66
|
+
from fixed `/usr/bin/vm_stat` output. The page size comes from its header, never an assumed 4KiB.
|
|
67
|
+
`availableBytes` is total minus that estimate (reclaimable cache included), NOT a pressure score or
|
|
68
|
+
an allocation guarantee. Compressor occupancy is physical RAM, not `Pages stored in compressor`.
|
|
69
|
+
Swap used/allocated bytes come from fixed `/usr/sbin/sysctl vm.swapusage` (binary MiB).
|
|
70
|
+
Invalid/missing/over-budget counters are `unavailable`, never zero or a silent total-free fallback.
|
|
71
|
+
Older producers and non-Darwin platforms omit these additive fields. Linux's existing free-page/PSI
|
|
72
|
+
semantics are unchanged; this library did not expose Linux MemAvailable.
|
|
73
|
+
Both helpers share the existing scan budget, fixed environment, output bound and awaited reaping.
|
|
74
|
+
`loadAverage` is load, NOT percent.
|
|
41
75
|
Linux memory PSI preserves native `some`/optional `full`, avg10/60/300 percentages and cumulative
|
|
42
76
|
stall microseconds. Missing/invalid PSI is unavailable. Other platforms explicitly have no PSI.
|
|
43
|
-
-
|
|
44
|
-
|
|
45
|
-
|
|
77
|
+
- `processes[].name` is an executable basename from kernel metadata. It excludes argv, environment,
|
|
78
|
+
process title and Linux comm, but it is still untrusted metadata that the process or its launcher can
|
|
79
|
+
choose (see the last item). `""` means unavailable, not a process called nothing:
|
|
80
|
+
- Darwin: native `proc_bsdinfo.pbi_comm`, or `ps ucomm` from kinfo `p_comm`. XNU writes it at exec, from the
|
|
81
|
+
looked-up executable file name, truncated to 16 bytes (`Google Chrome He`). `ps -c -o comm` is
|
|
82
|
+
argv[0] and is NOT used.
|
|
83
|
+
- Linux: basename of `readlink /proc/PID/exe` (` (deleted)` marker removed), read between the two
|
|
84
|
+
identity-checked stat reads. The kernel gates that link by ptrace read access, so other users'
|
|
85
|
+
processes are usually `""` without privileges. `/proc/PID/stat` comm is NOT used:
|
|
86
|
+
`prctl(PR_SET_NAME)`, `/proc/self/comm` and Node's `process.title` rewrite it. Kernel threads
|
|
87
|
+
have no `VmRSS`, so they are skipped (`process-unreadable-or-changed`) and never named.
|
|
88
|
+
- Whoever names, links or copies the executable file chooses the name. On Linux a process can also
|
|
89
|
+
exec a `memfd_create` file it named itself (`memfd:<name>`), and a privileged one can replace its
|
|
90
|
+
exe link with `prctl(PR_SET_MM_EXE_FILE)`. Names are bounded to 128 code points with control
|
|
91
|
+
characters replaced, no user names, paths or agent attribution are collected, and consumers must
|
|
92
|
+
treat them as untrusted display text, never execute or interpret them.
|
|
46
93
|
|
|
47
94
|
Bounds:
|
|
48
95
|
|
|
49
96
|
- Default scan budget 250ms, 2048 PIDs, 2MiB captured bytes; options allow at most 5s, 16384 PIDs,
|
|
50
97
|
16MiB. Linux proc files read sequentially (concurrency one), at most 8KiB each. Directory iteration
|
|
51
|
-
stops at the budget; Darwin output stops at the PID/output budget and reaps the fixed helper.
|
|
98
|
+
stops at the budget; Darwin output stops at the PID/output budget and reaps the fixed helper. Native reads charge
|
|
99
|
+
8 bytes for the timebase and 328 bytes per admitted PID (two 96-byte rusage buffers and one 136-byte
|
|
100
|
+
metadata buffer), including failed calls, to that SAME byte budget. Only `pbi_comm` and numeric
|
|
101
|
+
fields are inspected; `pbi_name`, arguments and environment are never decoded or exported. Native
|
|
102
|
+
syscalls are synchronous/non-preemptible like `os.cpus()`; admission is checked between reads.
|
|
103
|
+
- `/proc/PID/exe` is a `readlink`, which Node and Bun cannot cap: each call copies up to PATH_MAX
|
|
104
|
+
(4096) bytes into a fixed runtime buffer before the length is known. That fixed per-call syscall
|
|
105
|
+
copy can exceed the remaining budget; the logical budget cannot. A target longer than the remainder
|
|
106
|
+
is charged the remainder, so `bytesRead <= maxBytes`, and the budget is then exhausted: that
|
|
107
|
+
process's `status` read is refused, so the whole process is skipped
|
|
108
|
+
(`process-unreadable-or-changed`, `byte-limit`), not kept with an empty name, and the scan stops.
|
|
109
|
+
A target filling the 4096-byte buffer may be truncated: Node returns it silently, the name is
|
|
110
|
+
dropped (`""`, `file-byte-limit`) and the process is kept. Bun's readlink source refuses such a
|
|
111
|
+
target with `ENAMETOOLONG`, which would take the unreadable-link path (`""`, no reason); that Bun
|
|
112
|
+
path was read in source only, never executed here.
|
|
52
113
|
- `coverage.complete`, `enumerated`, `sampled`, `skipped`, `bytesRead` and reasons describe partial
|
|
53
114
|
coverage explicitly. `enumerated` is encountered rows, not total processes when partial. Truncation
|
|
54
115
|
is not a host-wide top-process ranking. OS enumeration order may favor the same subset each time.
|
|
@@ -58,6 +119,11 @@ Bounds:
|
|
|
58
119
|
immediate SIGKILL on abort/deadline/cap, and resolve only on close. No persistent children or workers.
|
|
59
120
|
- Unsupported platforms keep native host metrics but report process coverage unavailable.
|
|
60
121
|
|
|
122
|
+
macOS measurement/definition comparison, native ABI evidence and future publication checklist:
|
|
123
|
+
[here](../../docs/mon-accuracy.md). Process `rssBytes` still excludes compressed pages; it is not
|
|
124
|
+
Activity Monitor's physical footprint; use the separate `footprint` metric for that comparison.
|
|
125
|
+
Names remain executable names, so Pi commonly appears as `node`.
|
|
126
|
+
|
|
61
127
|
Local overhead observation (2026-10-22, Darwin arm64, Node 26.12.0, 10 logical CPUs, 16GiB RAM,
|
|
62
128
|
load about 6, not a quiet-runner benchmark): ten scans of 557 processes took 17.5-24.9ms each,
|
|
63
129
|
about 41.3KB captured, all complete. The Node collector consumed 25.7ms CPU total across ten
|
|
@@ -67,8 +133,27 @@ scans (2.6ms/sample, excludes helper CPU); a separate fixed `ps` invocation meas
|
|
|
67
133
|
real-input gate and reports its snapshot duration/coverage.
|
|
68
134
|
|
|
69
135
|
Development: `npm run check --workspace @nredd/pi-resource-sampler` (single-worker tests, including
|
|
70
|
-
actual host samples and child cleanup)
|
|
71
|
-
|
|
136
|
+
actual host samples and child cleanup). The full suite runs through Vitest on Node and pinned Bun.
|
|
137
|
+
Native failure tests inject fixed bindings through the same lazy loader seam used by production,
|
|
138
|
+
not a Node-shaped global builtin mock; they do not require the runtime's real FFI to exist.
|
|
139
|
+
`test/runtime.test.ts` runs under both engines: it starts a child whose argv[0], argv, environment, process title and (Linux) comm hold a
|
|
140
|
+
random secret, proves the 0.1.0 source exposes it, then requires the child in the snapshot and no
|
|
141
|
+
12-character fragment of the secret, plus three real CPU samples. Everything after spawn, readiness
|
|
142
|
+
included, is followed by SIGTERM, then SIGKILL, with a bounded wait for the runtime's exit status
|
|
143
|
+
of that exact child (never a PID probe); a cleanup failure is reported alongside the original error
|
|
144
|
+
(`AggregateError`), never instead of it. Regressions make readiness and the negative control fail
|
|
145
|
+
and require the child reaped, including a child that ignores SIGTERM and needs SIGKILL, and inject a
|
|
146
|
+
cleanup failure to require both errors. This cleanup is in-process only: if the test worker itself
|
|
147
|
+
is SIGKILLed, no JavaScript runs and the child outlives it. The packed contract probe below instead
|
|
148
|
+
runs in its own process group, which the gate kills on its Python timeout or `KeyboardInterrupt`
|
|
149
|
+
while the leader is unreaped; an already reaped leader, or an unhandled SIGTERM/SIGHUP or SIGKILL of
|
|
150
|
+
the gate, skips that cleanup and may leave members behind. The privacy
|
|
151
|
+
check samples with the library maxima (5s, 16384 PIDs, 16MiB) and never accepts a missing child as
|
|
152
|
+
a pass: on a host whose processes exceed those bounds, or whose enumeration reaches the child only
|
|
153
|
+
after them, it fails with the snapshot's coverage in the error. On Linux each process costs two
|
|
154
|
+
`stat` reads, the `/proc/PID/exe` target bytes and `status`, so the byte bound can bind before the
|
|
155
|
+
PID bound. `make check-resource-sampler-contract` builds and exercises an isolated installed
|
|
156
|
+
tarball, with no Pi or siblings. Both run on existing macOS/Linux CI jobs.
|
|
72
157
|
`dist` contains compiled ESM and declarations; the exact packed payload is contract-pinned. No install
|
|
73
|
-
scripts or runtime dependencies.
|
|
74
|
-
|
|
158
|
+
scripts or runtime dependencies. Releases publish through `publish.yml` with npm provenance; see
|
|
159
|
+
[releases](../../docs/releases.md).
|
package/dist/collect.d.ts
CHANGED
|
@@ -10,20 +10,72 @@ export declare class Budget {
|
|
|
10
10
|
enumerated: number;
|
|
11
11
|
skipped: number;
|
|
12
12
|
readonly reasons: Set<string>;
|
|
13
|
+
/**
|
|
14
|
+
* Initialize one scan's limits.
|
|
15
|
+
* @param deadline Absolute monotonic deadline in milliseconds.
|
|
16
|
+
* @param maxBytes Maximum captured/charged bytes.
|
|
17
|
+
* @param maxPids Maximum enumerated PIDs.
|
|
18
|
+
* @param signal Caller-owned cancellation signal.
|
|
19
|
+
*/
|
|
13
20
|
constructor(deadline: number, maxBytes: number, maxPids: number, signal: AbortSignal);
|
|
21
|
+
/** @returns Remaining admission milliseconds; throws when cancelled. */
|
|
14
22
|
remaining(): number;
|
|
23
|
+
/** @returns Whether time/bytes remain, recording exhausted limits; throws when cancelled. */
|
|
15
24
|
ready(): boolean;
|
|
16
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* Read a fixed-size proc file and always await handle closure.
|
|
27
|
+
* @param path Fixed proc file path for an admitted PID or pressure source.
|
|
28
|
+
* @returns Complete UTF-8 contents; rejects on exhaustion/truncation/read failure/abort.
|
|
29
|
+
*/
|
|
17
30
|
read(path: string): Promise<string>;
|
|
31
|
+
/**
|
|
32
|
+
* Linux executable basename, or "" when the exe link is unreadable (other users' processes without
|
|
33
|
+
* ptrace read access, exited processes), over budget or possibly truncated. Errors carry no detail
|
|
34
|
+
* outward. Node and Bun cannot cap readlink below their fixed PATH_MAX buffer, so the length is only
|
|
35
|
+
* known after the syscall: a target beyond the remaining budget is charged the remainder and dropped,
|
|
36
|
+
* keeping `bytesRead <= maxBytes`. Node returns a full buffer silently truncated, so that is dropped too.
|
|
37
|
+
* @param path Admitted PID's /proc/PID/exe link path.
|
|
38
|
+
* @returns Safe basename, or empty string when unavailable; aborts propagate.
|
|
39
|
+
*/
|
|
40
|
+
executable(path: string): Promise<string>;
|
|
18
41
|
}
|
|
19
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* Run a fixed helper with bounded capture, kill on cancellation/deadline and await close/reaping.
|
|
44
|
+
* @param executable Fixed absolute OS helper path.
|
|
45
|
+
* @param args Fixed helper arguments, never target process arguments.
|
|
46
|
+
* @param budget Shared admission and capture accounting.
|
|
47
|
+
* @param maxLines Maximum complete stdout rows to admit.
|
|
48
|
+
* @returns Captured text and whether the command completed without truncation/failure.
|
|
49
|
+
*/
|
|
20
50
|
export declare function command(executable: string, args: string[], budget: Budget, maxLines?: number): Promise<{
|
|
21
51
|
text: string;
|
|
22
52
|
complete: boolean;
|
|
23
53
|
}>;
|
|
24
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* Scan Linux sequentially and close the directory even on cancellation.
|
|
56
|
+
* @param budget Shared scan limits and cancellation.
|
|
57
|
+
* @param hz Host CLK_TCK rate in ticks per second.
|
|
58
|
+
* @returns Validated identity-bracketed process counters; aborts propagate.
|
|
59
|
+
*/
|
|
25
60
|
export declare function linuxProcesses(budget: Budget, hz: number): Promise<ProcessCounter[]>;
|
|
26
|
-
/**
|
|
61
|
+
/**
|
|
62
|
+
* Fixed metadata-only ps format. `ucomm` prints kinfo `p_comm`, never `comm`: `ps -c -o comm` shows the
|
|
63
|
+
* basename of argv[0], which any launcher picks and Node's `process.title` rewrites in place.
|
|
64
|
+
* @param budget Shared helper/native scan limits and cancellation.
|
|
65
|
+
* @returns Bounded fallback rows enriched with accessible native metrics; aborts propagate.
|
|
66
|
+
*/
|
|
27
67
|
export declare function darwinProcesses(budget: Budget): Promise<ProcessCounter[]>;
|
|
28
|
-
/**
|
|
68
|
+
/**
|
|
69
|
+
* Run fixed metadata-only helpers sharing the process deadline, cap and awaited reaping.
|
|
70
|
+
* @param budget Shared helper capture budget and cancellation.
|
|
71
|
+
* @param total Host physical RAM in bytes.
|
|
72
|
+
* @returns Explicit available/unavailable host usage and swap metrics.
|
|
73
|
+
*/
|
|
74
|
+
export declare function darwinHostMemory(budget: Budget, total: number): Promise<Pick<ResourceSnapshot["memory"], "usage" | "swap">>;
|
|
75
|
+
/**
|
|
76
|
+
* Collect optional platform-specific PSI; absence is not zero pressure.
|
|
77
|
+
* @param budget Shared file-read budget and cancellation.
|
|
78
|
+
* @param platform Host platform identifier.
|
|
79
|
+
* @returns Linux PSI availability or explicit unsupported state; aborts propagate.
|
|
80
|
+
*/
|
|
29
81
|
export declare function pressure(budget: Budget, platform: string): Promise<ResourceSnapshot["pressure"]>;
|
package/dist/collect.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { open, opendir } from "node:fs/promises";
|
|
2
|
+
import { open, opendir, readlink } from "node:fs/promises";
|
|
3
3
|
import { performance } from "node:perf_hooks";
|
|
4
|
-
import { darwinProcess, linuxRss, linuxStat, psi } from "./counters.js";
|
|
4
|
+
import { darwinMemory, darwinProcess, darwinSwap, executableName, linuxRss, linuxStat, psi, } from "./counters.js";
|
|
5
|
+
import { darwinNativeProcesses } from "./darwin.js";
|
|
6
|
+
/** Linux PATH_MAX: Node (libuv `pathconf`) and Bun (`PathBuffer`) readlink buffer size on Linux. */
|
|
7
|
+
const LINK_BUFFER_BYTES = 4096;
|
|
5
8
|
/** Per-scan mutable budget, never shared between sampler instances. */
|
|
6
9
|
export class Budget {
|
|
7
10
|
deadline;
|
|
@@ -12,16 +15,25 @@ export class Budget {
|
|
|
12
15
|
enumerated = 0;
|
|
13
16
|
skipped = 0;
|
|
14
17
|
reasons = new Set();
|
|
18
|
+
/**
|
|
19
|
+
* Initialize one scan's limits.
|
|
20
|
+
* @param deadline Absolute monotonic deadline in milliseconds.
|
|
21
|
+
* @param maxBytes Maximum captured/charged bytes.
|
|
22
|
+
* @param maxPids Maximum enumerated PIDs.
|
|
23
|
+
* @param signal Caller-owned cancellation signal.
|
|
24
|
+
*/
|
|
15
25
|
constructor(deadline, maxBytes, maxPids, signal) {
|
|
16
26
|
this.deadline = deadline;
|
|
17
27
|
this.maxBytes = maxBytes;
|
|
18
28
|
this.maxPids = maxPids;
|
|
19
29
|
this.signal = signal;
|
|
20
30
|
}
|
|
31
|
+
/** @returns Remaining admission milliseconds; throws when cancelled. */
|
|
21
32
|
remaining() {
|
|
22
33
|
this.signal.throwIfAborted();
|
|
23
34
|
return Math.max(0, this.deadline - performance.now());
|
|
24
35
|
}
|
|
36
|
+
/** @returns Whether time/bytes remain, recording exhausted limits; throws when cancelled. */
|
|
25
37
|
ready() {
|
|
26
38
|
if (this.remaining() <= 0)
|
|
27
39
|
this.reasons.add("deadline");
|
|
@@ -29,7 +41,11 @@ export class Budget {
|
|
|
29
41
|
this.reasons.add("byte-limit");
|
|
30
42
|
return this.remaining() > 0 && this.bytesRead < this.maxBytes;
|
|
31
43
|
}
|
|
32
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
* Read a fixed-size proc file and always await handle closure.
|
|
46
|
+
* @param path Fixed proc file path for an admitted PID or pressure source.
|
|
47
|
+
* @returns Complete UTF-8 contents; rejects on exhaustion/truncation/read failure/abort.
|
|
48
|
+
*/
|
|
33
49
|
async read(path) {
|
|
34
50
|
if (!this.ready())
|
|
35
51
|
throw new Error("budget exhausted");
|
|
@@ -52,8 +68,49 @@ export class Budget {
|
|
|
52
68
|
await file.close();
|
|
53
69
|
}
|
|
54
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Linux executable basename, or "" when the exe link is unreadable (other users' processes without
|
|
73
|
+
* ptrace read access, exited processes), over budget or possibly truncated. Errors carry no detail
|
|
74
|
+
* outward. Node and Bun cannot cap readlink below their fixed PATH_MAX buffer, so the length is only
|
|
75
|
+
* known after the syscall: a target beyond the remaining budget is charged the remainder and dropped,
|
|
76
|
+
* keeping `bytesRead <= maxBytes`. Node returns a full buffer silently truncated, so that is dropped too.
|
|
77
|
+
* @param path Admitted PID's /proc/PID/exe link path.
|
|
78
|
+
* @returns Safe basename, or empty string when unavailable; aborts propagate.
|
|
79
|
+
*/
|
|
80
|
+
async executable(path) {
|
|
81
|
+
if (!this.ready())
|
|
82
|
+
return "";
|
|
83
|
+
let target;
|
|
84
|
+
try {
|
|
85
|
+
target = await readlink(path, { encoding: "buffer" });
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
this.signal.throwIfAborted();
|
|
89
|
+
return "";
|
|
90
|
+
}
|
|
91
|
+
this.signal.throwIfAborted();
|
|
92
|
+
const remaining = this.maxBytes - this.bytesRead;
|
|
93
|
+
if (target.length > remaining) {
|
|
94
|
+
this.bytesRead = this.maxBytes;
|
|
95
|
+
this.reasons.add("byte-limit");
|
|
96
|
+
return "";
|
|
97
|
+
}
|
|
98
|
+
this.bytesRead += target.length;
|
|
99
|
+
if (target.length >= LINK_BUFFER_BYTES) {
|
|
100
|
+
this.reasons.add("file-byte-limit");
|
|
101
|
+
return "";
|
|
102
|
+
}
|
|
103
|
+
return executableName(target.toString("utf8"));
|
|
104
|
+
}
|
|
55
105
|
}
|
|
56
|
-
/**
|
|
106
|
+
/**
|
|
107
|
+
* Run a fixed helper with bounded capture, kill on cancellation/deadline and await close/reaping.
|
|
108
|
+
* @param executable Fixed absolute OS helper path.
|
|
109
|
+
* @param args Fixed helper arguments, never target process arguments.
|
|
110
|
+
* @param budget Shared admission and capture accounting.
|
|
111
|
+
* @param maxLines Maximum complete stdout rows to admit.
|
|
112
|
+
* @returns Captured text and whether the command completed without truncation/failure.
|
|
113
|
+
*/
|
|
57
114
|
export async function command(executable, args, budget, maxLines = Number.POSITIVE_INFINITY) {
|
|
58
115
|
if (!budget.ready())
|
|
59
116
|
return { text: "", complete: false };
|
|
@@ -65,11 +122,17 @@ export async function command(executable, args, budget, maxLines = Number.POSITI
|
|
|
65
122
|
const buffers = [];
|
|
66
123
|
let complete = true;
|
|
67
124
|
let lines = 0;
|
|
125
|
+
/**
|
|
126
|
+
* Terminate the helper and mark capture incomplete.
|
|
127
|
+
* @param reason Coverage reason to record.
|
|
128
|
+
* @returns Nothing; completion still waits for close.
|
|
129
|
+
*/
|
|
68
130
|
const stop = (reason) => {
|
|
69
131
|
complete = false;
|
|
70
132
|
budget.reasons.add(reason);
|
|
71
133
|
child.kill("SIGKILL");
|
|
72
134
|
};
|
|
135
|
+
/** @returns Nothing; terminate the helper after shared cancellation. */
|
|
73
136
|
const abort = () => stop("cancelled");
|
|
74
137
|
const timer = setTimeout(() => stop("deadline"), budget.remaining());
|
|
75
138
|
budget.signal.addEventListener("abort", abort, { once: true });
|
|
@@ -118,7 +181,12 @@ export async function command(executable, args, budget, maxLines = Number.POSITI
|
|
|
118
181
|
});
|
|
119
182
|
});
|
|
120
183
|
}
|
|
121
|
-
/**
|
|
184
|
+
/**
|
|
185
|
+
* Scan Linux sequentially and close the directory even on cancellation.
|
|
186
|
+
* @param budget Shared scan limits and cancellation.
|
|
187
|
+
* @param hz Host CLK_TCK rate in ticks per second.
|
|
188
|
+
* @returns Validated identity-bracketed process counters; aborts propagate.
|
|
189
|
+
*/
|
|
122
190
|
export async function linuxProcesses(budget, hz) {
|
|
123
191
|
const result = [];
|
|
124
192
|
const directory = await opendir("/proc");
|
|
@@ -135,11 +203,15 @@ export async function linuxProcesses(budget, hz) {
|
|
|
135
203
|
try {
|
|
136
204
|
const path = `/proc/${entry.name}`;
|
|
137
205
|
const first = linuxStat(await budget.read(`${path}/stat`), hz, performance.now());
|
|
206
|
+
if (!first)
|
|
207
|
+
throw new Error("process incomplete");
|
|
208
|
+
const name = await budget.executable(`${path}/exe`);
|
|
138
209
|
const rssBytes = linuxRss(await budget.read(`${path}/status`));
|
|
139
210
|
const last = linuxStat(await budget.read(`${path}/stat`), hz, performance.now());
|
|
140
|
-
|
|
211
|
+
// The name and RSS reads sit between two stat reads, so PID reuse rejects both.
|
|
212
|
+
if (!last || first.pid !== Number(entry.name) || first.identity !== last.identity || rssBytes === null)
|
|
141
213
|
throw new Error("process changed or incomplete");
|
|
142
|
-
result.push({ ...last, rssBytes });
|
|
214
|
+
result.push({ ...last, name, rssBytes });
|
|
143
215
|
}
|
|
144
216
|
catch {
|
|
145
217
|
budget.signal.throwIfAborted();
|
|
@@ -149,9 +221,14 @@ export async function linuxProcesses(budget, hz) {
|
|
|
149
221
|
}
|
|
150
222
|
return result;
|
|
151
223
|
}
|
|
152
|
-
/**
|
|
224
|
+
/**
|
|
225
|
+
* Fixed metadata-only ps format. `ucomm` prints kinfo `p_comm`, never `comm`: `ps -c -o comm` shows the
|
|
226
|
+
* basename of argv[0], which any launcher picks and Node's `process.title` rewrites in place.
|
|
227
|
+
* @param budget Shared helper/native scan limits and cancellation.
|
|
228
|
+
* @returns Bounded fallback rows enriched with accessible native metrics; aborts propagate.
|
|
229
|
+
*/
|
|
153
230
|
export async function darwinProcesses(budget) {
|
|
154
|
-
const { text } = await command("/bin/ps", ["-A", "-
|
|
231
|
+
const { text } = await command("/bin/ps", ["-A", "-o", "pid=,ppid=,lstart=,time=,rss=,ucomm="], budget, budget.maxPids);
|
|
155
232
|
const result = [];
|
|
156
233
|
for (const line of text.split("\n")) {
|
|
157
234
|
if (!line.trim())
|
|
@@ -169,9 +246,34 @@ export async function darwinProcesses(budget) {
|
|
|
169
246
|
budget.reasons.add("malformed-process-row");
|
|
170
247
|
}
|
|
171
248
|
}
|
|
172
|
-
return result;
|
|
249
|
+
return darwinNativeProcesses(result, budget);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Run fixed metadata-only helpers sharing the process deadline, cap and awaited reaping.
|
|
253
|
+
* @param budget Shared helper capture budget and cancellation.
|
|
254
|
+
* @param total Host physical RAM in bytes.
|
|
255
|
+
* @returns Explicit available/unavailable host usage and swap metrics.
|
|
256
|
+
*/
|
|
257
|
+
export async function darwinHostMemory(budget, total) {
|
|
258
|
+
const vm = await command("/usr/bin/vm_stat", [], budget);
|
|
259
|
+
const usage = vm.complete ? darwinMemory(vm.text, total) : null;
|
|
260
|
+
const swap = await command("/usr/sbin/sysctl", ["vm.swapusage"], budget);
|
|
261
|
+
const parsedSwap = swap.complete ? darwinSwap(swap.text) : null;
|
|
262
|
+
return {
|
|
263
|
+
usage: usage
|
|
264
|
+
? { state: "available", value: usage }
|
|
265
|
+
: { state: "unavailable", reason: "vm_stat invalid, unavailable or over budget" },
|
|
266
|
+
swap: parsedSwap
|
|
267
|
+
? { state: "available", value: parsedSwap }
|
|
268
|
+
: { state: "unavailable", reason: "swapusage invalid, unavailable or over budget" },
|
|
269
|
+
};
|
|
173
270
|
}
|
|
174
|
-
/**
|
|
271
|
+
/**
|
|
272
|
+
* Collect optional platform-specific PSI; absence is not zero pressure.
|
|
273
|
+
* @param budget Shared file-read budget and cancellation.
|
|
274
|
+
* @param platform Host platform identifier.
|
|
275
|
+
* @returns Linux PSI availability or explicit unsupported state; aborts propagate.
|
|
276
|
+
*/
|
|
175
277
|
export async function pressure(budget, platform) {
|
|
176
278
|
if (platform !== "linux")
|
|
177
279
|
return { source: "unsupported", reason: "no comparable native PSI metric on this platform" };
|
package/dist/counters.d.ts
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import type { CpuInfo } from "node:os";
|
|
2
2
|
import type { Metric, PsiLine } from "./types.js";
|
|
3
|
+
/** A >60s native interval is stale/suspend/anomaly territory for ~2s dashboard polling; warm anew.
|
|
4
|
+
* Linux intervals retain their existing semantics and are not subject to this Darwin-only limit.
|
|
5
|
+
*/
|
|
6
|
+
export declare const MAX_NATIVE_INTERVAL_MS = 60000;
|
|
7
|
+
/** sysctl vm.swapusage reports binary MiB, including fractional values. */
|
|
8
|
+
export declare const BYTES_PER_MEBIBYTE: number;
|
|
9
|
+
/** Three separately rounded hundredth-MiB fields can disagree; preserve the existing 0.02MiB bound. */
|
|
10
|
+
export declare const SWAP_ROUNDING_TOLERANCE_BYTES: number;
|
|
3
11
|
/** Internal raw process counter with a per-read monotonic timestamp. */
|
|
4
12
|
export interface ProcessCounter {
|
|
5
13
|
pid: number;
|
|
@@ -9,20 +17,95 @@ export interface ProcessCounter {
|
|
|
9
17
|
rssBytes: number;
|
|
10
18
|
cpuMs: number;
|
|
11
19
|
at: number;
|
|
20
|
+
/** Darwin native start identity and cumulative counters were read successfully. */
|
|
21
|
+
strongIdentity?: true;
|
|
22
|
+
footprintBytes?: number;
|
|
12
23
|
}
|
|
13
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* Copy counters immediately. Bun's `os.cpus()` returns lazy placeholders that read native counters on
|
|
26
|
+
* first property access, so a stored but unread array would silently describe a later instant.
|
|
27
|
+
* @param list Runtime CPU records whose lazy properties must be forced now.
|
|
28
|
+
* @returns Detached per-core counter copies.
|
|
29
|
+
*/
|
|
30
|
+
export declare function cpuSnapshot(list: readonly CpuInfo[]): CpuInfo[];
|
|
31
|
+
/**
|
|
32
|
+
* Compute an aggregate interval, validating each core and counter before summing.
|
|
33
|
+
* @param previous Previous per-core snapshot, if any.
|
|
34
|
+
* @param current Current per-core snapshot.
|
|
35
|
+
* @returns Host utilization in 0..100, or warming for invalid/nonadvancing counters.
|
|
36
|
+
*/
|
|
14
37
|
export declare function hostCpu(previous: CpuInfo[] | undefined, current: CpuInfo[]): Metric<number>;
|
|
15
|
-
/**
|
|
38
|
+
/**
|
|
39
|
+
* Divide CPU milliseconds by monotonic wall milliseconds, not a lifetime/decaying ps average.
|
|
40
|
+
* @param previous Previous authenticated process observation, if present.
|
|
41
|
+
* @param current Current cumulative CPU/identity observation.
|
|
42
|
+
* @returns Interval percentage (100 per core), or warming for reuse/reset/invalid intervals.
|
|
43
|
+
*/
|
|
16
44
|
export declare function processCpu(previous: ProcessCounter | undefined, current: ProcessCounter): Metric<number>;
|
|
17
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
* Bound display names by code point and replace terminal controls; discard directories.
|
|
47
|
+
* @param value Untrusted executable path or basename.
|
|
48
|
+
* @returns At most 128 display-safe basename code points.
|
|
49
|
+
*/
|
|
18
50
|
export declare function safeName(value: string): string;
|
|
19
|
-
/**
|
|
51
|
+
/**
|
|
52
|
+
* Strip the kernel's unlinked-file marker from a Linux executable link.
|
|
53
|
+
* @param target Untrusted /proc/PID/exe link target.
|
|
54
|
+
* @returns Sanitized executable basename without the deleted suffix.
|
|
55
|
+
*/
|
|
56
|
+
export declare function executableName(target: string): string;
|
|
57
|
+
/**
|
|
58
|
+
* Parse Linux stat, skipping the parenthesized comm safely (embedded spaces and ')' characters). comm is
|
|
59
|
+
* NOT a name source: processes rewrite it (`prctl(PR_SET_NAME)`, `/proc/self/comm`, Node's
|
|
60
|
+
* `process.title`). `name` stays ""; callers derive it from `/proc/PID/exe`.
|
|
61
|
+
* @param text Complete proc stat row.
|
|
62
|
+
* @param hz Host CLK_TCK rate in ticks per second.
|
|
63
|
+
* @param at Monotonic observation milliseconds.
|
|
64
|
+
* @returns Parsed identity/CPU counters with unknown name/RSS, or null for invalid data.
|
|
65
|
+
*/
|
|
20
66
|
export declare function linuxStat(text: string, hz: number, at: number): ProcessCounter | null;
|
|
21
|
-
/**
|
|
67
|
+
/**
|
|
68
|
+
* Read RSS from status in KiB, avoiding an assumed host page size.
|
|
69
|
+
* @param text Complete proc status text.
|
|
70
|
+
* @returns Resident bytes, or null when absent/invalid.
|
|
71
|
+
*/
|
|
22
72
|
export declare function linuxRss(text: string): number | null;
|
|
23
|
-
/**
|
|
73
|
+
/**
|
|
74
|
+
* Parse `ps -o pid=,ppid=,lstart=,time=,rss=,ucomm=`. `ucomm` is the kernel's `p_comm`, written only at
|
|
75
|
+
* exec from the executable file name (at most 16 bytes); it is not argv[0] or the process title.
|
|
76
|
+
* Darwin lstart has only one-second identity precision; do not derive interval CPU from it.
|
|
77
|
+
* @param line One fixed-format C-locale ps row.
|
|
78
|
+
* @param at Monotonic observation milliseconds.
|
|
79
|
+
* @returns Metadata/RSS fallback with no native CPU baseline, or null for malformed data.
|
|
80
|
+
*/
|
|
24
81
|
export declare function darwinProcess(line: string, at: number): ProcessCounter | null;
|
|
25
|
-
/**
|
|
82
|
+
/**
|
|
83
|
+
* vm_stat counters are pages, with the page size in the header (16KiB on Apple Silicon).
|
|
84
|
+
* App resident pages = anonymous - purgeable; add wired and physical compressor pages, NOT pages
|
|
85
|
+
* stored in the compressor. Available here means total minus this used estimate, not pressure.
|
|
86
|
+
* @param text C-locale vm_stat output including its page-size header.
|
|
87
|
+
* @param total Host physical RAM in bytes.
|
|
88
|
+
* @returns Validated App+Wired+Compressed usage and its complement, or null on invalid data.
|
|
89
|
+
*/
|
|
90
|
+
export declare function darwinMemory(text: string, total: number): {
|
|
91
|
+
usedBytes: number;
|
|
92
|
+
availableBytes: number;
|
|
93
|
+
basis: "app+wired+compressed";
|
|
94
|
+
} | null;
|
|
95
|
+
/**
|
|
96
|
+
* Parse sysctl's fixed C-locale swapusage format (binary MiB, including fractions).
|
|
97
|
+
* @param text Fixed sysctl vm.swapusage output.
|
|
98
|
+
* @returns Rounded used/allocated bytes, or null for malformed or inconsistent counters.
|
|
99
|
+
*/
|
|
100
|
+
export declare function darwinSwap(text: string): {
|
|
101
|
+
usedBytes: number;
|
|
102
|
+
totalBytes: number;
|
|
103
|
+
} | null;
|
|
104
|
+
/**
|
|
105
|
+
* Parse native PSI percentages and cumulative stall microseconds.
|
|
106
|
+
* @param text Linux memory pressure rows.
|
|
107
|
+
* @returns Valid some/optional full counters, or null for malformed data.
|
|
108
|
+
*/
|
|
26
109
|
export declare function psi(text: string): {
|
|
27
110
|
some: PsiLine;
|
|
28
111
|
full: PsiLine | null;
|