@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/dist/counters.js CHANGED
@@ -1,5 +1,33 @@
1
1
  import { basename } from "node:path";
2
- /** Compute an aggregate interval, validating each core and each counter before summing. */
2
+ /** A >60s native interval is stale/suspend/anomaly territory for ~2s dashboard polling; warm anew.
3
+ * Linux intervals retain their existing semantics and are not subject to this Darwin-only limit.
4
+ */
5
+ export const MAX_NATIVE_INTERVAL_MS = 60_000;
6
+ /** sysctl vm.swapusage reports binary MiB, including fractional values. */
7
+ export const BYTES_PER_MEBIBYTE = 1024 ** 2;
8
+ /** Three separately rounded hundredth-MiB fields can disagree; preserve the existing 0.02MiB bound. */
9
+ export const SWAP_ROUNDING_TOLERANCE_BYTES = 0.02 * BYTES_PER_MEBIBYTE;
10
+ /** Each required vm_stat counter must occur exactly once; duplicates are ambiguous, not additive. */
11
+ const VM_COUNTER_OCCURRENCES = 1;
12
+ /**
13
+ * Copy counters immediately. Bun's `os.cpus()` returns lazy placeholders that read native counters on
14
+ * first property access, so a stored but unread array would silently describe a later instant.
15
+ * @param list Runtime CPU records whose lazy properties must be forced now.
16
+ * @returns Detached per-core counter copies.
17
+ */
18
+ export function cpuSnapshot(list) {
19
+ return list.map(({ model, speed, times }) => ({
20
+ model,
21
+ speed,
22
+ times: { user: times.user, nice: times.nice, sys: times.sys, idle: times.idle, irq: times.irq },
23
+ }));
24
+ }
25
+ /**
26
+ * Compute an aggregate interval, validating each core and counter before summing.
27
+ * @param previous Previous per-core snapshot, if any.
28
+ * @param current Current per-core snapshot.
29
+ * @returns Host utilization in 0..100, or warming for invalid/nonadvancing counters.
30
+ */
3
31
  export function hostCpu(previous, current) {
4
32
  if (!previous || previous.length !== current.length || current.length === 0) {
5
33
  return { state: "warming", reason: "initial sample or CPU topology changed" };
@@ -24,14 +52,22 @@ export function hostCpu(previous, current) {
24
52
  ? { state: "available", value: ((total - idle) / total) * 100 }
25
53
  : { state: "warming", reason: "CPU counters have not advanced" };
26
54
  }
27
- /** CPU milliseconds divided by monotonic wall milliseconds, not a lifetime/decaying ps average. */
55
+ /**
56
+ * Divide CPU milliseconds by monotonic wall milliseconds, not a lifetime/decaying ps average.
57
+ * @param previous Previous authenticated process observation, if present.
58
+ * @param current Current cumulative CPU/identity observation.
59
+ * @returns Interval percentage (100 per core), or warming for reuse/reset/invalid intervals.
60
+ */
28
61
  export function processCpu(previous, current) {
29
- if (!previous || previous.identity !== current.identity)
62
+ if (!previous ||
63
+ previous.identity !== current.identity ||
64
+ (current.strongIdentity && (previous.parentPid !== current.parentPid || previous.name !== current.name)))
30
65
  return { state: "warming", reason: "initial sample or PID reused" };
31
66
  const elapsed = current.at - previous.at;
32
67
  const cpu = current.cpuMs - previous.cpuMs;
33
68
  if (!Number.isFinite(elapsed) ||
34
69
  elapsed <= 0 ||
70
+ (current.strongIdentity && elapsed > MAX_NATIVE_INTERVAL_MS) ||
35
71
  !Number.isFinite(cpu) ||
36
72
  previous.cpuMs < 0 ||
37
73
  current.cpuMs < 0 ||
@@ -40,13 +76,33 @@ export function processCpu(previous, current) {
40
76
  }
41
77
  return { state: "available", value: (cpu / elapsed) * 100 };
42
78
  }
43
- /** Bound display names and strip terminal controls; paths/arguments never leave the parser. */
79
+ /**
80
+ * Bound display names by code point and replace terminal controls; discard directories.
81
+ * @param value Untrusted executable path or basename.
82
+ * @returns At most 128 display-safe basename code points.
83
+ */
44
84
  export function safeName(value) {
45
- return basename(value)
46
- .replace(/[\p{C}]/gu, "?")
47
- .slice(0, 128);
85
+ return Array.from(basename(value).replace(/[\p{C}]/gu, "?"))
86
+ .slice(0, 128)
87
+ .join("");
88
+ }
89
+ /**
90
+ * Strip the kernel's unlinked-file marker from a Linux executable link.
91
+ * @param target Untrusted /proc/PID/exe link target.
92
+ * @returns Sanitized executable basename without the deleted suffix.
93
+ */
94
+ export function executableName(target) {
95
+ return safeName(target.endsWith(" (deleted)") ? target.slice(0, -" (deleted)".length) : target);
48
96
  }
49
- /** Parse Linux stat's parenthesized comm safely, including embedded spaces and ')' characters. */
97
+ /**
98
+ * Parse Linux stat, skipping the parenthesized comm safely (embedded spaces and ')' characters). comm is
99
+ * NOT a name source: processes rewrite it (`prctl(PR_SET_NAME)`, `/proc/self/comm`, Node's
100
+ * `process.title`). `name` stays ""; callers derive it from `/proc/PID/exe`.
101
+ * @param text Complete proc stat row.
102
+ * @param hz Host CLK_TCK rate in ticks per second.
103
+ * @param at Monotonic observation milliseconds.
104
+ * @returns Parsed identity/CPU counters with unknown name/RSS, or null for invalid data.
105
+ */
50
106
  export function linuxStat(text, hz, at) {
51
107
  const start = text.indexOf("(");
52
108
  const end = text.lastIndexOf(")");
@@ -69,14 +125,18 @@ export function linuxStat(text, hz, at) {
69
125
  return {
70
126
  pid,
71
127
  parentPid,
72
- name: safeName(text.slice(start + 1, end)),
128
+ name: "",
73
129
  identity: `${pid}:${identity}`,
74
130
  rssBytes: 0,
75
131
  cpuMs: ((user + system) / hz) * 1000,
76
132
  at,
77
133
  };
78
134
  }
79
- /** RSS comes from status in KiB, avoiding an assumed host page size. */
135
+ /**
136
+ * Read RSS from status in KiB, avoiding an assumed host page size.
137
+ * @param text Complete proc status text.
138
+ * @returns Resident bytes, or null when absent/invalid.
139
+ */
80
140
  export function linuxRss(text) {
81
141
  const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(text);
82
142
  if (!match?.[1])
@@ -84,7 +144,14 @@ export function linuxRss(text) {
84
144
  const bytes = Number(match[1]) * 1024;
85
145
  return Number.isSafeInteger(bytes) ? bytes : null;
86
146
  }
87
- /** Darwin lstart has only one-second identity precision; do not derive interval CPU from it. */
147
+ /**
148
+ * Parse `ps -o pid=,ppid=,lstart=,time=,rss=,ucomm=`. `ucomm` is the kernel's `p_comm`, written only at
149
+ * exec from the executable file name (at most 16 bytes); it is not argv[0] or the process title.
150
+ * Darwin lstart has only one-second identity precision; do not derive interval CPU from it.
151
+ * @param line One fixed-format C-locale ps row.
152
+ * @param at Monotonic observation milliseconds.
153
+ * @returns Metadata/RSS fallback with no native CPU baseline, or null for malformed data.
154
+ */
88
155
  export function darwinProcess(line, at) {
89
156
  const match = /^\s*(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(\S+)\s+(\d+)\s+(.*?)\s*$/.exec(line);
90
157
  if (!match?.[1] || !match[2] || !match[3] || !match[5] || match[6] === undefined)
@@ -96,7 +163,66 @@ export function darwinProcess(line, at) {
96
163
  return null;
97
164
  return { pid, parentPid, rssBytes, identity: `${pid}:${match[3]}`, name: safeName(match[6]), cpuMs: 0, at };
98
165
  }
99
- /** Parse native PSI percentages and cumulative stall microseconds, rejecting malformed values. */
166
+ /**
167
+ * vm_stat counters are pages, with the page size in the header (16KiB on Apple Silicon).
168
+ * App resident pages = anonymous - purgeable; add wired and physical compressor pages, NOT pages
169
+ * stored in the compressor. Available here means total minus this used estimate, not pressure.
170
+ * @param text C-locale vm_stat output including its page-size header.
171
+ * @param total Host physical RAM in bytes.
172
+ * @returns Validated App+Wired+Compressed usage and its complement, or null on invalid data.
173
+ */
174
+ export function darwinMemory(text, total) {
175
+ const [, pageSizeText] = /^Mach Virtual Memory Statistics: \(page size of (\d+) bytes\)\r?$/m.exec(text) ?? [];
176
+ const pageSize = Number(pageSizeText);
177
+ if (!Number.isSafeInteger(total) || total <= 0 || !Number.isSafeInteger(pageSize) || pageSize <= 0)
178
+ return null;
179
+ /**
180
+ * Read one uniquely present unsigned page count.
181
+ * @param name Exact vm_stat row label, excluding the colon.
182
+ * @returns Page count, or null for missing/duplicate/malformed rows.
183
+ */
184
+ const read = (name) => {
185
+ const rows = text.split("\n").filter((line) => line.startsWith(`${name}:`));
186
+ const [row] = rows;
187
+ const [, value] = rows.length === VM_COUNTER_OCCURRENCES ? (/^.*:\s+(\d+)\.\s*$/.exec(row ?? "") ?? []) : [];
188
+ const count = value === undefined ? Number.NaN : Number(value);
189
+ return Number.isSafeInteger(count) && count >= 0 ? count : null;
190
+ };
191
+ const anonymous = read("Anonymous pages");
192
+ const purgeable = read("Pages purgeable");
193
+ const wired = read("Pages wired down");
194
+ const compressed = read("Pages occupied by compressor");
195
+ if (anonymous === null || purgeable === null || wired === null || compressed === null || purgeable > anonymous)
196
+ return null;
197
+ const usedBytes = (anonymous - purgeable + wired + compressed) * pageSize;
198
+ if (!Number.isSafeInteger(usedBytes) || usedBytes < 0 || usedBytes > total)
199
+ return null;
200
+ return { usedBytes, availableBytes: total - usedBytes, basis: "app+wired+compressed" };
201
+ }
202
+ /**
203
+ * Parse sysctl's fixed C-locale swapusage format (binary MiB, including fractions).
204
+ * @param text Fixed sysctl vm.swapusage output.
205
+ * @returns Rounded used/allocated bytes, or null for malformed or inconsistent counters.
206
+ */
207
+ export function darwinSwap(text) {
208
+ const match = /^vm\.swapusage: total = (\d+\.\d+)M\s+used = (\d+\.\d+)M\s+free = (\d+\.\d+)M(?:\s+\(encrypted\))?\s*$/.exec(text);
209
+ if (!match)
210
+ return null;
211
+ const [, totalMebibytes, usedMebibytes, freeMebibytes] = match;
212
+ const totalBytes = Math.round(Number(totalMebibytes) * BYTES_PER_MEBIBYTE);
213
+ const usedBytes = Math.round(Number(usedMebibytes) * BYTES_PER_MEBIBYTE);
214
+ const freeBytes = Math.round(Number(freeMebibytes) * BYTES_PER_MEBIBYTE);
215
+ if (![totalBytes, usedBytes, freeBytes].every(Number.isSafeInteger) ||
216
+ usedBytes > totalBytes ||
217
+ Math.abs(totalBytes - usedBytes - freeBytes) > SWAP_ROUNDING_TOLERANCE_BYTES)
218
+ return null;
219
+ return { usedBytes, totalBytes };
220
+ }
221
+ /**
222
+ * Parse native PSI percentages and cumulative stall microseconds.
223
+ * @param text Linux memory pressure rows.
224
+ * @returns Valid some/optional full counters, or null for malformed data.
225
+ */
100
226
  export function psi(text) {
101
227
  const rows = new Map();
102
228
  for (const line of text.trim().split("\n")) {
@@ -0,0 +1,95 @@
1
+ import type { Budget } from "./collect.js";
2
+ import { type ProcessCounter } from "./counters.js";
3
+ /** Fixed Darwin LP64 ABI from sys/proc_info.h, sys/resource.h and mach/mach_time.h. */
4
+ export declare const DARWIN_ABI: {
5
+ /** proc_pid_rusage and mach_timebase_info return zero on success. */
6
+ readonly success: 0;
7
+ /** Kernel start/exit time zero means unset; a live process must have a nonzero start. */
8
+ readonly unsetTime: 0n;
9
+ /** C p_comm terminates at the first NUL byte, not the end of its fixed buffer. */
10
+ readonly nulByte: 0;
11
+ readonly bsd: {
12
+ /** sizeof(struct proc_bsdinfo), including fields we deliberately never decode. */
13
+ readonly bytes: 136;
14
+ /** PROC_PIDTBSDINFO flavor for proc_pidinfo. */
15
+ readonly flavor: 3;
16
+ /** This flavor has no auxiliary argument. */
17
+ readonly argument: 0n;
18
+ /** uint32_t pbi_pid byte offset. */
19
+ readonly pid: 12;
20
+ /** uint32_t pbi_ppid byte offset. */
21
+ readonly parentPid: 16;
22
+ /** char pbi_comm[MAXCOMLEN] starts here; pbi_name is NOT a name source. */
23
+ readonly comm: 48;
24
+ /** MAXCOMLEN bytes, excluding any adjacent pbi_name field. */
25
+ readonly commBytes: 16;
26
+ /** uint64_t pbi_start_tvsec byte offset. */
27
+ readonly startSeconds: 120;
28
+ /** uint64_t pbi_start_tvusec byte offset. */
29
+ readonly startMicros: 128;
30
+ };
31
+ readonly usage: {
32
+ /** sizeof(struct rusage_info_v0); later flavors are not requested. */
33
+ readonly bytes: 96;
34
+ /** RUSAGE_INFO_V0 flavor, providing CPU, footprint and start/exit identity. */
35
+ readonly flavor: 0;
36
+ /** uint64_t ri_user_time (Mach ticks) byte offset. */
37
+ readonly userTicks: 16;
38
+ /** uint64_t ri_system_time (Mach ticks) byte offset. */
39
+ readonly systemTicks: 24;
40
+ /** uint64_t ri_resident_size byte offset. */
41
+ readonly residentBytes: 64;
42
+ /** uint64_t ri_phys_footprint byte offset. */
43
+ readonly footprintBytes: 72;
44
+ /** uint64_t ri_proc_start_abstime byte offset. */
45
+ readonly startTicks: 80;
46
+ /** uint64_t ri_proc_exit_abstime byte offset. */
47
+ readonly exitTicks: 88;
48
+ };
49
+ readonly timebase: {
50
+ /** sizeof(mach_timebase_info_data_t), two uint32_t fields. */
51
+ readonly bytes: 8;
52
+ /** uint32_t numer byte offset. */
53
+ readonly numerator: 0;
54
+ /** uint32_t denom byte offset. */
55
+ readonly denominator: 4;
56
+ };
57
+ };
58
+ /** Charge every admitted fixed buffer, including failed syscalls, against the shared scan budget. */
59
+ export declare const DARWIN_NATIVE_READ_BYTES: number;
60
+ /** Convert native Mach-derived nanoseconds into the sampler's cumulative CPU milliseconds. */
61
+ export declare const NANOSECONDS_PER_MILLISECOND = 1000000;
62
+ /** The pbi_start_tvusec field must be strictly smaller than one second of microseconds. */
63
+ export declare const MICROSECONDS_PER_SECOND = 1000000n;
64
+ /** Runtime-independent fixed native bindings; the loader owns the returned library handle. */
65
+ export interface NativeCalls {
66
+ bsd(pid: number, buffer: Buffer): number;
67
+ usage(pid: number, buffer: Buffer): number;
68
+ timebase(buffer: Buffer): number;
69
+ close(): void;
70
+ }
71
+ /**
72
+ * Identity-check metadata between two rusage reads. Start absolute ticks distinguish same-second PID
73
+ * reuse; microsecond start, parent and exact p_comm bytes also participate. No sanitized-name collision
74
+ * can authenticate a baseline. Rusage CPU counters are Mach ticks; convert with mach_timebase_info,
75
+ * not an assumed nanosecond tick (Apple Silicon here reports 125/3 nanoseconds per tick).
76
+ * @param pid Expected process identifier from the bounded metadata enumeration.
77
+ * @param before First fixed rusage_info_v0 frame.
78
+ * @param bsd Intervening fixed proc_bsdinfo frame.
79
+ * @param after Second fixed rusage_info_v0 frame.
80
+ * @param at Monotonic observation time in milliseconds.
81
+ * @param ticksToNs Positive Mach timebase ratio, in nanoseconds per tick.
82
+ * @returns A strong-identity counter, or null for malformed/changed/invalid native data.
83
+ */
84
+ export declare function darwinNativeCounter(pid: number, before: Buffer, bsd: Buffer, after: Buffer, at: number, ticksToNs: number): ProcessCounter | null;
85
+ /**
86
+ * Enrich bounded ps rows with cheap native counters, retaining RSS/name rows when access fails.
87
+ * Charge all admitted fixed syscall buffers to the SAME scan budget, including unsuccessful reads.
88
+ * Synchronous syscalls, like os.cpus(), cannot be preempted; check admission before each PID.
89
+ * @param rows Bounded ps fallback rows, enriched in place only on successful native reads.
90
+ * @param budget Shared byte/deadline/abort admission state, charged even for failed syscalls.
91
+ * @param load Lazy native binding dependency; defaults to the platform's builtin FFI adapter.
92
+ * @returns The same array, retaining original rows for inaccessible or rejected PIDs.
93
+ * @throws If the shared abort signal is observed between native calls.
94
+ */
95
+ export declare function darwinNativeProcesses(rows: ProcessCounter[], budget: Budget, load?: () => NativeCalls | undefined): ProcessCounter[];
package/dist/darwin.js ADDED
@@ -0,0 +1,254 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import { safeName } from "./counters.js";
3
+ /** Fixed Darwin LP64 ABI from sys/proc_info.h, sys/resource.h and mach/mach_time.h. */
4
+ export const DARWIN_ABI = {
5
+ /** proc_pid_rusage and mach_timebase_info return zero on success. */
6
+ success: 0,
7
+ /** Kernel start/exit time zero means unset; a live process must have a nonzero start. */
8
+ unsetTime: 0n,
9
+ /** C p_comm terminates at the first NUL byte, not the end of its fixed buffer. */
10
+ nulByte: 0,
11
+ bsd: {
12
+ /** sizeof(struct proc_bsdinfo), including fields we deliberately never decode. */
13
+ bytes: 136,
14
+ /** PROC_PIDTBSDINFO flavor for proc_pidinfo. */
15
+ flavor: 3,
16
+ /** This flavor has no auxiliary argument. */
17
+ argument: 0n,
18
+ /** uint32_t pbi_pid byte offset. */
19
+ pid: 12,
20
+ /** uint32_t pbi_ppid byte offset. */
21
+ parentPid: 16,
22
+ /** char pbi_comm[MAXCOMLEN] starts here; pbi_name is NOT a name source. */
23
+ comm: 48,
24
+ /** MAXCOMLEN bytes, excluding any adjacent pbi_name field. */
25
+ commBytes: 16,
26
+ /** uint64_t pbi_start_tvsec byte offset. */
27
+ startSeconds: 120,
28
+ /** uint64_t pbi_start_tvusec byte offset. */
29
+ startMicros: 128,
30
+ },
31
+ usage: {
32
+ /** sizeof(struct rusage_info_v0); later flavors are not requested. */
33
+ bytes: 96,
34
+ /** RUSAGE_INFO_V0 flavor, providing CPU, footprint and start/exit identity. */
35
+ flavor: 0,
36
+ /** uint64_t ri_user_time (Mach ticks) byte offset. */
37
+ userTicks: 16,
38
+ /** uint64_t ri_system_time (Mach ticks) byte offset. */
39
+ systemTicks: 24,
40
+ /** uint64_t ri_resident_size byte offset. */
41
+ residentBytes: 64,
42
+ /** uint64_t ri_phys_footprint byte offset. */
43
+ footprintBytes: 72,
44
+ /** uint64_t ri_proc_start_abstime byte offset. */
45
+ startTicks: 80,
46
+ /** uint64_t ri_proc_exit_abstime byte offset. */
47
+ exitTicks: 88,
48
+ },
49
+ timebase: {
50
+ /** sizeof(mach_timebase_info_data_t), two uint32_t fields. */
51
+ bytes: 8,
52
+ /** uint32_t numer byte offset. */
53
+ numerator: 0,
54
+ /** uint32_t denom byte offset. */
55
+ denominator: 4,
56
+ },
57
+ };
58
+ /** Rusage reads bracket the single metadata read to reject identity changes during collection. */
59
+ const RUSAGE_READS_PER_PID = 2;
60
+ /** Charge every admitted fixed buffer, including failed syscalls, against the shared scan budget. */
61
+ export const DARWIN_NATIVE_READ_BYTES = DARWIN_ABI.bsd.bytes + RUSAGE_READS_PER_PID * DARWIN_ABI.usage.bytes;
62
+ /** Convert native Mach-derived nanoseconds into the sampler's cumulative CPU milliseconds. */
63
+ export const NANOSECONDS_PER_MILLISECOND = 1_000_000;
64
+ /** The pbi_start_tvusec field must be strictly smaller than one second of microseconds. */
65
+ export const MICROSECONDS_PER_SECOND = 1000000n;
66
+ /**
67
+ * Load only fixed native symbols, lazily; unsupported runtimes retain unavailable process metrics.
68
+ * @returns Owned syscall bindings, or undefined for unsupported platform/architecture/runtime.
69
+ * @throws If opening the runtime FFI library fails.
70
+ */
71
+ function nativeCalls() {
72
+ if (process.platform !== "darwin" || !["arm64", "x64"].includes(process.arch))
73
+ return undefined;
74
+ if (process.versions.bun) {
75
+ const ffi = process.getBuiltinModule("bun:ffi");
76
+ if (!ffi)
77
+ return undefined;
78
+ const lib = ffi.dlopen("/usr/lib/libproc.dylib", {
79
+ proc_pidinfo: { args: ["i32", "i32", "u64", "ptr", "i32"], returns: "i32" },
80
+ proc_pid_rusage: { args: ["i32", "i32", "ptr"], returns: "i32" },
81
+ mach_timebase_info: { args: ["ptr"], returns: "i32" },
82
+ });
83
+ return {
84
+ timebase: (buffer) => lib.symbols.mach_timebase_info(ffi.ptr(buffer)),
85
+ bsd: (pid, buffer) => lib.symbols.proc_pidinfo(pid, DARWIN_ABI.bsd.flavor, DARWIN_ABI.bsd.argument, ffi.ptr(buffer), DARWIN_ABI.bsd.bytes),
86
+ usage: (pid, buffer) => lib.symbols.proc_pid_rusage(pid, DARWIN_ABI.usage.flavor, ffi.ptr(buffer)),
87
+ close: () => lib.close(),
88
+ };
89
+ }
90
+ const ffi = process.getBuiltinModule("node:ffi");
91
+ if (!ffi)
92
+ return undefined;
93
+ const lib = ffi.dlopen("/usr/lib/libproc.dylib", {
94
+ proc_pidinfo: { arguments: ["i32", "i32", "u64", "pointer", "i32"], return: "i32" },
95
+ proc_pid_rusage: { arguments: ["i32", "i32", "pointer"], return: "i32" },
96
+ mach_timebase_info: { arguments: ["pointer"], return: "i32" },
97
+ });
98
+ return {
99
+ timebase: (buffer) => lib.functions.mach_timebase_info(buffer),
100
+ bsd: (pid, buffer) => lib.functions.proc_pidinfo(pid, DARWIN_ABI.bsd.flavor, DARWIN_ABI.bsd.argument, buffer, DARWIN_ABI.bsd.bytes),
101
+ usage: (pid, buffer) => lib.functions.proc_pid_rusage(pid, DARWIN_ABI.usage.flavor, buffer),
102
+ close: () => lib.lib.close(),
103
+ };
104
+ }
105
+ /**
106
+ * Initialize the Mach timebase; close the owned library on failure, including runtime throws.
107
+ * @param load Lazy runtime binding loader, shared by production and deterministic failure tests.
108
+ * @returns Owned bindings with nanoseconds per tick, or undefined when unavailable/invalid.
109
+ * @throws If opening or initializing FFI throws (the caller retains fallback rows).
110
+ */
111
+ function nativeLibrary(load) {
112
+ const lib = load();
113
+ if (!lib)
114
+ return undefined;
115
+ let initialized = false;
116
+ try {
117
+ const timebase = Buffer.alloc(DARWIN_ABI.timebase.bytes);
118
+ if (lib.timebase(timebase) !== DARWIN_ABI.success ||
119
+ timebase.readUInt32LE(DARWIN_ABI.timebase.numerator) === 0 ||
120
+ timebase.readUInt32LE(DARWIN_ABI.timebase.denominator) === 0)
121
+ return undefined;
122
+ initialized = true;
123
+ return {
124
+ ...lib,
125
+ ticksToNs: timebase.readUInt32LE(DARWIN_ABI.timebase.numerator) / timebase.readUInt32LE(DARWIN_ABI.timebase.denominator),
126
+ };
127
+ }
128
+ finally {
129
+ if (!initialized)
130
+ lib.close();
131
+ }
132
+ }
133
+ /**
134
+ * Identity-check metadata between two rusage reads. Start absolute ticks distinguish same-second PID
135
+ * reuse; microsecond start, parent and exact p_comm bytes also participate. No sanitized-name collision
136
+ * can authenticate a baseline. Rusage CPU counters are Mach ticks; convert with mach_timebase_info,
137
+ * not an assumed nanosecond tick (Apple Silicon here reports 125/3 nanoseconds per tick).
138
+ * @param pid Expected process identifier from the bounded metadata enumeration.
139
+ * @param before First fixed rusage_info_v0 frame.
140
+ * @param bsd Intervening fixed proc_bsdinfo frame.
141
+ * @param after Second fixed rusage_info_v0 frame.
142
+ * @param at Monotonic observation time in milliseconds.
143
+ * @param ticksToNs Positive Mach timebase ratio, in nanoseconds per tick.
144
+ * @returns A strong-identity counter, or null for malformed/changed/invalid native data.
145
+ */
146
+ export function darwinNativeCounter(pid, before, bsd, after, at, ticksToNs) {
147
+ if (!Number.isFinite(ticksToNs) || ticksToNs <= 0)
148
+ return null;
149
+ if (before.length !== DARWIN_ABI.usage.bytes ||
150
+ after.length !== DARWIN_ABI.usage.bytes ||
151
+ bsd.length !== DARWIN_ABI.bsd.bytes)
152
+ return null;
153
+ const start = after.readBigUInt64LE(DARWIN_ABI.usage.startTicks);
154
+ if (start === DARWIN_ABI.unsetTime ||
155
+ before.readBigUInt64LE(DARWIN_ABI.usage.startTicks) !== start ||
156
+ bsd.readUInt32LE(DARWIN_ABI.bsd.pid) !== pid)
157
+ return null;
158
+ if (before.readBigUInt64LE(DARWIN_ABI.usage.exitTicks) !== DARWIN_ABI.unsetTime ||
159
+ after.readBigUInt64LE(DARWIN_ABI.usage.exitTicks) !== DARWIN_ABI.unsetTime)
160
+ return null;
161
+ const seconds = bsd.readBigUInt64LE(DARWIN_ABI.bsd.startSeconds);
162
+ const micros = bsd.readBigUInt64LE(DARWIN_ABI.bsd.startMicros);
163
+ if (seconds === DARWIN_ABI.unsetTime || micros >= MICROSECONDS_PER_SECOND)
164
+ return null;
165
+ /** Cumulative user/system Mach ticks from one size-checked rusage frame. */
166
+ const beforeCpu = before.readBigUInt64LE(DARWIN_ABI.usage.userTicks) + before.readBigUInt64LE(DARWIN_ABI.usage.systemTicks);
167
+ const afterCpu = after.readBigUInt64LE(DARWIN_ABI.usage.userTicks) + after.readBigUInt64LE(DARWIN_ABI.usage.systemTicks);
168
+ const cpuMs = afterCpu < beforeCpu ? Number.NaN : (Number(afterCpu) * ticksToNs) / NANOSECONDS_PER_MILLISECOND;
169
+ const rssBytes = Number(after.readBigUInt64LE(DARWIN_ABI.usage.residentBytes));
170
+ const footprintBytes = Number(after.readBigUInt64LE(DARWIN_ABI.usage.footprintBytes));
171
+ if (![rssBytes, footprintBytes].every(Number.isSafeInteger) || !Number.isFinite(cpuMs) || !Number.isFinite(at))
172
+ return null;
173
+ const parentPid = bsd.readUInt32LE(DARWIN_ABI.bsd.parentPid);
174
+ const rawName = bsd.subarray(DARWIN_ABI.bsd.comm, DARWIN_ABI.bsd.comm + DARWIN_ABI.bsd.commBytes);
175
+ const nul = rawName.indexOf(DARWIN_ABI.nulByte);
176
+ const nameBytes = nul < 0 ? rawName : rawName.subarray(0, nul);
177
+ return {
178
+ pid,
179
+ parentPid,
180
+ name: safeName(nameBytes.toString("utf8")),
181
+ identity: `${pid}:native:${start}:${seconds}:${micros}:${parentPid}:${nameBytes.toString("hex")}`,
182
+ rssBytes,
183
+ footprintBytes,
184
+ cpuMs,
185
+ at,
186
+ strongIdentity: true,
187
+ };
188
+ }
189
+ /**
190
+ * Enrich bounded ps rows with cheap native counters, retaining RSS/name rows when access fails.
191
+ * Charge all admitted fixed syscall buffers to the SAME scan budget, including unsuccessful reads.
192
+ * Synchronous syscalls, like os.cpus(), cannot be preempted; check admission before each PID.
193
+ * @param rows Bounded ps fallback rows, enriched in place only on successful native reads.
194
+ * @param budget Shared byte/deadline/abort admission state, charged even for failed syscalls.
195
+ * @param load Lazy native binding dependency; defaults to the platform's builtin FFI adapter.
196
+ * @returns The same array, retaining original rows for inaccessible or rejected PIDs.
197
+ * @throws If the shared abort signal is observed between native calls.
198
+ */
199
+ export function darwinNativeProcesses(rows, budget, load = nativeCalls) {
200
+ if (!budget.ready())
201
+ return rows;
202
+ if (budget.maxBytes - budget.bytesRead < DARWIN_ABI.timebase.bytes) {
203
+ budget.bytesRead = budget.maxBytes;
204
+ budget.reasons.add("byte-limit");
205
+ return rows;
206
+ }
207
+ budget.bytesRead += DARWIN_ABI.timebase.bytes;
208
+ let lib;
209
+ try {
210
+ lib = nativeLibrary(load);
211
+ }
212
+ catch {
213
+ return rows;
214
+ }
215
+ if (!lib)
216
+ return rows;
217
+ try {
218
+ for (let i = 0; i < rows.length; i++) {
219
+ if (!budget.ready())
220
+ break;
221
+ if (budget.maxBytes - budget.bytesRead < DARWIN_NATIVE_READ_BYTES) {
222
+ budget.bytesRead = budget.maxBytes;
223
+ budget.reasons.add("byte-limit");
224
+ break;
225
+ }
226
+ budget.bytesRead += DARWIN_NATIVE_READ_BYTES;
227
+ const row = rows[i];
228
+ if (!row)
229
+ continue;
230
+ const before = Buffer.alloc(DARWIN_ABI.usage.bytes);
231
+ const bsd = Buffer.alloc(DARWIN_ABI.bsd.bytes);
232
+ const after = Buffer.alloc(DARWIN_ABI.usage.bytes);
233
+ try {
234
+ if (lib.usage(row.pid, before) !== DARWIN_ABI.success ||
235
+ !budget.ready() ||
236
+ lib.bsd(row.pid, bsd) !== DARWIN_ABI.bsd.bytes ||
237
+ !budget.ready() ||
238
+ lib.usage(row.pid, after) !== DARWIN_ABI.success)
239
+ continue;
240
+ const counter = darwinNativeCounter(row.pid, before, bsd, after, performance.now(), lib.ticksToNs);
241
+ if (counter)
242
+ rows[i] = counter;
243
+ }
244
+ catch {
245
+ // Runtime FFI failures belong to this PID, not the entire already-collected ps list.
246
+ budget.signal.throwIfAborted();
247
+ }
248
+ }
249
+ return rows;
250
+ }
251
+ finally {
252
+ lib.close();
253
+ }
254
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  import type { ResourceSampler, SamplerOptions } from "./types.js";
2
2
  export type { Metric, ProcessSample, PsiLine, ResourceSampler, ResourceSnapshot, SamplerOptions } from "./types.js";
3
- /** Create an isolated, passive sampler. No timers or child processes exist until sample(). */
3
+ /**
4
+ * Create an isolated, passive sampler. No timers or children exist until sample().
5
+ * @param options Optional validated scan limits.
6
+ * @returns Sampler owning its own baselines and awaited collection/disposal lifecycle.
7
+ */
4
8
  export declare function createResourceSampler(options?: SamplerOptions): ResourceSampler;
package/dist/index.js CHANGED
@@ -1,15 +1,26 @@
1
1
  import { cpus, freemem, loadavg, platform, totalmem } from "node:os";
2
2
  import { performance } from "node:perf_hooks";
3
- import { Budget, command, darwinProcesses, linuxProcesses, pressure } from "./collect.js";
4
- import { hostCpu, processCpu } from "./counters.js";
5
- /** Validate bounded integers before collecting any host information. */
3
+ import { Budget, command, darwinHostMemory, darwinProcesses, linuxProcesses, pressure } from "./collect.js";
4
+ import { cpuSnapshot, hostCpu, processCpu } from "./counters.js";
5
+ /**
6
+ * Validate bounded integers before collecting host information.
7
+ * @param value Requested bound, if supplied.
8
+ * @param fallback Default bound when absent.
9
+ * @param min Inclusive lower bound.
10
+ * @param max Inclusive upper bound.
11
+ * @returns Validated integer; throws RangeError for invalid input.
12
+ */
6
13
  function bounded(value, fallback, min, max) {
7
14
  const result = value ?? fallback;
8
15
  if (!Number.isInteger(result) || result < min || result > max)
9
16
  throw new RangeError(`Sampler bound must be an integer from ${min} to ${max}`);
10
17
  return result;
11
18
  }
12
- /** Create an isolated, passive sampler. No timers or child processes exist until sample(). */
19
+ /**
20
+ * Create an isolated, passive sampler. No timers or children exist until sample().
21
+ * @param options Optional validated scan limits.
22
+ * @returns Sampler owning its own baselines and awaited collection/disposal lifecycle.
23
+ */
13
24
  export function createResourceSampler(options = {}) {
14
25
  const duration = bounded(options.maxDurationMs, 250, 10, 5000);
15
26
  const maxPids = bounded(options.maxPids, 2048, 1, 16384);
@@ -22,16 +33,23 @@ export function createResourceSampler(options = {}) {
22
33
  let active;
23
34
  let controller;
24
35
  let disposed = false;
36
+ /**
37
+ * Collect one scan and advance baselines only after successful completion.
38
+ * @param signal Combined caller/disposal cancellation signal.
39
+ * @returns Typed snapshot with explicit coverage and metric availability; aborts reject.
40
+ */
25
41
  async function collect(signal) {
26
42
  const start = performance.now();
27
43
  const wallTimeMs = Date.now();
28
44
  const budget = new Budget(start + duration, maxBytes, maxPids, signal);
29
45
  signal.throwIfAborted();
30
- const currentCpus = cpus();
46
+ const currentCpus = cpuSnapshot(cpus());
31
47
  const cpu = previousTime !== undefined && start <= previousTime
32
48
  ? { state: "warming", reason: "invalid monotonic interval" }
33
49
  : hostCpu(previousCpus, currentCpus);
34
50
  const nativePressure = await pressure(budget, host);
51
+ const totalBytes = totalmem();
52
+ const nativeMemory = host === "darwin" ? await darwinHostMemory(budget, totalBytes) : {};
35
53
  let counters = [];
36
54
  try {
37
55
  if (host === "linux") {
@@ -62,10 +80,17 @@ export function createResourceSampler(options = {}) {
62
80
  name: counter.name,
63
81
  identity: counter.identity,
64
82
  rssBytes: counter.rssBytes,
65
- cpu: host === "darwin"
83
+ ...(host === "darwin"
84
+ ? {
85
+ footprint: counter.footprintBytes === undefined
86
+ ? { state: "unavailable", reason: "native footprint inaccessible or builtin FFI unavailable" }
87
+ : { state: "available", value: counter.footprintBytes },
88
+ }
89
+ : {}),
90
+ cpu: host === "darwin" && !counter.strongIdentity
66
91
  ? {
67
92
  state: "unavailable",
68
- reason: "ps start identity precision is one second; PID reuse cannot be excluded",
93
+ reason: "native counters inaccessible or builtin FFI unavailable; ps identity has only whole seconds",
69
94
  }
70
95
  : processCpu(previousProcesses.get(counter.pid), counter),
71
96
  }));
@@ -84,7 +109,7 @@ export function createResourceSampler(options = {}) {
84
109
  cpu,
85
110
  logicalCpus: currentCpus.length,
86
111
  loadAverage: host === "win32" ? [] : loadavg(),
87
- memory: { totalBytes: totalmem(), freeBytes: freemem() },
112
+ memory: { totalBytes, freeBytes: freemem(), ...nativeMemory },
88
113
  processes,
89
114
  coverage: {
90
115
  complete: budget.reasons.size === 0,
@@ -98,6 +123,11 @@ export function createResourceSampler(options = {}) {
98
123
  };
99
124
  }
100
125
  return {
126
+ /**
127
+ * Start the sole active sample.
128
+ * @param signal Optional caller cancellation signal.
129
+ * @returns Snapshot promise, rejecting on concurrent/disposed use or cancellation.
130
+ */
101
131
  sample(signal) {
102
132
  if (disposed)
103
133
  return Promise.reject(new Error("Resource sampler is disposed"));
@@ -105,6 +135,7 @@ export function createResourceSampler(options = {}) {
105
135
  return Promise.reject(new Error("Resource sampler already has an active sample"));
106
136
  controller = new AbortController();
107
137
  const local = controller;
138
+ /** @returns Nothing; forward caller cancellation to this scan. */
108
139
  const abort = () => local.abort(signal?.reason);
109
140
  if (signal?.aborted)
110
141
  abort();
@@ -116,6 +147,7 @@ export function createResourceSampler(options = {}) {
116
147
  });
117
148
  return active;
118
149
  },
150
+ /** @returns Cleanup completion after aborting any scan and clearing baselines. */
119
151
  async dispose() {
120
152
  disposed = true;
121
153
  controller?.abort();