@nredd/pi-resource-sampler 0.2.0 → 0.2.2
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 +29 -9
- package/dist/collect.d.ts +5 -1
- package/dist/collect.js +11 -10
- package/dist/counters.js +5 -3
- package/dist/darwin.d.ts +15 -0
- package/dist/darwin.js +7 -9
- package/package.json +7 -10
package/README.md
CHANGED
|
@@ -4,8 +4,11 @@ Pi-independent, dependency-free ESM library for passive host resource dashboards
|
|
|
4
4
|
`@nredd/pi-resource-sampler` is not a Pi extension. No tools, timers, hooks, output or policy are
|
|
5
5
|
registered. Runs on Node >=22.14 and Bun.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
Current `0.2.1` provides native Darwin interval CPU/footprint and host used/swap metrics, plus
|
|
8
|
+
names-only Linux `/proc` enumeration. Consumers pin exact registry dependencies, never workspace links.
|
|
9
|
+
Avoid `0.2.0` on Linux: its `opendir` listing can fail when a PID exits mid-iteration, losing the
|
|
10
|
+
process list and next-sample CPU baseline. The current names-only enumeration skips that process
|
|
11
|
+
rather than failing the scan.
|
|
9
12
|
|
|
10
13
|
Upgrade from `0.1.0`, which is unsafe: on Darwin it reported `ps -c -o comm`, the basename of argv[0],
|
|
11
14
|
so a launcher-chosen argv[0] or Node `process.title` (e.g. `npm exec <package> mcp`) leaked into
|
|
@@ -52,7 +55,7 @@ Semantics:
|
|
|
52
55
|
with identical parent/name and nondecreasing CPU. Each observation has its own monotonic timestamp.
|
|
53
56
|
Identity/parent/name changes, negative deltas, nonpositive/nonfinite intervals and native intervals
|
|
54
57
|
over 60s warm instead of fabricating CPU. Native CPU counters are Mach ticks converted using the
|
|
55
|
-
kernel timebase
|
|
58
|
+
kernel-reported timebase, NOT assumed nanoseconds.
|
|
56
59
|
- `processes[].footprint` is an optional Darwin metric from `ri_phys_footprint`, including compressed
|
|
57
60
|
memory. Native `rssBytes` comes from `ri_resident_size`. Inaccessible/exited/reused PIDs or exhausted
|
|
58
61
|
native budgets retain the enumerated metadata/RSS row with unavailable CPU/footprint; unsupported
|
|
@@ -94,8 +97,12 @@ Semantics:
|
|
|
94
97
|
Bounds:
|
|
95
98
|
|
|
96
99
|
- Default scan budget 250ms, 2048 PIDs, 2MiB captured bytes; options allow at most 5s, 16384 PIDs,
|
|
97
|
-
16MiB. Linux proc files read sequentially (concurrency one), at most 8KiB each.
|
|
98
|
-
|
|
100
|
+
16MiB. Linux proc files read sequentially (concurrency one), at most 8KiB each. Linux lists `/proc`
|
|
101
|
+
names only, never `opendir` Dirents: a PID that exits mid-listing comes back `DT_UNKNOWN` and the
|
|
102
|
+
runtime would `lstat` it, so it is instead one skipped row (`process-unreadable-or-changed`) when
|
|
103
|
+
its own stat read fails. RESIDUAL: that one `readdir` is read whole (one short name per process,
|
|
104
|
+
e.g. ~100KiB at 16384 PIDs) before the PID cap, deadline or abort can apply; per-PID reads stop at
|
|
105
|
+
the budget; Darwin output stops at the PID/output budget and reaps the fixed helper. Native reads charge
|
|
99
106
|
8 bytes for the timebase and 328 bytes per admitted PID (two 96-byte rusage buffers and one 136-byte
|
|
100
107
|
metadata buffer), including failed calls, to that SAME byte budget. Only `pbi_comm` and numeric
|
|
101
108
|
fields are inspected; `pbi_name`, arguments and environment are never decoded or exported. Native
|
|
@@ -119,8 +126,7 @@ Bounds:
|
|
|
119
126
|
immediate SIGKILL on abort/deadline/cap, and resolve only on close. No persistent children or workers.
|
|
120
127
|
- Unsupported platforms keep native host metrics but report process coverage unavailable.
|
|
121
128
|
|
|
122
|
-
|
|
123
|
-
[here](../../docs/mon-accuracy.md). Process `rssBytes` still excludes compressed pages; it is not
|
|
129
|
+
Process `rssBytes` still excludes compressed pages; it is not
|
|
124
130
|
Activity Monitor's physical footprint; use the separate `footprint` metric for that comparison.
|
|
125
131
|
Names remain executable names, so Pi commonly appears as `node`.
|
|
126
132
|
|
|
@@ -135,8 +141,10 @@ real-input gate and reports its snapshot duration/coverage.
|
|
|
135
141
|
Development: `npm run check --workspace @nredd/pi-resource-sampler` (single-worker tests, including
|
|
136
142
|
actual host samples and child cleanup). The full suite runs through Vitest on Node and pinned Bun.
|
|
137
143
|
Native failure tests inject fixed bindings through the same lazy loader seam used by production,
|
|
138
|
-
|
|
139
|
-
|
|
144
|
+
and `nativeCalls(host)` takes a fake `process` (platform, arch, `versions.bun`, `getBuiltinModule`)
|
|
145
|
+
with recording `bun:ffi`/`node:ffi` fakes, never a patched global. Both adapters and the per-PID
|
|
146
|
+
loop therefore run on every OS without the runtime's real FFI; macOS also runs the real libproc path.
|
|
147
|
+
`tests/runtime.test.ts` runs under both engines: it starts a child whose argv[0], argv, environment, process title and (Linux) comm hold a
|
|
140
148
|
random secret, proves the 0.1.0 source exposes it, then requires the child in the snapshot and no
|
|
141
149
|
12-character fragment of the secret, plus three real CPU samples. Everything after spawn, readiness
|
|
142
150
|
included, is followed by SIGTERM, then SIGKILL, with a bounded wait for the runtime's exit status
|
|
@@ -157,3 +165,15 @@ tarball, with no Pi or siblings. Both run on existing macOS/Linux CI jobs.
|
|
|
157
165
|
`dist` contains compiled ESM and declarations; the exact packed payload is contract-pinned. No install
|
|
158
166
|
scripts or runtime dependencies. Releases publish through `publish.yml` with npm provenance; see
|
|
159
167
|
[releases](../../docs/releases.md).
|
|
168
|
+
|
|
169
|
+
## Changelog fragments
|
|
170
|
+
|
|
171
|
+
Add `changes/<issue>.<category>.md` instead of editing the shared Unreleased block.
|
|
172
|
+
Use the [one-line fragment grammar](https://github.com/nredd/pi-harness/blob/main/packages/subagents/README.md#changelog-fragments), including
|
|
173
|
+
its matching issue link. From the repository root, `make check-changelog-fragments` validates
|
|
174
|
+
all enrolled packages; `make fold-changelog` explicitly folds them without releasing.
|
|
175
|
+
See the [release contract](https://github.com/nredd/pi-harness/blob/main/docs/releases.md#changelog-fragments).
|
|
176
|
+
|
|
177
|
+
The #932 migration preserves 1 historical bullet: 0 exact bullets move to fragments
|
|
178
|
+
and 1 remains in `CHANGELOG.md`. The legacy `#878` attribution is not the required matching Markdown issue link.
|
|
179
|
+
Historical attribution and released sections are unchanged; no issue IDs are invented.
|
package/dist/collect.d.ts
CHANGED
|
@@ -52,7 +52,11 @@ export declare function command(executable: string, args: string[], budget: Budg
|
|
|
52
52
|
complete: boolean;
|
|
53
53
|
}>;
|
|
54
54
|
/**
|
|
55
|
-
* Scan Linux sequentially
|
|
55
|
+
* Scan Linux sequentially over a names-only `/proc` listing.
|
|
56
|
+
*
|
|
57
|
+
* Names only, never `opendir` Dirents: `/proc` reports a PID that exits mid-listing as `DT_UNKNOWN`, and
|
|
58
|
+
* Node's `Dir` then `lstat`s it, and that ENOENT rejects the iterator with its batch, which cannot resume, so
|
|
59
|
+
* the whole scan was lost (`process-collection-unavailable`). A vanished PID must fail its own stat read instead.
|
|
56
60
|
* @param budget Shared scan limits and cancellation.
|
|
57
61
|
* @param hz Host CLK_TCK rate in ticks per second.
|
|
58
62
|
* @returns Validated identity-bracketed process counters; aborts propagate.
|
package/dist/collect.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { open,
|
|
2
|
+
import { open, readdir, readlink } from "node:fs/promises";
|
|
3
3
|
import { performance } from "node:perf_hooks";
|
|
4
4
|
import { darwinMemory, darwinProcess, darwinSwap, executableName, linuxRss, linuxStat, psi, } from "./counters.js";
|
|
5
5
|
import { darwinNativeProcesses } from "./darwin.js";
|
|
@@ -135,10 +135,8 @@ export async function command(executable, args, budget, maxLines = Number.POSITI
|
|
|
135
135
|
/** @returns Nothing; terminate the helper after shared cancellation. */
|
|
136
136
|
const abort = () => stop("cancelled");
|
|
137
137
|
const timer = setTimeout(() => stop("deadline"), budget.remaining());
|
|
138
|
+
// No abort can land unobserved: `ready()` threw on an aborted signal, and nothing since has yielded.
|
|
138
139
|
budget.signal.addEventListener("abort", abort, { once: true });
|
|
139
|
-
// Close the race between the ready check and listener registration.
|
|
140
|
-
if (budget.signal.aborted)
|
|
141
|
-
abort();
|
|
142
140
|
child.stdout.on("data", (data) => {
|
|
143
141
|
if (!complete)
|
|
144
142
|
return;
|
|
@@ -182,16 +180,19 @@ export async function command(executable, args, budget, maxLines = Number.POSITI
|
|
|
182
180
|
});
|
|
183
181
|
}
|
|
184
182
|
/**
|
|
185
|
-
* Scan Linux sequentially
|
|
183
|
+
* Scan Linux sequentially over a names-only `/proc` listing.
|
|
184
|
+
*
|
|
185
|
+
* Names only, never `opendir` Dirents: `/proc` reports a PID that exits mid-listing as `DT_UNKNOWN`, and
|
|
186
|
+
* Node's `Dir` then `lstat`s it, and that ENOENT rejects the iterator with its batch, which cannot resume, so
|
|
187
|
+
* the whole scan was lost (`process-collection-unavailable`). A vanished PID must fail its own stat read instead.
|
|
186
188
|
* @param budget Shared scan limits and cancellation.
|
|
187
189
|
* @param hz Host CLK_TCK rate in ticks per second.
|
|
188
190
|
* @returns Validated identity-bracketed process counters; aborts propagate.
|
|
189
191
|
*/
|
|
190
192
|
export async function linuxProcesses(budget, hz) {
|
|
191
193
|
const result = [];
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
if (!/^\d+$/.test(entry.name))
|
|
194
|
+
for (const pid of await readdir("/proc")) {
|
|
195
|
+
if (!/^\d+$/.test(pid))
|
|
195
196
|
continue;
|
|
196
197
|
if (!budget.ready())
|
|
197
198
|
break;
|
|
@@ -201,7 +202,7 @@ export async function linuxProcesses(budget, hz) {
|
|
|
201
202
|
}
|
|
202
203
|
budget.enumerated++;
|
|
203
204
|
try {
|
|
204
|
-
const path = `/proc/${
|
|
205
|
+
const path = `/proc/${pid}`;
|
|
205
206
|
const first = linuxStat(await budget.read(`${path}/stat`), hz, performance.now());
|
|
206
207
|
if (!first)
|
|
207
208
|
throw new Error("process incomplete");
|
|
@@ -209,7 +210,7 @@ export async function linuxProcesses(budget, hz) {
|
|
|
209
210
|
const rssBytes = linuxRss(await budget.read(`${path}/status`));
|
|
210
211
|
const last = linuxStat(await budget.read(`${path}/stat`), hz, performance.now());
|
|
211
212
|
// The name and RSS reads sit between two stat reads, so PID reuse rejects both.
|
|
212
|
-
if (!last || first.pid !== Number(
|
|
213
|
+
if (!last || first.pid !== Number(pid) || first.identity !== last.identity || rssBytes === null)
|
|
213
214
|
throw new Error("process changed or incomplete");
|
|
214
215
|
result.push({ ...last, name, rssBytes });
|
|
215
216
|
}
|
package/dist/counters.js
CHANGED
|
@@ -182,9 +182,11 @@ export function darwinMemory(text, total) {
|
|
|
182
182
|
* @returns Page count, or null for missing/duplicate/malformed rows.
|
|
183
183
|
*/
|
|
184
184
|
const read = (name) => {
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
|
|
185
|
+
const values = text
|
|
186
|
+
.split("\n")
|
|
187
|
+
.filter((line) => line.startsWith(`${name}:`))
|
|
188
|
+
.map((line) => /^.*:\s+(\d+)\.\s*$/.exec(line)?.[1]);
|
|
189
|
+
const [value] = values.length === VM_COUNTER_OCCURRENCES ? values : [];
|
|
188
190
|
const count = value === undefined ? Number.NaN : Number(value);
|
|
189
191
|
return Number.isSafeInteger(count) && count >= 0 ? count : null;
|
|
190
192
|
};
|
package/dist/darwin.d.ts
CHANGED
|
@@ -68,6 +68,21 @@ export interface NativeCalls {
|
|
|
68
68
|
timebase(buffer: Buffer): number;
|
|
69
69
|
close(): void;
|
|
70
70
|
}
|
|
71
|
+
/** The `process` fields that select an FFI adapter; tests inject a fake host to run both on any OS. */
|
|
72
|
+
export interface NativeHost {
|
|
73
|
+
readonly platform: string;
|
|
74
|
+
readonly arch: string;
|
|
75
|
+
/** Runtime versions; only a `bun` entry selects the Bun adapter. */
|
|
76
|
+
readonly versions: Readonly<Record<string, string | undefined>>;
|
|
77
|
+
getBuiltinModule(id: string): unknown;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Load only fixed native symbols, lazily; unsupported runtimes retain unavailable process metrics.
|
|
81
|
+
* @param host Platform, architecture, runtime and builtin loader; defaults to the running `process`.
|
|
82
|
+
* @returns Owned syscall bindings, or undefined for unsupported platform/architecture/runtime.
|
|
83
|
+
* @throws If opening the runtime FFI library fails.
|
|
84
|
+
*/
|
|
85
|
+
export declare function nativeCalls(host?: NativeHost): NativeCalls | undefined;
|
|
71
86
|
/**
|
|
72
87
|
* Identity-check metadata between two rusage reads. Start absolute ticks distinguish same-second PID
|
|
73
88
|
* reuse; microsecond start, parent and exact p_comm bytes also participate. No sanitized-name collision
|
package/dist/darwin.js
CHANGED
|
@@ -65,14 +65,15 @@ export const NANOSECONDS_PER_MILLISECOND = 1_000_000;
|
|
|
65
65
|
export const MICROSECONDS_PER_SECOND = 1000000n;
|
|
66
66
|
/**
|
|
67
67
|
* Load only fixed native symbols, lazily; unsupported runtimes retain unavailable process metrics.
|
|
68
|
+
* @param host Platform, architecture, runtime and builtin loader; defaults to the running `process`.
|
|
68
69
|
* @returns Owned syscall bindings, or undefined for unsupported platform/architecture/runtime.
|
|
69
70
|
* @throws If opening the runtime FFI library fails.
|
|
70
71
|
*/
|
|
71
|
-
function nativeCalls() {
|
|
72
|
-
if (
|
|
72
|
+
export function nativeCalls(host = process) {
|
|
73
|
+
if (host.platform !== "darwin" || !["arm64", "x64"].includes(host.arch))
|
|
73
74
|
return undefined;
|
|
74
|
-
if (
|
|
75
|
-
const ffi =
|
|
75
|
+
if (host.versions.bun) {
|
|
76
|
+
const ffi = host.getBuiltinModule("bun:ffi");
|
|
76
77
|
if (!ffi)
|
|
77
78
|
return undefined;
|
|
78
79
|
const lib = ffi.dlopen("/usr/lib/libproc.dylib", {
|
|
@@ -87,7 +88,7 @@ function nativeCalls() {
|
|
|
87
88
|
close: () => lib.close(),
|
|
88
89
|
};
|
|
89
90
|
}
|
|
90
|
-
const ffi =
|
|
91
|
+
const ffi = host.getBuiltinModule("node:ffi");
|
|
91
92
|
if (!ffi)
|
|
92
93
|
return undefined;
|
|
93
94
|
const lib = ffi.dlopen("/usr/lib/libproc.dylib", {
|
|
@@ -215,7 +216,7 @@ export function darwinNativeProcesses(rows, budget, load = nativeCalls) {
|
|
|
215
216
|
if (!lib)
|
|
216
217
|
return rows;
|
|
217
218
|
try {
|
|
218
|
-
for (
|
|
219
|
+
for (const [i, row] of rows.entries()) {
|
|
219
220
|
if (!budget.ready())
|
|
220
221
|
break;
|
|
221
222
|
if (budget.maxBytes - budget.bytesRead < DARWIN_NATIVE_READ_BYTES) {
|
|
@@ -224,9 +225,6 @@ export function darwinNativeProcesses(rows, budget, load = nativeCalls) {
|
|
|
224
225
|
break;
|
|
225
226
|
}
|
|
226
227
|
budget.bytesRead += DARWIN_NATIVE_READ_BYTES;
|
|
227
|
-
const row = rows[i];
|
|
228
|
-
if (!row)
|
|
229
|
-
continue;
|
|
230
228
|
const before = Buffer.alloc(DARWIN_ABI.usage.bytes);
|
|
231
229
|
const bsd = Buffer.alloc(DARWIN_ABI.bsd.bytes);
|
|
232
230
|
const after = Buffer.alloc(DARWIN_ABI.usage.bytes);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nredd/pi-resource-sampler",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Bounded, privacy-safe host resource interval sampling without Pi dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -30,18 +30,15 @@
|
|
|
30
30
|
},
|
|
31
31
|
"scripts": {
|
|
32
32
|
"build": "tsc -p tsconfig.build.json",
|
|
33
|
-
"
|
|
33
|
+
"prepack": "npm run build",
|
|
34
|
+
"lint": "biome check .",
|
|
35
|
+
"format": "biome check --write .",
|
|
34
36
|
"typecheck": "tsc --noEmit",
|
|
35
|
-
"test": "
|
|
36
|
-
"test:bun": "node ../../scripts/run-vitest.ts bun
|
|
37
|
+
"test": "node ../../scripts/run-vitest.ts node --coverage",
|
|
38
|
+
"test:bun": "node ../../scripts/run-vitest.ts bun",
|
|
37
39
|
"check": "npm run lint && npm run typecheck && npm run build && npm test && npm run test:bun"
|
|
38
40
|
},
|
|
39
41
|
"devDependencies": {
|
|
40
|
-
"@
|
|
41
|
-
"@types/node": "26.6.5",
|
|
42
|
-
"@vitest/coverage-istanbul": "5.0.3",
|
|
43
|
-
"@vitest/coverage-v8": "5.0.3",
|
|
44
|
-
"typescript": "7.0.2",
|
|
45
|
-
"vitest": "5.0.3"
|
|
42
|
+
"@nredd/pi-test-lib": "0.0.0"
|
|
46
43
|
}
|
|
47
44
|
}
|