Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .changeset/node-runtime-traces.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,5 @@ Node, Bun and Deno now report more runtime traces in `traces.system`:
- `v8_heap_size_limit`, `v8_heap_available`, `v8_heap_malloced`, `v8_heap_peak_malloced` and the ceiling-based `ram_js_heap_total` / `_used` / `_free` (`total` is the heap limit, not the committed heap). Node and Deno only; omitted on Bun, whose heap statistics are not a V8 ceiling.
- `process_memory_limit` (the cgroup cap), reported only for a real cap: omitted when `process.constrainedMemory()` is 0, the 2^64 sentinel, or at least total RAM.
- `process_uptime_s`.
- `ram_system_available`, on Node only: on Bun and Deno it ignores a container memory cap on Linux (measured), so it is omitted there.

`createNodeSystemTraceProducers` gains `measuresV8Heap` and `measuresAvailableMemory` (default `true`) for runtimes that cannot answer honestly.
`createNodeSystemTraceProducers` gains `measuresV8Heap` (default `true`) for runtimes that cannot answer honestly.
11 changes: 11 additions & 0 deletions .changeset/ram-system-free-semantics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@bugsee/node': minor
'@bugsee/bun': minor
'@bugsee/deno': minor
'@bugsee/electron': minor
'@bugsee/trackers': minor
---

`ram_system_free` now means memory available to new work, in bytes as on Android (`availMem`), instead of raw free pages. Sources: Electron `process.getSystemMemoryInfo()` (macOS free + fileBacked + purgeable, Linux `available`, Windows `free`), Deno `systemMemoryInfo().available` on macOS, `/proc/meminfo` `MemAvailable` on Bun, then `os.freemem()` (libuv `MemAvailable` on Linux, `ullAvailPhys` on Windows). Node and Bun on macOS omit the trace, because `os.freemem()` there is free pages only and no native available figure exists. The value is omitted when no source gives a finite, non-negative number not above total RAM. Inside a container it is the host's figure; the cap is `process_memory_limit`.

The `ram_system_available` trace is removed (it was Node-only and never released): `process.availableMemory()` equals `os.freemem()` without a cgroup limit and reads lower inside one, and it is not comparable on Bun and Deno. `@bugsee/trackers/node` drops the `availableMemory` stage and `createAvailableMemoryReader`, and gains `createProcMeminfoReader` and `parseMemAvailable`. The `measuresAvailableMemory` option is replaced by `readsProcMeminfo` (default `false`; only Bun sets it), and `createSystemFreeReader`, `createElectronMemoryReader`, `createDenoMemoryReader` and `firstAnswer` are exported.
4 changes: 2 additions & 2 deletions docs/PROGRESS.md

Large diffs are not rendered by default.

6 changes: 2 additions & 4 deletions packages/bun/src/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,12 @@ describe('@bugsee/bun launch', () => {
expect(names).not.toContain('cpu_usage_process'); // no CPU start value: it begins with the first sampled window
});

it('opts out of the V8 heap, available-memory and gc traces (Bun: JSC heap, not comparable availableMemory, blind GC observer)', () => {
it('opts out of the V8 heap and gc traces (Bun: JSC heap, blind GC observer) and reads /proc/meminfo MemAvailable for ram_system_free', () => {
track(launchCore('tok', base()).client);
expect(createNodeSystemTraceProducers).toHaveBeenCalledWith(
expect.objectContaining({
measuresV8Heap: false,
measuresAvailableMemory: false,
readsProcMeminfo: true,
measuresGc: false,
}),
);
Expand Down Expand Up @@ -436,14 +436,12 @@ describe('@bugsee/bun — the runtime gates reach the shared ProcessTracker', ()
track(launchCore('tok', base({ scheduler, captureSystemTraces: true })).client);
const tracker = processTrackerFor(); // the launch went through the registry accessor: same `process` singleton
expect(tracker.current('v8Heap')).toBeUndefined();
expect(tracker.current('availableMemory')).toBeUndefined();
const seen: string[] = [];
const off = tracker.onAny((name) => void seen.push(name));
for (const cb of calls) cb();
off();
expect(seen).toContain('memory');
expect(seen).not.toContain('v8Heap');
expect(seen).not.toContain('gc');
expect(seen).not.toContain('availableMemory');
});
});
8 changes: 5 additions & 3 deletions packages/bun/src/launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ export function launchCore(appToken: string, options: BugseeLaunchOptions = {}):
systemProbe: bunSystemProbe,
systemTraceProducers: createNodeSystemTraceProducers({
// JSC's heap statistics are not a V8 ceiling (`limit - used` is meaningless; ~1000x Node's cost per call),
// and on Linux `availableMemory` ignores the container cap (measured under `docker -m 256m`: 11.2 GB vs
// Node's 253 MB), so those traces are omitted here.
// so the V8 heap traces are omitted here.
measuresV8Heap: false,
measuresAvailableMemory: false,
// Bun < 1.3.13's `os.freemem()` is not MemAvailable on Linux, so `ram_system_free` reads /proc/meminfo
// MemAvailable first there, then os.freemem() (omitted on macOS: Bun has no native available figure).
// `process.availableMemory()` is never used.
readsProcMeminfo: true,
// `PerformanceObserver('gc')` is BLIND on Bun (0 entries after heavy churn — measured): a quiet-looking
// zero would be a lie, so no observer is constructed and the gc traces are omitted.
measuresGc: false,
Expand Down
6 changes: 2 additions & 4 deletions packages/deno/src/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,10 +312,10 @@ describe('@bugsee/deno — the event-loop metrics Deno cannot measure', () => {
);
});

it('opts out of ram_system_available (a different quantity) and gc (blind observer) and keeps the V8 heap (real V8)', () => {
it('never reads /proc/meminfo for ram_system_free (a scoped --allow-read would prompt), opts out of gc (blind observer) and keeps the V8 heap (real V8)', () => {
track(launchCore('tok', base()).client);
const arg = vi.mocked(createNodeSystemTraceProducers).mock.calls[0]?.[0];
expect(arg?.measuresAvailableMemory).toBe(false);
expect(arg).not.toHaveProperty('readsProcMeminfo'); // only Bun reads /proc/meminfo
expect(arg?.measuresGc).toBe(false);
expect(arg).not.toHaveProperty('measuresV8Heap'); // the node default (true) applies
});
Expand Down Expand Up @@ -432,7 +432,6 @@ describe('@bugsee/deno — the runtime gates reach the shared ProcessTracker', (
};
track(launchCore('tok', base({ scheduler, captureSystemTraces: true })).client);
const tracker = processTrackerFor(); // the launch went through the registry accessor: same `process` singleton
expect(tracker.current('availableMemory')).toBeUndefined();
expect(tracker.current('v8Heap')?.limit).toBeGreaterThan(0);
const seen: string[] = [];
const off = tracker.onAny((name) => void seen.push(name));
Expand All @@ -441,6 +440,5 @@ describe('@bugsee/deno — the runtime gates reach the shared ProcessTracker', (
expect(seen).toContain('memory');
expect(seen).not.toContain('eventLoop');
expect(seen).not.toContain('gc');
expect(seen).not.toContain('availableMemory');
});
});
6 changes: 3 additions & 3 deletions packages/deno/src/launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ export function launchCore(appToken: string, options: BugseeLaunchOptions = {}):
// its own tell (a zero `idle`), so it needs no flag.
systemTraceProducers: createNodeSystemTraceProducers({
measuresEventLoopDelay: false,
// Deno's `process.availableMemory()` is not the Node quantity: 23 GB vs 3.4 GB on one macOS host, and on
// Linux it ignores the container cap (11.2 GB under `docker -m 256m` vs Node's 253 MB).
measuresAvailableMemory: false,
// `ram_system_free` on Deno: `os.freemem()` (MemAvailable on Linux since 2023, avail_phys on Windows) and
// `Deno.systemMemoryInfo().available` on macOS. It must NOT read /proc/meminfo (no `readsProcMeminfo`): the
// read triggers an interactive permission prompt under a scoped `--allow-read`.
// `PerformanceObserver('gc')` is BLIND on Deno too (0 entries, also with --v8-flags=--expose-gc): omit.
measuresGc: false,
// the shared tracker's sampling timer honors an injected scheduler, and its poll errors are reported
Expand Down
81 changes: 45 additions & 36 deletions packages/node/src/trace-producers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ const constDeps = (over: NodeTraceProducerDeps = {}): NodeTraceProducerDeps => (
uptime: () => 42.7,
v8Heap: () => ({ limit: 1000, used: 300, available: 700, malloced: 11, peakMalloced: 12 }),
memoryLimit: () => 500,
availableMemory: () => 250,
...over,
});

Expand Down Expand Up @@ -134,7 +133,6 @@ describe('createNodeSystemTraceProducers', () => {
['ram_js_heap_free', 700],
['ram_js_heap_total', 1000],
['ram_js_heap_used', 300],
['ram_system_available', 250],
['ram_system_free', 400],
['ram_system_total', 1000],
['v8_heap_available', 700],
Expand Down Expand Up @@ -195,10 +193,9 @@ describe('createNodeSystemTraceProducers', () => {
expect(h.got.has('process_memory_rss')).toBe(true);
});

it('omits process_memory_limit / ram_system_available when their readers answer undefined', () => {
const h = run({ memoryLimit: () => undefined, availableMemory: () => undefined });
it('omits process_memory_limit when its reader answers undefined', () => {
const h = run({ memoryLimit: () => undefined });
expect(h.got.has('process_memory_limit')).toBe(false);
expect(h.got.has('ram_system_available')).toBe(false);
expect(h.got.get('process_uptime_s')).toBe(42);
});

Expand All @@ -209,36 +206,45 @@ describe('createNodeSystemTraceProducers', () => {
for (const k of h.got.keys()) expect(k).not.toMatch(/^(v8_heap_|ram_js_heap_)/);
});

it('measuresAvailableMemory:false omits ram_system_available even where the runtime answers (Bun/Deno)', () => {
const { availableMemory: _off, ...base } = constDeps({ eventLoop });
const h = harness({ ...base, measuresAvailableMemory: false });
h.startAll();
expect(h.got.has('ram_system_available')).toBe(false);
});

it('an injected reader wins over the measures* flag (as for the event-loop source)', () => {
const h = harness({
...constDeps({ eventLoop }),
measuresV8Heap: false,
measuresAvailableMemory: false,
});
h.startAll();
expect(h.got.get('v8_heap_size_limit')).toBe(1000);
expect(h.got.get('ram_system_available')).toBe(250);
it('ram_system_free: os.freemem() (not on macOS), MemAvailable first for readsProcMeminfo, native first of all; total stays total', () => {
const { systemMemory: _s, ...base } = constDeps({ eventLoop });
const run1 = (over: NodeTraceProducerDeps) => {
const h = harness({ ...base, memoryLimit: () => undefined, ...over });
h.startAll();
return h.got;
};
const meminfo = () => 'MemAvailable: 3 kB\n';
expect(run1({ platform: 'linux', meminfo, freeMemory: () => 9 }).get('ram_system_free')).toBe(
9,
);
expect(run1({ platform: 'darwin', freeMemory: () => 9 }).has('ram_system_free')).toBe(false);
expect(
run1({ platform: 'darwin', nativeAvailableMemory: () => 5 }).get('ram_system_free'),
).toBe(5);
expect(
run1({ platform: 'linux', readsProcMeminfo: true, meminfo, freeMemory: () => 9 }).get(
'ram_system_free',
),
).toBe(3072);
expect(
run1({
platform: 'linux',
readsProcMeminfo: true,
meminfo: () => undefined,
freeMemory: () => 9,
}).get('ram_system_free'),
).toBe(9);
const none = run1({ platform: 'linux', freeMemory: () => Number.NaN });
expect(none.has('ram_system_free')).toBe(false);
expect(Number(none.get('ram_system_total'))).toBeGreaterThan(0);
});

it('an explicit undefined reader does not clobber the wired default (measures* true)', () => {
const {
v8Heap: _a,
memoryLimit: _b,
availableMemory: _c,
...base
} = constDeps({ eventLoop });
const { v8Heap: _a, memoryLimit: _b, ...base } = constDeps({ eventLoop });
const h = harness({
...base,
v8Heap: undefined,
memoryLimit: undefined,
availableMemory: undefined,
});
h.startAll();
expect(Number(h.got.get('v8_heap_size_limit'))).toBeGreaterThan(0); // the real node default, not absent
Expand Down Expand Up @@ -462,7 +468,7 @@ describe('createNodeSystemTraceProducers', () => {
it('gate: creating the producers constructs no histogram and starts no timer until start', () => {
const { perfHooks, state } = fakePerfHooks();
const h = harness({ ...constDeps(), perfHooks });
expect(h.producers).toHaveLength(10);
expect(h.producers).toHaveLength(9);
expect(state.monitor).toBe(0);
expect(h.spy.set).toBe(0);
h.producers[0]?.start({ emit: () => {} }); // memory: arms the shared timer only
Expand Down Expand Up @@ -576,9 +582,9 @@ describe('createNodeSystemTraceProducers', () => {
await new Promise((r) => setTimeout(r, 120));
tick?.();
for (const p of ps) p.stop();
// `process_memory_limit` exists only inside a real cgroup cap and `ram_system_available` only on
// Node >= 20.13, so each is checked for what the host can answer rather than demanded.
const optional = ['process_memory_limit', 'ram_system_available'];
// `process_memory_limit` exists only inside a real cgroup cap, so it is checked for what the host can answer.
// `ram_system_free` is omitted on macOS (os.freemem() there is not memory available to new work).
const optional = ['process_memory_limit', 'ram_system_free'];
expect([...got.keys()].filter((k) => !optional.includes(k)).sort()).toEqual([
'cpu_usage_process',
'cpu_usage_system',
Expand All @@ -599,16 +605,19 @@ describe('createNodeSystemTraceProducers', () => {
'ram_js_heap_free',
'ram_js_heap_total',
'ram_js_heap_used',
'ram_system_free',
'ram_system_total',
'v8_heap_available',
'v8_heap_malloced',
'v8_heap_peak_malloced',
'v8_heap_size_limit',
]);
expect(got.has('ram_system_available')).toBe(
typeof (process as { availableMemory?: unknown }).availableMemory === 'function',
);
expect(got.has('ram_system_available')).toBe(false); // retired
if (process.platform === 'darwin') expect(got.has('ram_system_free')).toBe(false);
else {
expect(Number(got.get('ram_system_free'))).toBeLessThanOrEqual(
Number(got.get('ram_system_total')),
);
}
expect(Number(got.get('v8_heap_size_limit'))).toBeGreaterThan(0);
for (const v of got.values()) expect(Number.isFinite(v)).toBe(true);
});
Expand Down
20 changes: 5 additions & 15 deletions packages/node/src/trace-producers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
processTrackerFor,
} from '@bugsee/trackers/node';

// Node `traces.system` producers (mirrors the mobile tracker/producer split): ten producers, each subscribed to ONE
// Node `traces.system` producers (mirrors the mobile tracker/producer split): nine producers, each subscribed to ONE
// stage of the shared per-process ProcessTracker (`@bugsee/trackers/node`, the abstraction layer over the runtime's
// process APIs). This file is COMPOSITION only: which stage feeds which trace names, plus the runtime-identity gates
// the platform packages pass through (`measures*`). The tracker owns every runtime read, its lifetime and its
Expand Down Expand Up @@ -59,7 +59,8 @@ class SystemMemoryProducer extends StageProducer<'systemMemory'> {
}
protected publish(m: ProcessEvents['systemMemory']): void {
this.emit('ram_system_total', m.total);
this.emit('ram_system_free', m.free);
// memory available to new work (Android parity), absent when no source answers
if (m.free !== undefined) this.emit('ram_system_free', m.free);
}
}

Expand Down Expand Up @@ -134,16 +135,6 @@ class MemoryLimitProducer extends StageProducer<'memoryLimit'> {
}
}

class AvailableMemoryProducer extends StageProducer<'availableMemory'> {
readonly name = 'system-memory-available';
constructor(tracker: ProcessTracker) {
super(tracker, 'availableMemory');
}
protected publish(m: ProcessEvents['availableMemory']): void {
this.emit('ram_system_available', m.bytes);
}
}

// Emitted every tick, never held: a quiet interval is a TRUE zero (the observer is running), and a source that
// stops answering must be omitted rather than re-recorded from a held value. No baseline: the interval opens at
// activation, so nothing has been observed yet (a zero would be invented).
Expand Down Expand Up @@ -171,9 +162,9 @@ class UptimeProducer extends StageProducer<'uptime'> {
}

/**
* The tracker seams plus the platform GATES (`measuresEventLoopDelay`, `measuresV8Heap`, `measuresAvailableMemory`,
* The tracker seams plus the platform GATES (`measuresEventLoopDelay`, `measuresV8Heap`,
* `measuresGc`; see {@link ProcessTrackerEnv}) — runtime-identity facts the platform packages pass in: Deno gates the
* event-loop histogram, Bun the V8 heap, both the available-memory and GC readers.
* event-loop histogram, Bun the V8 heap, both the GC reader (Bun also sets `readsProcMeminfo`).
*/
export interface NodeTraceProducerDeps extends ProcessTrackerEnv {
onError?: (error: unknown) => void;
Expand All @@ -191,7 +182,6 @@ export function createNodeSystemTraceProducers(deps: NodeTraceProducerDeps = {})
new EventLoopUtilizationProducer(tracker),
new V8HeapProducer(tracker),
new MemoryLimitProducer(tracker),
new AvailableMemoryProducer(tracker),
new GcProducer(tracker),
new UptimeProducer(tracker),
];
Expand Down
Loading