From 6aff1533789893fbece1f07a60f9e20c75ab0077 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 00:25:56 +0500 Subject: [PATCH 1/3] feat(trackers,node): ProcessTracker for node/bun/deno (TR8, part 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Absorbs @bugsee/node's per-signal ProcessStatsTracker, GC observer, guarded event-loop sources and runtime readers into a per-process singleton ProcessTracker in @bugsee/trackers/node (ten per-stage-activated stages, registry accessor with merge-not-drop rebind). Producers in @bugsee/node are now composition only; Bun/Deno gates are passed through unchanged. πŸ€– Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/node-process-tracker.md | 8 + docs/PROGRESS.md | 3 +- packages/bun/src/launch.test.ts | 34 +- packages/deno/src/launch.test.ts | 34 +- packages/node/package.json | 3 +- packages/node/src/index.test.ts | 3 +- packages/node/src/index.ts | 13 +- packages/node/src/launch.test.ts | 45 + packages/node/src/trace-producers.test.ts | 16 +- packages/node/src/trace-producers.ts | 262 ++--- .../trackers/process-stats-tracker.test.ts | 734 -------------- .../src/trackers/process-stats-tracker.ts | 260 ----- packages/trackers/README.md | 4 +- packages/trackers/package.json | 7 +- packages/trackers/src/index.test.ts | 6 +- .../src/node}/gc-observer.test.ts | 0 .../src/node}/gc-observer.ts | 0 .../src/node}/guarded-event-loop.test.ts | 0 .../src/node}/guarded-event-loop.ts | 8 +- packages/trackers/src/node/index.test.ts | 21 + packages/trackers/src/node/index.ts | 41 +- .../trackers/src/node/process-tracker.test.ts | 939 ++++++++++++++++++ packages/trackers/src/node/process-tracker.ts | 541 ++++++++++ .../src/node}/runtime-readers.test.ts | 0 .../src/node}/runtime-readers.ts | 2 +- packages/trackers/tsconfig.json | 3 +- packages/trackers/tsconfig.portable.json | 11 + pnpm-lock.yaml | 9 +- 28 files changed, 1829 insertions(+), 1178 deletions(-) create mode 100644 .changeset/node-process-tracker.md delete mode 100644 packages/node/src/trackers/process-stats-tracker.test.ts delete mode 100644 packages/node/src/trackers/process-stats-tracker.ts rename packages/{node/src/trackers => trackers/src/node}/gc-observer.test.ts (100%) rename packages/{node/src/trackers => trackers/src/node}/gc-observer.ts (100%) rename packages/{node/src/trackers => trackers/src/node}/guarded-event-loop.test.ts (100%) rename packages/{node/src/trackers => trackers/src/node}/guarded-event-loop.ts (95%) create mode 100644 packages/trackers/src/node/index.test.ts create mode 100644 packages/trackers/src/node/process-tracker.test.ts create mode 100644 packages/trackers/src/node/process-tracker.ts rename packages/{node/src/trackers => trackers/src/node}/runtime-readers.test.ts (100%) rename packages/{node/src/trackers => trackers/src/node}/runtime-readers.ts (99%) create mode 100644 packages/trackers/tsconfig.portable.json diff --git a/.changeset/node-process-tracker.md b/.changeset/node-process-tracker.md new file mode 100644 index 00000000..90ba22e2 --- /dev/null +++ b/.changeset/node-process-tracker.md @@ -0,0 +1,8 @@ +--- +'@bugsee/node': minor +'@bugsee/bun': patch +'@bugsee/deno': patch +'@bugsee/trackers': minor +--- + +Node, Bun and Deno system traces now come from a per-process `ProcessTracker` in the new `@bugsee/trackers/node` entry, which replaces `@bugsee/node`'s `ProcessStatsTracker`. Trace names and values are unchanged; the GC observer and event-loop histogram now run only while their traces are enabled, and the runtime gates for Bun and Deno still omit the traces those runtimes cannot measure honestly. `@bugsee/node` no longer exports `ProcessStatsTracker` and `ProcessStats`; it now exports `processTrackerFor`, `resetProcessTracker` and the `ProcessTracker` type instead. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index e5ad93d8..bbeac916 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -413,10 +413,11 @@ solid), in slices: - **TR6 (DONE, `feat/storage-tracker`):** domain **`StorageTracker`** (`packages/trackers/src/browser/storage-tracker.ts`), singleton per window via `createTrackerRegistry` (`storageTrackerFor(env, onError?)`, `resetStorageTracker`; keyed window -> navigator -> env object, `rebind` as PowerTracker). Wraps `navigator.storage.estimate()` + `persisted()`; ONE stage `storageEstimate` `{usageBytes?, quotaBytes?, persisted?}`. This is an ORIGIN quota ESTIMATE (browsers fuzz/pad it), NOT device free space. No change event, so it polls sparsely: on activation, on `visibilitychange` -> visible, then a slow timer (default 5 min via an injectable scheduler; ticks while the page is hidden are skipped). A field that is non-finite/negative/non-number is omitted (never 0); `persisted` only when boolean; an estimate with no usable field emits nothing. A rejected/throwing `estimate()`/`persisted()` is reported via `onError` and costs only its own field (host getters through `hostRead`); launch is never failed. **Retention rule (tested):** the LAST estimate survives the last unsubscribe (`current()` answers at once; a failed poll never erases it); timer and visibility listener do not (released, re-armed on the next subscriber, which also polls afresh). A single epoch counter is bumped by every poll/stop/reset, so a stale in-flight promise (after stop/reset, or superseded by a newer poll) is inert. `rebind` keeps every defined seam (undefined never clobbers) and applies it from the NEXT activation; a tracker that is attached keeps the navigator/document/scheduler it armed (only `onError` changes at once). Visibility-triggered polls are throttled to one per 60 s (`VISIBILITY_MIN_GAP_MS`, injectable `now`); the slow timer is not. Poll failures are reported ONCE per failure streak (reset by a poll without failures, and by `reset()`), not on every tick. A PARTIAL poll (one of `estimate()`/`persisted()` failed) merges: the failed call's retained fields are kept, answered fields replace, and the estimate's age advances only when usage/quota were refreshed. `currentFresh()` returns the retained estimate only while younger than 2x the poll interval (`current()` still returns it regardless). `StorageProducer` (browser `trace-producers.ts`, built after the `sensors:false` gate like the other sensor producers, so a `systemMetricsSampler` replaces it) emits the NEW JS-specific trace `storage_estimate` `{usage, quota}` in integer MB (`bytesToMegabytes`, floored; a missing key is omitted, `persisted` is not a trace) - NOT the Android `disk_mem_*` group. It is held/de-duplicated (`emitIfChanged`) because the poll period (5 min) far exceeds the default 60 s recording window; a non-held value would almost never appear in a report. `StorageProducer.onStart` seeds only from `currentFresh()` (never a snapshot older than 2x the interval). **OWNER DECISION PENDING:** a held polled value cannot be retracted, so after failed polls the last known estimate keeps being re-recorded every `refreshMs`. Alternatives: plain `emit` (the value would rarely land in a 60 s window) or a provider retract/release mechanism (same open question as the TR4 time traces). Usage under 1 MiB floors to 0 MB (an honest floor, not a measurement of zero). Shared by the WebView launch via the browser producers. Launch-level test proves launch goes through `storageTrackerFor` (the window's singleton holds the estimate). - **TR7 (DONE, `feat/environment-tracker`):** domain **`EnvironmentTracker`** (`packages/trackers/src/browser/environment-tracker.ts`), singleton per window via `createTrackerRegistry` (`environmentTrackerFor(env, onError?)`, `resetEnvironmentTracker`; keyed window -> navigator -> env object; `rebind` merges seams, never drops a defined one; a RUNNING tracker whose window/navigator/document/scheduler/interval changed detaches with the OLD seams, swaps in place, then re-attaches; `detectPrivateMode` turned on while running probes at once, turned off drops the result and any in-flight probe). Five stages: `language` `{language?, languages?, previous}` (`navigator.language(s)` + `languagechange`), `timezone` `{timeZone?, utcOffsetMinutes?, previous}` (no browser event, so re-read on a slow injectable timer, default 60 s with hidden-page ticks skipped, and on visibility -> visible; a DST shift is an offset change), `hints` `{cookiesEnabled?, secureContext?, crossOriginIsolated?, serviceWorkerControlled?, automation?, doNotTrack?, globalPrivacyControl?}`, `permissions` `{camera?, microphone?, geolocation?, notifications?, 'idle-detection'?: 'granted'|'denied'|'prompt'}` and `privateMode` `{private: 'yes'|'no'|'unknown', method?}`. `language`/`timezone` are CHANGE-ONLY (the first reading is a silent baseline held in `current()`, because they back `*_changed` events); `hints`/`permissions` are SNAPSHOT stages (first reading + every change); `privateMode` emits when its answer first arrives and when it changes. **Never prompts:** only `navigator.permissions.query()` is called (never requestPermission/getUserMedia/...), only the state STRING is kept, a PermissionStatus `change` refreshes it; a name the browser rejects with TypeError is omitted silently (Firefox does not know `camera`), other rejections are reported once per failure streak. **Private mode** is a HEURISTIC, never a certainty: one method `storage-quota` (`estimate().quota` under 120 MiB -> `yes`, at/over 1 GiB -> `no`, between or unreadable -> `unknown`; Chromium gives incognito a small fixed quota, Safari fuzzes). Omit-never-fabricate everywhere (empty/non-string language, NaN offset, non-boolean hints, unusable permission states are omitted; unknown DNT values omitted). Every host read goes through `hostRead` (a hostile getter costs only its field and is reported), a throwing `onError` never escapes. **Retention rule (tested):** the last language/time zone/hints/permissions/private-mode readings survive the last unsubscribe (and the change-only stages compare a restart against them); DOM listeners (languagechange, visibilitychange, PermissionStatus change), the timer and async work in flight do not (epoch tokens make a stale query/probe inert). **Events (`events.system`, `createBrowserSystemEventsSource`; the WebView launch shares the same source):** `language_changed` `{language?, languages?, previousLanguage?}`, `timezone_changed` `{timezone?, utcOffsetMinutes?, previousTimezone?, previousUtcOffsetMinutes?}`, `private_mode_detected` `{method?}` (ONLY for a `yes`; `no`/`unknown` never produce an event). Event names are free-form in `SystemEvent` (no registry/schema list exists to extend). **Launch option `captureEnvironmentHints`** (canonical `com.bugsee.option.capture.environment-hints`, browser launch only, default TRUE (opt-out), fail-closed boolean: anything but a boolean is OFF and reported) -> tracker `detectPrivateMode`; the WebView launch never enables it. **OWNER DECISION (2026-10-20, binding): private/incognito detection is OPT-OUT, ON by default** (the launch option keeps its name `captureEnvironmentHints`, default TRUE, `false` opts out, an invalid value is OFF and reported); still a tri-state heuristic (`yes`/`no`/`unknown`, method `storage-quota`), never a certainty. The decision covers private mode only, not other sensitive signals. The WebView launch still passes `detectPrivateMode: false` (no launch option there; a WebView's storage quota is not a private-window signal). **Not done / scope notes:** no `displayMode` stage (the UiTracker owns display-mode; `display_mode_changed` will be derived from it later); `hints` and `permissions` are tracker-level only, they have no wire consumer (the environment envelope schema is closed and has no field for them, so language/timezone were NOT added to `environment` either: `platform.locale`/`utc_offset` are still read once at launch by `buildBrowserEnvironment`, and the new events carry the later changes); **hints and permissions are NOT read by default (PR #84 review):** tracker env flags `observeHints` / `queryPermissions` (default false; a change while running re-attaches, turning one off drops its reading and, for permissions, the status listeners and in-flight queries); the browser system-events source passes both `false` explicitly (never inherited from the window's shared tracker), so a launch issues no `permissions.query()` and reads no hints until a real consumer sets them. Launch tests prove launch goes through `environmentTrackerFor` (the window's singleton holds the readings; mutating the source to `new EnvironmentTracker` fails them) and that private mode is ON by default and off with `captureEnvironmentHints: false`; the WebView launch has the same singleton test. **Review round 2:** persistent host-read failures of language/timezone/hints/visibility are reported once per failure streak (a clean run or `reset()` ends it); emitted stage payloads are copies, so a subscriber cannot mutate retained readings; the WebView launch now passes `document` + `scheduler` to the environment source; `resetEnvironmentTracker` is NOT re-exported from `@bugsee/browser` (reach teardown via `environmentTrackerFor(env).reset()`). **Round 3:** a host read that THROWS keeps that field's retained value (language, languages, time zone id, offset, each hint), so a transient failure never yields a fake `language_changed`/`timezone_changed`; `reset()` now drops all subscribers (`removeAllListeners`, as ApplicationTracker does) so the tracker re-activates for the next subscriber; a throwing `PermissionStatus.state` getter is reported once per streak. **Round 4:** per-permission-name streaks; a throwing state read, or a name whose re-query is rejected with a non-TypeError, keeps that name's retained state (a TypeError still omits it). **Round 5:** the browser system-events source subscribes to the tracker with ONE `onAny` (the activation read can emit a change made while the SDK was stopped, so per-stage subscriptions lost the later stages: a zone change alongside a language change vanished); the WebView launch passes `detectPrivateMode: false` explicitly (never inherits ON from an earlier launch on the window); stage payloads copy `previous` as well (a kept field shares its array). **PR review:** `privateMode` is no longer re-emitted on every activation: it emits when the answer first arrives and when it changes, a retained yes/no is not re-probed on a restart or a seam-moving rebind (an `unknown` is retried), and turning detection off then on re-detects; the browser events source always passes `detectPrivateMode` explicitly (omitted = false, never inherited); an answered-but-unusable permission state clears the stale entry (a failed/throwing read still retains it); private-probe getter failures (storage/estimate/quota) are reported once per streak; it stays a heuristic (constrained storage can false-positive). **Per-session delivery:** the tracker outlives sessions and never re-probes a retained yes/no, so the browser events source reads `current().privateMode` right after subscribing and re-emits `private_mode_detected` once for a retained `yes` (never for `no`/`unknown`, and never when this source opted out; the sink-side `detectPrivateMode` guard also covers the retained read). - **TR5 (implemented on `feat/process-tracker`, PR #83; multi-agent review rounds still in progress, one owner decision open β€” see "Known limit" below):** domain **`ProcessTracker`** (`packages/trackers/src/browser/process-tracker.ts`), singleton per window via `createTrackerRegistry` (`processTrackerFor(env, onError?)`, `resetProcessTracker`; keyed window -> performance -> env object, `rebind` merge-not-drop: a seam change on a RUNNING tracker first detaches every armed stage with the seams it was armed with, then swaps and restarts). It ABSORBS and replaces the per-signal `MemoryTracker` and `MainThreadLagTracker` (files + tests deleted; `MemoryProducer`/`MainThreadLagProducer` now subscribe to it; trace names and wire shapes unchanged). Five stages, each armed ONLY while it has listeners (via the `listenerCount(name)` / `onListenersChanged()` hooks `MultiKeyEmitterBase` already has on `main` from TR2; this PR does not touch the emitter; `start()`/`stop()` do nothing here): `heap` `{used, limit}` (`performance.memory`, polled; a figure that is not a finite non-negative number omits the reading), `mainThreadLag` `{lagMs}` (TIMER DRIFT, algorithm and visible-only gating unchanged: block >= 1 s always shows, shorter that crosses no due tick reads 0, reported once, fresh baseline each visible start), `idle` `{idleMs}` (NEW, ONE `requestIdleCallback` probe per sampling tick, never a loop and at most one in flight, visible pages only, `timeRemaining()` clamped to <= 50 ms; a tick whose callback never runs yields NO sample, never 0; omitted without rIC, e.g. Safari), `userIdle` `{userState: 'active'|'idle', screenState?: 'locked'|'unlocked'}` (NEW, Idle Detection API), `uptime` `{uptimeMs}` (`performance.now()`, omitted without a clock; no trace consumes it yet). **Idle Detection permission rule (binding): the SDK NEVER prompts.** `IdleDetector.requestPermission()` is never called; the detector starts ONLY when `navigator.permissions.query({name:'idle-detection'})` ALREADY reports `granted` (an engine that does not know the name rejects = stage inert, silent). The permission is re-queried on every activation and watched through its `change` event (granted later -> starts; revoked -> aborts and drops the tracker's retained state). Threshold floored at the spec's 60 s; stop aborts via `AbortController`; every async continuation is guarded by its run. **Retention rule (tested):** the last `userIdle` state survives the last unsubscribe (`currentUserIdle()`; `currentUserIdleFresh()`, which `UserIdleProducer` seeds from, answers only once the ARMED stage's detector has PUBLISHED in this run (permission re-confirmed and its `start()` settled; no age bound, a live detector reports changes only) and is undefined while the async permission re-query or `start()` is pending, or after a refusal/revoke; with NO armed stage it serves the state only while younger than 2 detector thresholds, via a new injectable `now` seam defaulting to `Date.now`, mirroring TR6's `currentFresh()`. A revoke while no stage is armed is therefore only noticed by the next activation's re-query (the plain `currentUserIdle()` read keeps the snapshot until then), but it can never seed a held trace); heap is read live; idle/lag/uptime keep nothing (a stale baseline would be a lie); timers, lifecycle subscription, pending probe and detector are released. New JS-specific traces (`BrowserTraceEnv` gains `requestIdleCallback`/`cancelIdleCallback`/`IdleDetector`/`AbortController`, bound/taken from the injected window by `browserTraceEnvFrom`): `main_thread_idle_ms` (ms, polled/not held; built under the same lifecycle gate as lag/fps) and `user_idle_state` (a STRING like `app_state`: `active` | `idle` | `locked`, where a locked screen wins over `userState`; held, de-duplicated; no trace at all unless the permission was already granted). **`user_idle_state` is OPT-IN (review P2; the maintainer's decision, PENDING OWNER CONFIRMATION): the host page's `idle-detection` grant shows only that the page was given the permission, not consent to record and upload idle/locked state. So `createBrowserSystemTraceProducers` builds `UserIdleProducer` only for `BrowserTraceEnv.captureUserIdle === true`, fed by the new browser + WebView launch option `captureUserIdle` (default false, strict boolean: any other value stays off and is reported; local key `com.bugsee.option.browser.capture-user-idle`, exported as `CAPTURE_USER_IDLE_OPTION_KEY`). Even when on, the tracker starts a detector only if the permission ALREADY reports `granted` (the SDK still never prompts). Without the opt-in the permission is not even queried. This applies ONLY to `user_idle_state`; private-mode detection is opt-out by a separate owner decision.** The viewer has no definition for either name yet (generic value block, design Β§13.3). **Known limit (OWNER DECISION PENDING β€” no retract mechanism invented):** `user_idle_state` is a HELD trace and the tracker emits nothing when the permission is revoked, so a producer that already published a value keeps having it re-recorded every `refreshMs` until the producer stops (the revoke only drops the tracker's retained copy and so stops NEW seeds; the seed is gated as above). Resolving it needs a decision on a retract/clear signal for held traces (same family as TR6's held `storage_estimate`). Other hardening from review: a hostile `performance.now` getter is reported exactly once in total (the factory reads silently, the tracker reports; only a SUCCESSFUL clock read is memoised per env, a failed one is retried on the next activation); `ProcessTracker.reset()` now drops every listener (like `ApplicationTracker`), so a later listener change cannot re-arm a stage for a gone subscriber; `browserTraceEnvFrom` now hands back stable bound closures per (window, function), so a no-op relaunch no longer restarts armed stages; a non-finite lag baseline omits that tick's `main_thread_lag_ms` instead of sending NaN; the gated teardown always closes the run. Launch-level test proves browser launch goes through `processTrackerFor` (the window's singleton can read the heap through launch's seams); the WebView launch shares the producers. `sensors:false` (a `systemMetricsSampler`) still builds only the battery producer. +- **TR8 part 1 (implemented on `feat/node-process-tracker`; Process only, Storage/disk is a later slice):** the node/bun/deno **`ProcessTracker`** (`packages/trackers/src/node/process-tracker.ts`, `@bugsee/trackers/node`) ABSORBS and REPLACES `@bugsee/node`'s per-signal `ProcessStatsTracker` (files + tests deleted from `packages/node/src/trackers/`); `gc-observer`, `guarded-event-loop` and `runtime-readers` moved (with their tests) to `packages/trackers/src/node/` unchanged apart from `EventLoopSource` now living beside the histogram source. Singleton per process via the registry (`processTrackerFor(env, onError?)`, key `env.key` else the `process` object; `resetProcessTracker(key?)`); `rebind` merges (defined seams replace, undefined never clobber; an UNCHANGED relaunch restarts nothing; a changed seam tears every armed stage down with the OLD seams, the timer is cleared on the scheduler that armed it, then re-arms on the new ones; latest `onError` wins). Ten **per-stage-activated** stages (one shared unref'd timer exists only while some stage has a listener; each stage's machinery only while it is wanted): `memory`, `systemMemory`, `cpu` `{userDelta, systemDelta, processPct}`, `eventLoop` `{meanMs, maxMs, p99Ms}`, `utilization` `{utilization}`, `gc` `{count, pauseMs, maxPauseMs}`, `v8Heap`, `memoryLimit` `{bytes}`, `availableMemory` `{bytes}`, `uptime` `{seconds}`. Trace names and wire values are unchanged. Honesty rules are unchanged and still tracker-owned: a stage that cannot answer EMITS NOTHING (ELU zeros on Bun/Deno, an unsampled histogram, a blind/refusing GC observer, untrue heap/limit/available readings), and the runtime-identity GATES (`measuresEventLoopDelay`/`measuresV8Heap`/`measuresAvailableMemory`/`measuresGc`) are now tracker env flags that the platform composition roots (`@bugsee/{deno,bun}` via `createNodeSystemTraceProducers`) pass through; an injected source/reader wins over its gate. **Retention rule (stated and tested):** only the resolved seams and the "this runtime refused" memory inside the guarded sources survive the last unsubscribe; the CPU baseline, ELU baseline, histogram, GC interval and the last windowed sample all start FRESH on the next subscription. `current(stage)` reads stateless stages LIVE (guarded, copies) and answers the last emitted sample of a windowed stage (`cpu` is seeded with a zero-length window when it arms, so a producer has a baseline). Hardening: reporter indirection that swallows a throwing `onError`, generation-guarded timer callbacks (a timer whose clear failed never emits), each stage read isolated (one throwing reader drops only itself; a failed CPU read never advances the baseline), a failing source start leaves its stage unarmed (never half-armed, retried on the next listener change/rebind), a timer that cannot be armed unwinds the stages armed for it, one failing stop never strands another, emitted payloads are copies. `@bugsee/node`'s `trace-producers.ts` is now composition only (ten producers, each subscribed to ONE stage; `NodeTraceProducerDeps` = tracker env + `onError`), and `@bugsee/node` re-exports `processTrackerFor`/`resetProcessTracker`/`ProcessTracker` (and drops the `ProcessStatsTracker`/`ProcessStats` exports). **Behaviour notes:** (1) the tracker is one per PROCESS now, so a second producer set / relaunch shares it and its seams are rebound (tests that inject fakes must pass a private `key` or call `resetProcessTracker()`); (2) per-stage activation means the GC observer and the delay histogram exist only while their producer is subscribed (before, they ran whenever any producer was); (3) the ELU baseline is taken when its stage arms (before: when the producers were built), so the first sample no longer spans an idle gap; (4) the activation CPU/baseline read and the poll are per stage, so one failing reader no longer fails the whole poll (before: an `uptime` failure dropped the whole row); (5) the `current()` cpu baseline is an explicit zero-length window `{0,0,0}` (before: a ~0-length read, same values in practice). **Tooling:** `@bugsee/trackers` gained `@types/node` (devDependency) and `tsconfig.json` now carries `types: ["node"]` for `src/node`; `tsconfig.portable.json` re-typechecks the portable root + browser entries WITHOUT node types (`pnpm typecheck` runs both) so a node global cannot leak into code shipped to browsers. `@bugsee/node` gained the `@bugsee/trackers` workspace dependency. Launch tests prove the default producers go through the registry accessor (mutating the producer factory to `new ProcessTracker` fails them) and that the Bun/Deno gates reach the shared tracker end to end. - **ST0β€² (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing - trace, legacy `sample` kept). Node: `ProcessStatsTracker` (one timer; memory/system RAM/CPU/event-loop) + + trace, legacy `sample` kept). Node: `ProcessStatsTracker` (one timer; memory/system RAM/CPU/event-loop; SUPERSEDED by the `@bugsee/trackers/node` `ProcessTracker`, TR8) + `createNodeSystemTraceProducers` with the Bun/Deno honesty flags on its deps (Deno omits event-loop lag). Browser: `BatteryTracker` (`getBattery` only on activation, abortable) + `BatteryProducer`; the `charging` trace is `{ state: 1|2|3 }` (the viewer's table keys), not a boolean. **Bun/Deno** wire the same diff --git a/packages/bun/src/launch.test.ts b/packages/bun/src/launch.test.ts index 6563443c..c14503eb 100644 --- a/packages/bun/src/launch.test.ts +++ b/packages/bun/src/launch.test.ts @@ -8,7 +8,13 @@ import { type HttpTransport, type Scheduler, } from '@bugsee/core'; -import { createNodeSystemTraceProducers, type NodeRuntime, type SystemProbe } from '@bugsee/node'; +import { + createNodeSystemTraceProducers, + type NodeRuntime, + processTrackerFor, + resetProcessTracker, + type SystemProbe, +} from '@bugsee/node'; import { strFromU8, unzipSync } from '@bugsee/util'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { bunSystemProbe } from './environment'; @@ -96,6 +102,7 @@ beforeEach(() => { const clients: Array<{ stop: (t?: number) => Promise }> = []; afterEach(async () => { await Promise.all(clients.splice(0).map((c) => c.stop())); + resetProcessTracker(); // the per-process ProcessTracker singleton must not carry one test's seams into the next delete (globalThis as { __BUGSEE__?: unknown }).__BUGSEE__; }); const track = Promise }>(c: T): T => { @@ -415,3 +422,28 @@ describe('@bugsee/bun β€” captureSystemTraces:false attaches no trace sampling', expect((await createCaptureExporter(off.store).drain()).get('traces.system')).toBeUndefined(); }); }); + +describe('@bugsee/bun β€” the runtime gates reach the shared ProcessTracker', () => { + it('the per-process tracker honours Bun gates end to end: no V8 heap, no gc, no available memory', () => { + const calls: Array<() => void> = []; + const scheduler: Scheduler = { + setInterval: (cb) => { + calls.push(cb); + return `h${calls.length}`; + }, + clearInterval: () => {}, + }; + 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'); + }); +}); diff --git a/packages/deno/src/launch.test.ts b/packages/deno/src/launch.test.ts index 5b2e957b..7cc830be 100644 --- a/packages/deno/src/launch.test.ts +++ b/packages/deno/src/launch.test.ts @@ -8,7 +8,13 @@ import { type HttpTransport, type Scheduler, } from '@bugsee/core'; -import { createNodeSystemTraceProducers, type NodeRuntime, type SystemProbe } from '@bugsee/node'; +import { + createNodeSystemTraceProducers, + type NodeRuntime, + processTrackerFor, + resetProcessTracker, + type SystemProbe, +} from '@bugsee/node'; import { strFromU8, unzipSync } from '@bugsee/util'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { denoSystemProbe } from './environment'; @@ -98,6 +104,7 @@ beforeEach(() => { const clients: Array<{ stop: (t?: number) => Promise }> = []; afterEach(async () => { await Promise.all(clients.splice(0).map((c) => c.stop())); + resetProcessTracker(); // the per-process ProcessTracker singleton must not carry one test's seams into the next delete (globalThis as { __BUGSEE__?: unknown }).__BUGSEE__; }); const track = Promise }>(c: T): T => { @@ -412,3 +419,28 @@ describe('@bugsee/deno β€” captureSystemTraces:false attaches no trace sampling' expect((await createCaptureExporter(off.store).drain()).get('traces.system')).toBeUndefined(); }); }); + +describe('@bugsee/deno β€” the runtime gates reach the shared ProcessTracker', () => { + it('the per-process tracker honours Deno gates end to end: no lag, no gc, no available memory; V8 heap kept', () => { + const calls: Array<() => void> = []; + const scheduler: Scheduler = { + setInterval: (cb) => { + calls.push(cb); + return `h${calls.length}`; + }, + clearInterval: () => {}, + }; + 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)); + for (const cb of calls) cb(); + off(); + expect(seen).toContain('memory'); + expect(seen).not.toContain('eventLoop'); + expect(seen).not.toContain('gc'); + expect(seen).not.toContain('availableMemory'); + }); +}); diff --git a/packages/node/package.json b/packages/node/package.json index e8c60a6e..c21dce7d 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -35,7 +35,8 @@ "@bugsee/core": "workspace:*", "@bugsee/node-utils": "workspace:*", "@bugsee/performance": "workspace:*", - "@bugsee/protocol": "workspace:*" + "@bugsee/protocol": "workspace:*", + "@bugsee/trackers": "workspace:*" }, "devDependencies": { "@bugsee/util": "workspace:*", diff --git a/packages/node/src/index.test.ts b/packages/node/src/index.test.ts index 8724f939..7b6e2908 100644 --- a/packages/node/src/index.test.ts +++ b/packages/node/src/index.test.ts @@ -46,7 +46,6 @@ const EXPECTED_EXPORTS = [ 'createNodeRequestContextStore', 'createNodeSystemEventsSource', 'createNodeSystemTraceProducers', - 'ProcessStatsTracker', 'createProfilingController', 'createRequestScopedActiveSpanStore', 'createUncaughtExceptionProvider', @@ -63,6 +62,8 @@ const EXPECTED_EXPORTS = [ 'neverThrow', 'openServerContext', 'openServerRequest', + 'processTrackerFor', + 'resetProcessTracker', 'realSystemProbe', 'runServerRequest', 'sanitizeHardwareGpu', diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts index d6438284..8b0cf09b 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -23,6 +23,13 @@ export { neverThrow, type ReportAttachmentInput, } from '@bugsee/core'; +export { + type EventLoopSource, + type PerfHooks, + type ProcessTracker, + processTrackerFor, + resetProcessTracker, +} from '@bugsee/trackers/node'; // The request-scoped active-span store for bare-`@bugsee/node` consumers wiring APM by // hand. One store per context source: the stash key is process-global (realm convergence), so two // live stores over the same source alias on it. The launch builds and owns one; hand-wirers must @@ -125,9 +132,3 @@ export { } from './server-instrument'; export { createNodeSystemEventsSource } from './system-events'; export { createNodeSystemTraceProducers, type NodeTraceProducerDeps } from './trace-producers'; -export type { PerfHooks } from './trackers/guarded-event-loop'; -export { - type EventLoopSource, - type ProcessStats, - ProcessStatsTracker, -} from './trackers/process-stats-tracker'; diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index 8e13cf30..22eca3c9 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -58,6 +58,7 @@ import { type RequestJson, Severity, } from '@bugsee/protocol'; +import { processTrackerFor, resetProcessTracker } from '@bugsee/trackers/node'; import { strFromU8, unzipSync } from '@bugsee/util'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { hashAppToken } from './data-location'; @@ -176,6 +177,7 @@ const clients: ReturnType[] = []; afterEach(async () => { // Stop every launched client so the console interceptor unpatches the global console. await Promise.all(clients.splice(0).map((c) => c.stop())); + resetProcessTracker(); // the per-process ProcessTracker singleton must not carry one test's seams into the next vi.restoreAllMocks(); // Reset the process Carrier so each test builds fresh interceptor singletons (default global path). delete (globalThis as { __BUGSEE__?: unknown }).__BUGSEE__; @@ -1370,6 +1372,49 @@ function seedPriorGeneration( } describe('launch β€” system trace producers', () => { + it('the default producers go through the per-process ProcessTracker registry accessor', async () => { + const fs = fakeScheduler(); + launchTracked( + 'tok', + baseOptions({ + captureStore: memStore(), + clock: fixedClock, + scheduler: fs.scheduler, + systemMetricsSampler: undefined, + }), + ); + // the launch's producers are subscribed to THE `process` singleton: its cpu stage is armed (seeded baseline) + // and its tick is driven by the launch's scheduler + const tracker = processTrackerFor(); + expect(tracker.current('cpu')).toEqual({ userDelta: 0, systemDelta: 0, processPct: 0 }); + expect(fs.calls.some((c) => c.ms === 1000)).toBe(true); + // a relaunch shares the SAME tracker (no second instance, no second set of sources) + expect(processTrackerFor()).toBe(tracker); + }); + + it('a launch reports its onError to the shared tracker (latest launch wins)', async () => { + const onError = vi.fn(); + launchTracked( + 'tok', + baseOptions({ + captureStore: memStore(), + clock: fixedClock, + scheduler: fakeScheduler().scheduler, + systemMetricsSampler: undefined, + onError, + }), + ); + const spy = vi.spyOn(process, 'memoryUsage').mockImplementation(() => { + throw new Error('memoryUsage boom'); + }); + try { + expect(processTrackerFor().current('memory')).toBeUndefined(); + } finally { + spy.mockRestore(); + } + expect(onError.mock.calls.map((c) => (c[0] as Error).message)).toContain('memoryUsage boom'); + }); + const producerDeps = (fs: ReturnType) => { const calls: string[] = []; const perfHooks = { diff --git a/packages/node/src/trace-producers.test.ts b/packages/node/src/trace-producers.test.ts index ba13f0c9..b96af068 100644 --- a/packages/node/src/trace-producers.test.ts +++ b/packages/node/src/trace-producers.test.ts @@ -6,6 +6,7 @@ function harness(deps: NodeTraceProducerDeps) { const spy = { set: 0, cleared: 0 }; let tick: (() => void) | undefined; const producers = createNodeSystemTraceProducers({ + key: {}, // a private tracker per test: the per-process singleton must not leak state between cases ...deps, scheduler: { setInterval: (cb) => { @@ -377,7 +378,7 @@ describe('createNodeSystemTraceProducers', () => { it('real node perf_hooks: the start baseline carries NO lag traces (nothing measured yet)', () => { const got = new Map(); - const ps = createNodeSystemTraceProducers(); + const ps = createNodeSystemTraceProducers({ key: {} }); for (const p of ps) p.start({ emit: (n, v) => void got.set(n, v) }); for (const p of ps) p.stop(); expect(got.has('event_loop_lag_ms')).toBe(false); @@ -391,8 +392,11 @@ describe('createNodeSystemTraceProducers', () => { expect(h.producers).toHaveLength(10); expect(state.monitor).toBe(0); expect(h.spy.set).toBe(0); - h.producers[0]?.start({ emit: () => {} }); + h.producers[0]?.start({ emit: () => {} }); // memory: arms the shared timer only expect(h.spy.set).toBe(1); + expect(state.monitor).toBe(0); // per-stage activation: nothing builds the histogram for a memory subscriber + h.producers[3]?.start({ emit: () => {} }); // event-loop-lag + expect(h.spy.set).toBe(1); // still ONE shared timer expect(state.monitor).toBe(1); expect(state.enabled).toBe(true); }); @@ -435,8 +439,9 @@ describe('createNodeSystemTraceProducers', () => { h.startAll(); const baselineUser = h.got.get('cpu_usage_user'); h.tick(); - // activation read 100k; the single first read (baseline) is 200k, tick is 300k => one window of 100k each - expect(baselineUser).toBe(100_000); + // arming reads 100k (the baseline, seeded as a zero-length window); the single tick reads 200k => one window of + // 100k no matter how many producers share the tracker + expect(baselineUser).toBe(0); expect(h.got.get('cpu_usage_user')).toBe(100_000); }); @@ -475,7 +480,7 @@ describe('createNodeSystemTraceProducers', () => { it('works with real node perf_hooks and no injected readers', () => { const got = new Map(); - const ps = createNodeSystemTraceProducers(); + const ps = createNodeSystemTraceProducers({ key: {} }); for (const p of ps) p.start({ emit: (n, v) => void got.set(n, v) }); for (const p of ps) p.stop(); expect(typeof got.get('process_memory_rss')).toBe('number'); @@ -485,6 +490,7 @@ describe('createNodeSystemTraceProducers', () => { const got = new Map(); let tick: (() => void) | undefined; const ps = createNodeSystemTraceProducers({ + key: {}, scheduler: { setInterval: (cb) => { tick = cb; diff --git a/packages/node/src/trace-producers.ts b/packages/node/src/trace-producers.ts index 3512187e..33194b30 100644 --- a/packages/node/src/trace-producers.ts +++ b/packages/node/src/trace-producers.ts @@ -1,41 +1,36 @@ -import { totalmem } from 'node:os'; -import process from 'node:process'; -import { getHeapStatistics } from 'node:v8'; import { type TraceProducer, TraceProducerBase } from '@bugsee/capture'; -import { createGcSource, type ObserverCtor } from './trackers/gc-observer'; import { - createGuardedElu, - createGuardedEventLoopSource, - type PerfHooks, - realPerfHooks, -} from './trackers/guarded-event-loop'; -import { - type ProcessStats, - type ProcessStatsDeps, - ProcessStatsTracker, -} from './trackers/process-stats-tracker'; -import { - createAvailableMemoryReader, - createMemoryLimitReader, - createV8HeapReader, -} from './trackers/runtime-readers'; + type ProcessEvents, + type ProcessTracker, + type ProcessTrackerEnv, + processTrackerFor, +} from '@bugsee/trackers/node'; + +// Node `traces.system` producers (mirrors the mobile tracker/producer split): ten 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 +// honesty rules (a stage that cannot answer emits nothing, never a zero). -// Node `traces.system` producers (mirrors the mobile tracker/producer split): ten producers over ONE shared -// ProcessStatsTracker. +type Stage = keyof ProcessEvents; -abstract class StatsProducer extends TraceProducerBase { +abstract class StageProducer extends TraceProducerBase { #off: (() => void) | undefined; - constructor(protected readonly tracker: ProcessStatsTracker) { + constructor( + protected readonly tracker: ProcessTracker, + private readonly stage: S, + ) { super(); } - protected abstract publish(stats: ProcessStats): void; + protected abstract publish(payload: ProcessEvents[S]): void; protected onStart(): void { - this.#off = this.tracker.on('stats', (s) => this.publish(s)); // subscribing activates the tracker - this.baseline(this.tracker.current()); + this.#off = this.tracker.on(this.stage, (p) => this.publish(p)); // subscribing arms the stage + this.baseline(); } - /** The value emitted at start. Most families publish the current reading; interval-based ones override. */ - protected baseline(stats: ProcessStats): void { - this.publish(stats); + /** The value emitted at start. Most families publish the current reading; windowed ones override (no baseline). */ + protected baseline(): void { + const current = this.tracker.current(this.stage); + if (current !== undefined) this.publish(current); } protected override onStop(): void { this.#off?.(); @@ -43,60 +38,77 @@ abstract class StatsProducer extends TraceProducerBase { } } -class ProcessMemoryProducer extends StatsProducer { +class ProcessMemoryProducer extends StageProducer<'memory'> { readonly name = 'process-memory'; - protected publish(s: ProcessStats): void { - this.emit('process_memory_rss', s.memory.rss); - this.emit('process_memory_heap_total', s.memory.heapTotal); - this.emit('process_memory_heap_used', s.memory.heapUsed); - this.emit('process_memory_external', s.memory.external); - this.emit('process_memory_array_buffers', s.memory.arrayBuffers); + constructor(tracker: ProcessTracker) { + super(tracker, 'memory'); + } + protected publish(m: ProcessEvents['memory']): void { + this.emit('process_memory_rss', m.rss); + this.emit('process_memory_heap_total', m.heapTotal); + this.emit('process_memory_heap_used', m.heapUsed); + this.emit('process_memory_external', m.external); + this.emit('process_memory_array_buffers', m.arrayBuffers); } } -class SystemMemoryProducer extends StatsProducer { +class SystemMemoryProducer extends StageProducer<'systemMemory'> { readonly name = 'system-memory'; - protected publish(s: ProcessStats): void { - this.emit('ram_system_total', s.systemMemory.total); - this.emit('ram_system_free', s.systemMemory.free); + constructor(tracker: ProcessTracker) { + super(tracker, 'systemMemory'); + } + protected publish(m: ProcessEvents['systemMemory']): void { + this.emit('ram_system_total', m.total); + this.emit('ram_system_free', m.free); } } -class CpuProducer extends StatsProducer { +class CpuProducer extends StageProducer<'cpu'> { readonly name = 'cpu'; - protected publish(s: ProcessStats): void { - this.emit('cpu_usage_user', s.cpu.userDelta); - this.emit('cpu_usage_system', s.cpu.systemDelta); - this.emit('cpu_usage_process', s.cpu.processPct); + constructor(tracker: ProcessTracker) { + super(tracker, 'cpu'); + } + protected publish(c: ProcessEvents['cpu']): void { + this.emit('cpu_usage_user', c.userDelta); + this.emit('cpu_usage_system', c.systemDelta); + this.emit('cpu_usage_process', c.processPct); } } -// Omitted, never zeroed, when the runtime cannot measure it. -class EventLoopLagProducer extends StatsProducer { +// Omitted, never zeroed, when the runtime cannot measure it (the tracker emits nothing then). No baseline: a +// window has not elapsed at start, and a restart while the stage stays armed must not re-emit the last window. +class EventLoopLagProducer extends StageProducer<'eventLoop'> { readonly name = 'event-loop-lag'; - protected publish(s: ProcessStats): void { - if (s.eventLoop === undefined) return; - this.emit('event_loop_lag_ms', s.eventLoop.meanMs); - this.emit('event_loop_lag_max_ms', s.eventLoop.maxMs); - this.emit('event_loop_lag_p99_ms', s.eventLoop.p99Ms); + constructor(tracker: ProcessTracker) { + super(tracker, 'eventLoop'); + } + protected override baseline(): void {} + protected publish(l: ProcessEvents['eventLoop']): void { + this.emit('event_loop_lag_ms', l.meanMs); + this.emit('event_loop_lag_max_ms', l.maxMs); + this.emit('event_loop_lag_p99_ms', l.p99Ms); } } -class EventLoopUtilizationProducer extends StatsProducer { +class EventLoopUtilizationProducer extends StageProducer<'utilization'> { readonly name = 'event-loop-utilization'; - protected publish(s: ProcessStats): void { - if (s.utilization === undefined) return; - this.emit('event_loop_utilization', s.utilization); + constructor(tracker: ProcessTracker) { + super(tracker, 'utilization'); + } + protected override baseline(): void {} + protected publish(u: ProcessEvents['utilization']): void { + this.emit('event_loop_utilization', u.utilization); } } // `ram_js_heap_*` is the CEILING-based view shared with the browser and Android (`total` = the heap limit), // so it is NOT an alias of `process_memory_heap_*` (committed heap). Only `used` is the same number. -class V8HeapProducer extends StatsProducer { +class V8HeapProducer extends StageProducer<'v8Heap'> { readonly name = 'v8-heap'; - protected publish(s: ProcessStats): void { - const h = s.v8Heap; - if (h === undefined) return; + constructor(tracker: ProcessTracker) { + super(tracker, 'v8Heap'); + } + protected publish(h: ProcessEvents['v8Heap']): void { this.emit('v8_heap_size_limit', h.limit); this.emit('v8_heap_available', h.available); this.emit('v8_heap_malloced', h.malloced); @@ -109,108 +121,65 @@ class V8HeapProducer extends StatsProducer { // Emitted every tick, never held for the provider's refresh: a cap can be lifted at runtime, and a held value // would then be re-recorded as a stale limit instead of being omitted. -class MemoryLimitProducer extends StatsProducer { +class MemoryLimitProducer extends StageProducer<'memoryLimit'> { readonly name = 'process-memory-limit'; - protected publish(s: ProcessStats): void { - if (s.memoryLimit !== undefined) this.emit('process_memory_limit', s.memoryLimit); + constructor(tracker: ProcessTracker) { + super(tracker, 'memoryLimit'); + } + protected publish(m: ProcessEvents['memoryLimit']): void { + this.emit('process_memory_limit', m.bytes); } } -class AvailableMemoryProducer extends StatsProducer { +class AvailableMemoryProducer extends StageProducer<'availableMemory'> { readonly name = 'system-memory-available'; - protected publish(s: ProcessStats): void { - if (s.availableMemory !== undefined) this.emit('ram_system_available', s.availableMemory); + 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. -class GcProducer extends StatsProducer { +// 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). +class GcProducer extends StageProducer<'gc'> { readonly name = 'gc'; - // No baseline: the interval opens at activation, so nothing has been observed yet (a zero would be invented), - // and a restart while the tracker stays active would re-emit the last interval's cached counts. + constructor(tracker: ProcessTracker) { + super(tracker, 'gc'); + } protected override baseline(): void {} - protected publish(s: ProcessStats): void { - if (s.gc === undefined) return; - this.emit('gc_count', s.gc.count); - this.emit('gc_pause_ms', s.gc.pauseMs); - this.emit('gc_pause_max_ms', s.gc.maxPauseMs); + protected publish(g: ProcessEvents['gc']): void { + this.emit('gc_count', g.count); + this.emit('gc_pause_ms', g.pauseMs); + this.emit('gc_pause_max_ms', g.maxPauseMs); } } -class UptimeProducer extends StatsProducer { +class UptimeProducer extends StageProducer<'uptime'> { readonly name = 'process-uptime'; - protected publish(s: ProcessStats): void { - this.emit('process_uptime_s', s.uptimeS); + constructor(tracker: ProcessTracker) { + super(tracker, 'uptime'); + } + protected publish(u: ProcessEvents['uptime']): void { + this.emit('process_uptime_s', u.seconds); } } -export interface NodeTraceProducerDeps extends ProcessStatsDeps { - /** perf_hooks primitives for the event-loop metrics (partial on Bun/Deno). Default node:perf_hooks. */ - perfHooks?: PerfHooks; - /** - * Does this runtime's `monitorEventLoopDelay` observe a BLOCKED loop? Default `true`. Deno's does not - * (answers, never throws, never registers a stall), so `@bugsee/deno` passes `false` and the histogram - * is never even constructed. - */ - measuresEventLoopDelay?: boolean; - /** - * Is `v8.getHeapStatistics()` a real V8 heap with a ceiling? Default `true`. Bun's is JSC-derived (its - * `heap_size_limit` is not a ceiling, so `limit - used` means nothing, and it costs ~1000x Node per call β€” - * measured), so `@bugsee/bun` passes `false` and `v8_heap_*` / `ram_js_heap_*` are omitted. - */ - measuresV8Heap?: boolean; - /** - * Is `process.availableMemory()` comparable to the Node figure? Default `true`. It is not on Bun/Deno: - * Deno answered 23 GB against Node's 3.4 GB on one macOS host, and on Linux both ignore the container - * cap (11.2 GB under `docker -m 256m` where Node answers 253 MB). `@bugsee/deno` and `@bugsee/bun` - * pass `false` and `ram_system_available` is omitted there. - */ - measuresAvailableMemory?: boolean; - /** - * Does `PerformanceObserver({entryTypes:['gc']})` see collections? Default `true`. It is blind on Bun and - * Deno (0 entries after heavy churn and forced GC β€” measured), where a quiet-looking zero would be a lie, so - * `@bugsee/bun` / `@bugsee/deno` pass `false` and no observer is ever constructed. - */ - measuresGc?: boolean; - /** Test seam for the GC observer constructor. Default `node:perf_hooks`. */ - performanceObserver?: ObserverCtor; +/** + * The tracker seams plus the platform GATES (`measuresEventLoopDelay`, `measuresV8Heap`, `measuresAvailableMemory`, + * `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. + */ +export interface NodeTraceProducerDeps extends ProcessTrackerEnv { + onError?: (error: unknown) => void; } export function createNodeSystemTraceProducers(deps: NodeTraceProducerDeps = {}): TraceProducer[] { - const { - perfHooks, - measuresEventLoopDelay = true, - measuresV8Heap = true, - measuresAvailableMemory = true, - measuresGc = true, - performanceObserver, - ...rest - } = deps; - const perf = perfHooks ?? realPerfHooks; - // `??` / conditional spreads (never a bare `...rest` over defaults): an explicit `undefined` must not - // clobber a default, and `eventLoop` must be ABSENT (not undefined) when the runtime cannot measure it. - const eventLoop = - rest.eventLoop ?? - (measuresEventLoopDelay ? createGuardedEventLoopSource(perf.monitorEventLoopDelay) : undefined); - const gc = rest.gc ?? (measuresGc ? createGcSource(performanceObserver) : undefined); - const tracker = new ProcessStatsTracker({ - ...rest, - ...(gc !== undefined ? { gc } : {}), - ...(eventLoop !== undefined ? { eventLoop } : {}), - eventLoopUtilization: rest.eventLoopUtilization ?? createGuardedElu(perf.eventLoopUtilization), - // Same rule as `eventLoop`: an injected reader wins, otherwise the default is wired only where the runtime - // can give a true value; an unwired reader means the field is ABSENT. - ...optionalReader('v8Heap', rest.v8Heap, measuresV8Heap, () => - createV8HeapReader(getHeapStatistics), - ), - ...optionalReader('memoryLimit', rest.memoryLimit, true, () => - createMemoryLimitReader(process, totalmem), - ), - ...optionalReader('availableMemory', rest.availableMemory, measuresAvailableMemory, () => - createAvailableMemoryReader(process), - ), - }); + const { onError, ...env } = deps; + // The per-process singleton: a relaunch (or a second producer set) shares it and hands it THIS launch's seams. + const tracker = processTrackerFor(env, onError); return [ new ProcessMemoryProducer(tracker), new SystemMemoryProducer(tracker), @@ -224,14 +193,3 @@ export function createNodeSystemTraceProducers(deps: NodeTraceProducerDeps = {}) new UptimeProducer(tracker), ]; } - -/** `{ [key]: reader }` for an injected reader, else the default when `enabled`, else nothing. */ -function optionalReader( - key: K, - injected: R | undefined, - enabled: boolean, - make: () => R, -): { [P in K]?: R } { - const reader = injected ?? (enabled ? make() : undefined); - return (reader !== undefined ? { [key]: reader } : {}) as { [P in K]?: R }; -} diff --git a/packages/node/src/trackers/process-stats-tracker.test.ts b/packages/node/src/trackers/process-stats-tracker.test.ts deleted file mode 100644 index 3c21b8e4..00000000 --- a/packages/node/src/trackers/process-stats-tracker.test.ts +++ /dev/null @@ -1,734 +0,0 @@ -import type { Scheduler } from '@bugsee/core'; -import { describe, expect, it, vi } from 'vitest'; -import type { GcSource } from './gc-observer'; -import { - type EventLoopSource, - type ProcessStats, - ProcessStatsTracker, -} from './process-stats-tracker'; - -// Every handle is unique, and clearInterval must be handed exactly a live handle setInterval returned β€” -// so clearing `undefined`/`null` (a handle dropped too early) or the same handle twice fails the test. -function fakeScheduler() { - let cb: (() => void) | null = null; - let cleared = 0; - let sets = 0; - const live = new Set(); - const scheduler: Scheduler = { - setInterval: (c) => { - cb = c; - sets += 1; - const handle = { id: sets }; - live.add(handle); - return handle; - }, - clearInterval: (h) => { - expect(live.has(h), `clearInterval(${JSON.stringify(h)}) is not a live handle`).toBe(true); - live.delete(h); - cleared += 1; - }, - }; - return { scheduler, tick: () => cb?.(), cleared: () => cleared, sets: () => sets }; -} -const mem = { rss: 1, heapTotal: 2, heapUsed: 3, external: 4, arrayBuffers: 5 }; -function mk(over: Partial[0]> = {}) { - let cpu = { user: 0, system: 0 }; - let wall = 0; - const fs = fakeScheduler(); - const tracker = new ProcessStatsTracker({ - memoryUsage: () => mem, - systemMemory: () => ({ total: 100, free: 40 }), - cpuUsage: () => cpu, - cpuCount: () => 2, - monotonicNowMs: () => wall, - scheduler: fs.scheduler, - intervalMs: 1000, - ...over, - }); - return { - tracker, - fs, - advance: (c: { user: number; system: number }, w: number) => { - cpu = c; - wall = w; - }, - }; -} - -describe('ProcessStatsTracker', () => { - it('attaches NOTHING at construction (no timer, no sources started)', () => { - const started: string[] = []; - const eventLoop: EventLoopSource = { - read: () => undefined, - start: () => void started.push('start'), - stop: () => void started.push('stop'), - }; - const { fs } = mk({ eventLoop }); - expect(fs.sets()).toBe(0); - expect(started).toEqual([]); - }); - - it('the first subscriber activates it: one timer + event-loop source started; the last one leaves β†’ released', () => { - const calls: string[] = []; - const eventLoop: EventLoopSource = { - read: () => undefined, - start: () => void calls.push('start'), - stop: () => void calls.push('stop'), - }; - const { tracker, fs } = mk({ eventLoop }); - const off1 = tracker.on('stats', () => {}); - const off2 = tracker.on('stats', () => {}); - expect(fs.sets()).toBe(1); - expect(calls).toEqual(['start']); - off1(); - expect(fs.cleared()).toBe(0); // still one subscriber - off2(); - expect(fs.cleared()).toBe(1); - expect(calls).toEqual(['start', 'stop']); - }); - - it('emits stats on each tick with cpu deltas over the wall window (normalized by cores)', () => { - const { tracker, fs, advance } = mk(); - const got: ProcessStats[] = []; - tracker.on('stats', (s) => got.push(s)); - advance({ user: 400_000, system: 200_000 }, 1000); // 600 000 Β΅s busy over 1 000 ms on 2 cores - fs.tick(); - expect(got).toHaveLength(1); - expect(got[0]?.memory).toEqual(mem); - expect(got[0]?.systemMemory).toEqual({ total: 100, free: 40 }); - expect(got[0]?.cpu).toEqual({ userDelta: 400_000, systemDelta: 200_000, processPct: 30 }); - }); - - it('current() returns the cached stats and does NOT advance the cpu baseline (shared by many producers)', () => { - const { tracker, advance } = mk(); - tracker.on('stats', () => {}); - const a = tracker.current(); - advance({ user: 500_000, system: 0 }, 1000); - const b = tracker.current(); - const c = tracker.current(); - expect(b).toBe(a); - expect(c).toBe(a); // same object until the next poll - expect(a.cpu.userDelta).toBe(0); // baseline: no delta yet - }); - - it('a zero wall window yields processPct 0 (no divide by zero)', () => { - const { tracker, fs } = mk(); - const got: ProcessStats[] = []; - tracker.on('stats', (s) => got.push(s)); - fs.tick(); // wall unchanged - expect(got[0]?.cpu.processPct).toBe(0); - }); - - it('includes eventLoop / utilization only when their sources answer (omitted, never zeroed)', () => { - const { tracker, fs } = mk({ - eventLoop: { - read: () => ({ meanMs: 1, maxMs: 2, p99Ms: 3 }), - start: () => {}, - stop: () => {}, - }, - eventLoopUtilization: () => undefined, - }); - const got: ProcessStats[] = []; - tracker.on('stats', (s) => got.push(s)); - fs.tick(); - expect(got[0]?.eventLoop).toEqual({ meanMs: 1, maxMs: 2, p99Ms: 3 }); - expect('utilization' in (got[0] ?? {})).toBe(false); - }); - - it('restart: re-attaches and re-baselines (no stale cache)', () => { - const { tracker, fs, advance } = mk(); - const off = tracker.on('stats', () => {}); - advance({ user: 1, system: 1 }, 10); - off(); - tracker.on('stats', () => {}); - expect(fs.sets()).toBe(2); - expect(tracker.current().cpu.userDelta).toBe(0); - }); - - it('a throwing reader is reported via onError and does not break the timer', () => { - const errors: unknown[] = []; - let boom = false; - const { tracker, fs } = mk({ - memoryUsage: () => { - if (boom) throw new Error('read boom'); - return mem; - }, - onError: (e) => errors.push(e), - }); - const got: ProcessStats[] = []; - tracker.on('stats', (s) => got.push(s)); - boom = true; - expect(() => fs.tick()).not.toThrow(); - expect(got).toHaveLength(0); - expect((errors[0] as Error).message).toBe('read boom'); - }); - - it('an explicit undefined dep falls back to the default (not clobbered)', () => { - const { tracker } = mk({ memoryUsage: undefined, cpuCount: undefined }); - const got: ProcessStats[] = []; - tracker.on('stats', (s) => got.push(s)); - const s = tracker.current(); - expect(s.memory.rss).not.toBe(1); // the injected-default 'mem' is not used; real reader is - expect(typeof s.memory.heapUsed).toBe('number'); - }); - - it("uses real defaults (os/perf_hooks/process) and an unref'd default scheduler", () => { - const tracker = new ProcessStatsTracker({ intervalMs: 5 }); - const off = tracker.on('stats', () => {}); - const s = tracker.current(); - expect(s.systemMemory.total).toBeGreaterThan(0); - expect(s.cpu.processPct).toBeGreaterThanOrEqual(0); - off(); // clears the real interval - }); - - it('the default scheduler delivers ticks, and is silent after the last unsubscribe', () => { - vi.useFakeTimers(); - try { - const tracker = new ProcessStatsTracker({ intervalMs: 5 }); - const got: ProcessStats[] = []; - const off = tracker.on('stats', (s) => got.push(s)); - vi.advanceTimersByTime(5); - expect(got).toHaveLength(1); - vi.advanceTimersByTime(10); - expect(got).toHaveLength(3); - off(); - expect(vi.getTimerCount()).toBe(0); // the real interval was cleared - vi.advanceTimersByTime(100); - expect(got).toHaveLength(3); - } finally { - vi.useRealTimers(); - } - }); - - it('reports utilization when the source answers', () => { - const { tracker, fs } = mk({ eventLoopUtilization: () => 0.5 }); - const got: ProcessStats[] = []; - tracker.on('stats', (s) => got.push(s)); - fs.tick(); - expect(got[0]?.utilization).toBe(0.5); - }); - - it('onError is optional: a throwing reader without onError is swallowed', () => { - let boom = false; - const { tracker, fs } = mk({ - memoryUsage: () => { - if (boom) throw new Error('x'); - return mem; - }, - }); - tracker.on('stats', () => {}); - boom = true; - expect(() => fs.tick()).not.toThrow(); - }); - - it('a deactivate with no event-loop source is fine', () => { - const { tracker, fs } = mk(); - tracker.on('stats', () => {})(); - expect(fs.cleared()).toBe(1); - }); - - it('current() inside a stats listener already returns the emitted stats (cached before emit)', () => { - const { tracker, fs } = mk({ memoryUsage: () => ({ ...mem }) }); - let seen: ProcessStats | undefined; - let inside: ProcessStats | undefined; - tracker.on('stats', (s) => { - seen = s; - inside = tracker.current(); - }); - fs.tick(); - expect(inside).toBe(seen); - }); - - it('deactivation drops the cache: current() afterwards is a fresh read', () => { - const { tracker, fs } = mk({ memoryUsage: () => ({ ...mem }) }); - const off = tracker.on('stats', () => {}); - fs.tick(); - const before = tracker.current(); - off(); - expect(tracker.current()).not.toBe(before); - }); - - it('activation discards a cache taken before any subscriber', () => { - const { tracker } = mk({ memoryUsage: () => ({ ...mem }) }); - const early = tracker.current(); - tracker.on('stats', () => {}); - expect(tracker.current()).not.toBe(early); - }); - - it('a throwing reader AT ACTIVATION: reported via onError, on() does not throw, nothing left attached, and a later activation retries', () => { - const errors: unknown[] = []; - const calls: string[] = []; - let broken = true; - const eventLoop: EventLoopSource = { - read: () => undefined, - start: () => void calls.push('start'), - stop: () => void calls.push('stop'), - }; - const { tracker, fs } = mk({ - cpuUsage: () => { - if (broken) throw new Error('cpu boom'); - return { user: 0, system: 0 }; - }, - eventLoop, - onError: (e) => errors.push(e), - }); - let off: (() => void) | undefined; - expect(() => { - off = tracker.on('stats', () => {}); - }).not.toThrow(); - expect((errors[0] as Error).message).toBe('cpu boom'); - expect(fs.sets()).toBe(0); // no timer was registered - off?.(); - broken = false; - const got: ProcessStats[] = []; - tracker.on('stats', (s) => got.push(s)); - expect(fs.sets()).toBe(1); - expect(calls).toEqual(['start']); - fs.tick(); - expect(got).toHaveLength(1); - expect(errors).toHaveLength(1); - }); - - it('current() after a failed activation RETRIES it (timer + event-loop source) instead of accepting a baseline from an unarmed tracker', () => { - const errors: unknown[] = []; - const calls: string[] = []; - let broken = true; - const eventLoop: EventLoopSource = { - read: () => undefined, - start: () => void calls.push('start'), - stop: () => void calls.push('stop'), - }; - const { tracker, fs } = mk({ - cpuUsage: () => { - if (broken) throw new Error('cpu boom'); - return { user: 0, system: 0 }; - }, - eventLoop, - onError: (e) => errors.push(e), - }); - const got: ProcessStats[] = []; - tracker.on('stats', (s) => got.push(s)); // activation fails, subscriber stays registered - expect(fs.sets()).toBe(0); - broken = false; - expect(tracker.current().memory).toEqual(mem); // the retry succeeds before the baseline is read - expect(fs.sets()).toBe(1); - expect(calls).toEqual(['start']); - fs.tick(); - expect(got).toHaveLength(1); // the already-registered subscriber now receives ticks - expect(tracker.current()).toBe(got[0]); - expect(errors).toHaveLength(1); - // the retry happens once: a further current() does not re-activate - tracker.current(); - expect(fs.sets()).toBe(1); - expect(calls).toEqual(['start']); - }); - - it('current() after a failed activation whose retry ALSO fails propagates the failure (and a later current() retries again)', () => { - const errors: unknown[] = []; - let broken = true; - const { tracker, fs } = mk({ - cpuUsage: () => { - if (broken) throw new Error('cpu boom'); - return { user: 0, system: 0 }; - }, - onError: (e) => errors.push(e), - }); - tracker.on('stats', () => {}); - expect(() => tracker.current()).toThrow('cpu boom'); - expect(fs.sets()).toBe(0); - broken = false; - expect(() => tracker.current()).not.toThrow(); - expect(fs.sets()).toBe(1); - }); - - it('a pending activation failure is cleared on deactivation: current() with no subscribers does not activate', () => { - let broken = true; - const { tracker, fs } = mk({ - cpuUsage: () => { - if (broken) throw new Error('cpu boom'); - return { user: 0, system: 0 }; - }, - onError: () => {}, - }); - const off = tracker.on('stats', () => {}); - off(); - broken = false; - tracker.current(); - expect(fs.sets()).toBe(0); // no subscriber β†’ no retry, no timer - }); - - it('a throwing setInterval at activation stops the already-started event-loop source', () => { - const errors: unknown[] = []; - const calls: string[] = []; - let refuse = true; - const eventLoop: EventLoopSource = { - read: () => undefined, - start: () => void calls.push('start'), - stop: () => void calls.push('stop'), - }; - let sets = 0; - let cleared = 0; - const scheduler: Scheduler = { - setInterval: () => { - if (refuse) throw new Error('no timers'); - sets += 1; - return 'h'; - }, - clearInterval: () => { - cleared += 1; - }, - }; - const { tracker } = mk({ eventLoop, scheduler, onError: (e) => errors.push(e) }); - const off = tracker.on('stats', () => {}); - expect((errors[0] as Error).message).toBe('no timers'); - expect(calls).toEqual(['start', 'stop']); - off(); - refuse = false; - tracker.on('stats', () => {}); - expect(sets).toBe(1); - expect(calls).toEqual(['start', 'stop', 'start']); // the unwound source is not stopped twice - expect(cleared).toBe(0); // the failed activation registered no timer, so there was none to clear - }); - - it('an activation failure before the event-loop source started does not stop it, and onError is optional', () => { - const calls: string[] = []; - const eventLoop: EventLoopSource = { - read: () => undefined, - start: () => void calls.push('start'), - stop: () => void calls.push('stop'), - }; - const { tracker } = mk({ - monotonicNowMs: () => { - throw new Error('clock boom'); - }, - eventLoop, - }); - expect(() => tracker.on('stats', () => {})).not.toThrow(); - expect(calls).toEqual([]); - }); - - it('a throwing event-loop stop() during the activation unwind is reported and the original error is too', () => { - const errors: unknown[] = []; - const eventLoop: EventLoopSource = { - read: () => undefined, - start: () => {}, - stop: () => { - throw new Error('stop boom'); - }, - }; - const scheduler: Scheduler = { - setInterval: () => { - throw new Error('no timers'); - }, - clearInterval: () => {}, - }; - const { tracker } = mk({ eventLoop, scheduler, onError: (e) => errors.push(e) }); - expect(() => tracker.on('stats', () => {})).not.toThrow(); - expect(errors.map((e) => (e as Error).message).sort()).toEqual(['no timers', 'stop boom']); - }); - - it('an event-loop source whose start() throws is reported and is NOT stopped (it never started)', () => { - const errors: unknown[] = []; - const calls: string[] = []; - const eventLoop: EventLoopSource = { - read: () => undefined, - start: () => { - calls.push('start'); - throw new Error('start boom'); - }, - stop: () => void calls.push('stop'), - }; - const { tracker, fs } = mk({ eventLoop, onError: (e) => errors.push(e) }); - tracker.on('stats', () => {})(); - expect((errors[0] as Error).message).toBe('start boom'); - expect(calls).toEqual(['start']); - expect(fs.sets()).toBe(0); - }); - - describe('gc source', () => { - const interval = { count: 2, pauseMs: 9, maxPauseMs: 6 }; - const mkGc = (over: Partial = {}) => { - const calls: string[] = []; - const gc: GcSource = { - start: () => void calls.push('start'), - stop: () => void calls.push('stop'), - read: () => interval, - ...over, - }; - return { gc, calls }; - }; - - it('starts on the first subscriber, stops on the last, and starts nothing before', () => { - const { gc, calls } = mkGc(); - const { tracker } = mk({ gc }); - expect(calls).toEqual([]); - const off = tracker.on('stats', () => {}); - expect(calls).toEqual(['start']); - off(); - expect(calls).toEqual(['start', 'stop']); - }); - - it('carries the interval on the baseline and on every poll; absent when the source answers undefined or is not wired', () => { - const { gc } = mkGc(); - const { tracker, fs } = mk({ gc }); - const got: ProcessStats[] = []; - tracker.on('stats', (st) => got.push(st)); - expect(tracker.current().gc).toEqual(interval); - fs.tick(); - expect(got[0]?.gc).toEqual(interval); - - const none = mk({ gc: mkGc({ read: () => undefined }).gc }); - none.tracker.on('stats', () => {}); - expect('gc' in none.tracker.current()).toBe(false); - const unwired = mk(); - unwired.tracker.on('stats', () => {}); - expect('gc' in unwired.tracker.current()).toBe(false); - }); - - it('a throwing read is reported and only gc is dropped', () => { - const errors: unknown[] = []; - const { gc } = mkGc({ - read: () => { - throw new Error('gc read'); - }, - }); - const { tracker } = mk({ gc, onError: (e) => errors.push(e) }); - tracker.on('stats', () => {}); - const cur = tracker.current(); - expect('gc' in cur).toBe(false); - expect(cur.memory).toEqual(mem); - expect((errors[0] as Error).message).toBe('gc read'); - }); - - it('a failed activation after gc started stops it; a gc whose start() throws is reported and not stopped', () => { - const a = mkGc(); - const scheduler: Scheduler = { - setInterval: () => { - throw new Error('no timers'); - }, - clearInterval: () => {}, - }; - mk({ gc: a.gc, scheduler }).tracker.on('stats', () => {})(); - expect(a.calls).toEqual(['start', 'stop']); // stopped once by the unwind, never again on release - - const errors: unknown[] = []; - const b = mkGc({ - start: () => { - throw new Error('start boom'); - }, - }); - mk({ gc: b.gc, onError: (e) => errors.push(e) }).tracker.on('stats', () => {})(); - expect((errors[0] as Error).message).toBe('start boom'); - expect(b.calls).toEqual([]); - }); - - it('a throwing gc stop() does not strand the event-loop source stop (and vice versa)', () => { - const calls: string[] = []; - const eventLoop: EventLoopSource = { - read: () => undefined, - start: () => {}, - stop: () => { - calls.push('el-stop'); - throw new Error('el'); - }, - }; - const { gc } = mkGc({ - stop: () => { - calls.push('gc-stop'); - throw new Error('gc'); - }, - }); - const errors: unknown[] = []; - const { tracker } = mk({ gc, eventLoop, onError: (e) => errors.push(e) }); - const off = tracker.on('stats', () => {}); - expect(() => off()).not.toThrow(); - expect(calls.sort()).toEqual(['el-stop', 'gc-stop']); - expect(errors.map((e) => (e as Error).message).sort()).toEqual(['el', 'gc']); - }); - - it('a poll that fails before gc is read does not drain the interval', () => { - let reads = 0; - let boom = true; - const { gc } = mkGc({ - read: () => { - reads += 1; - return interval; - }, - }); - const { tracker, fs } = mk({ - gc, - eventLoopUtilization: () => { - if (boom) throw new Error('elu'); - return 0.1; - }, - onError: () => {}, - }); - const got: ProcessStats[] = []; - tracker.on('stats', (st) => got.push(st)); - // the activation baseline is read lazily, so the first poll is the failing one - fs.tick(); - expect(got).toHaveLength(0); - expect(reads).toBe(0); - boom = false; - fs.tick(); - expect(got[0]?.gc).toEqual(interval); - }); - - it('a throwing onError during a failing stop() does not strand the other source', () => { - const calls: string[] = []; - const eventLoop: EventLoopSource = { - read: () => undefined, - start: () => {}, - stop: () => { - calls.push('el-stop'); - throw new Error('el'); - }, - }; - const { gc } = mkGc({ - stop: () => { - calls.push('gc-stop'); - throw new Error('gc'); - }, - }); - const { tracker } = mk({ - gc, - eventLoop, - onError: () => { - throw new Error('reporter'); - }, - }); - const off = tracker.on('stats', () => {}); - expect(() => off()).not.toThrow(); - expect(calls.sort()).toEqual(['el-stop', 'gc-stop']); - }); - - it('restarts the source on re-activation', () => { - const { gc, calls } = mkGc(); - const { tracker } = mk({ gc }); - tracker.on('stats', () => {})(); - tracker.on('stats', () => {}); - expect(calls).toEqual(['start', 'stop', 'start']); - }); - }); - - describe('runtime-depth readers (v8 heap, memory limit, available memory, uptime)', () => { - const heap = { limit: 100, used: 30, available: 70, malloced: 5, peakMalloced: 6 }; - - it('carries uptime in whole seconds, and no optional field when no reader is given', () => { - const { tracker } = mk({ uptime: () => 12.9 }); - const stats = tracker.current(); - expect(stats.uptimeS).toBe(12); - expect(stats).not.toHaveProperty('v8Heap'); - expect(stats).not.toHaveProperty('memoryLimit'); - expect(stats).not.toHaveProperty('availableMemory'); - }); - - it('defaults uptime to process.uptime()', () => { - const spy = vi.spyOn(process, 'uptime').mockReturnValue(99.5); - try { - expect(mk().tracker.current().uptimeS).toBe(99); - } finally { - spy.mockRestore(); - } - }); - - it('exposes each injected reader, on the baseline and on every poll', () => { - let used = 30; - const { tracker, fs } = mk({ - v8Heap: () => ({ ...heap, used }), - memoryLimit: () => 777, - availableMemory: () => 555, - uptime: () => 3, - }); - const seen: ProcessStats[] = []; - tracker.on('stats', (s) => seen.push(s)); - expect(tracker.current()).toMatchObject({ - v8Heap: heap, - memoryLimit: 777, - availableMemory: 555, - uptimeS: 3, - }); - used = 31; - fs.tick(); - expect(seen[0]?.v8Heap?.used).toBe(31); - expect(seen[0]?.memoryLimit).toBe(777); - expect(seen[0]?.availableMemory).toBe(555); - }); - - it('omits a field whose reader answers undefined', () => { - const { tracker } = mk({ - v8Heap: () => undefined, - memoryLimit: () => undefined, - availableMemory: () => undefined, - }); - const stats = tracker.current(); - expect(stats).not.toHaveProperty('v8Heap'); - expect(stats).not.toHaveProperty('memoryLimit'); - expect(stats).not.toHaveProperty('availableMemory'); - }); - - it('a throwing reader is reported and ONLY its field is dropped (memory/cpu/other readers survive)', () => { - const onError = vi.fn(); - const { tracker, fs } = mk({ - v8Heap: () => { - throw new Error('v8'); - }, - memoryLimit: () => 777, - availableMemory: () => { - throw new Error('avail'); - }, - onError, - }); - const seen: ProcessStats[] = []; - tracker.on('stats', (s) => seen.push(s)); - const base = tracker.current(); - expect(base.memory).toEqual(mem); - expect(base.memoryLimit).toBe(777); - expect(base).not.toHaveProperty('v8Heap'); - expect(base).not.toHaveProperty('availableMemory'); - expect(onError).toHaveBeenCalledTimes(2); - fs.tick(); - expect(seen).toHaveLength(1); - expect(seen[0]?.memoryLimit).toBe(777); - expect(onError).toHaveBeenCalledTimes(4); - }); - - it('a throwing uptime reader does not advance the CPU baseline: the next delta covers the whole gap', () => { - let fail = true; - const { tracker, fs, advance } = mk({ - uptime: () => { - if (fail) throw new Error('uptime'); - return 1; - }, - onError: () => {}, - }); - const seen: ProcessStats[] = []; - tracker.on('stats', (s) => seen.push(s)); - advance({ user: 100, system: 40 }, 1000); - fs.tick(); // fails: nothing emitted, baseline untouched - fail = false; - advance({ user: 300, system: 100 }, 2000); - fs.tick(); - expect(seen).toHaveLength(1); - expect(seen[0]?.cpu).toMatchObject({ userDelta: 300, systemDelta: 100 }); - }); - - it('a throwing uptime reader is reported and the stats are not emitted for that poll', () => { - const onError = vi.fn(); - let fail = false; - const { tracker, fs } = mk({ - uptime: () => { - if (fail) throw new Error('uptime'); - return 1; - }, - onError, - }); - const seen: ProcessStats[] = []; - tracker.on('stats', (s) => seen.push(s)); - fail = true; - fs.tick(); - expect(seen).toEqual([]); - expect(onError).toHaveBeenCalledTimes(1); - }); - }); -}); diff --git a/packages/node/src/trackers/process-stats-tracker.ts b/packages/node/src/trackers/process-stats-tracker.ts deleted file mode 100644 index 776aa9de..00000000 --- a/packages/node/src/trackers/process-stats-tracker.ts +++ /dev/null @@ -1,260 +0,0 @@ -import { cpus, freemem, totalmem } from 'node:os'; -import { performance } from 'node:perf_hooks'; -import { InterceptorBase, type Scheduler } from '@bugsee/core'; -import type { GcInterval, GcSource } from './gc-observer'; -import type { V8HeapStats } from './runtime-readers'; - -// Shared node process-stats TRACKER (mirrors the mobile tracker/producer split): ONE timer aggregates -// memory / system RAM / CPU deltas (+ optional event-loop sources) into a ProcessStats object that many -// per-trace producers read. Attaches nothing until its first subscriber; the last unsubscribe releases -// the timer and stops the event-loop source. - -export interface EventLoopSource { - /** Mean/max/p99 lag (ms) since the previous read, or undefined when the runtime cannot measure it. */ - read(): { meanMs: number; maxMs: number; p99Ms: number } | undefined; - start(): void; - stop(): void; -} - -export interface ProcessStats { - memory: { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - arrayBuffers: number; - }; - systemMemory: { total: number; free: number }; - cpu: { userDelta: number; systemDelta: number; processPct: number }; - eventLoop?: { meanMs: number; maxMs: number; p99Ms: number }; - /** GC activity since the previous poll; ABSENT (never zero) when no GC source is running. */ - gc?: GcInterval; - utilization?: number; - /** Whole seconds since process start. Portable, so always present. */ - uptimeS: number; - /** Each optional field is ABSENT (never zero) when its reader is not wired or cannot answer. */ - v8Heap?: V8HeapStats; - memoryLimit?: number; - availableMemory?: number; -} - -export interface ProcessStatsDeps { - memoryUsage?: () => ProcessStats['memory']; - cpuUsage?: () => { user: number; system: number }; - systemMemory?: () => { total: number; free: number }; - cpuCount?: () => number; - monotonicNowMs?: () => number; - /** Lazily started on activation, stopped on deactivation. Default: none (lag omitted). */ - eventLoop?: EventLoopSource; - /** Lazily started on activation, stopped on deactivation. Default: none (gc omitted). */ - gc?: GcSource; - /** ELU delta 0..1 per call, or undefined when unavailable. Default: none. */ - eventLoopUtilization?: () => number | undefined; - /** Seconds since process start (fractions floored). Default `process.uptime()`. */ - uptime?: () => number; - /** Optional readers; each answers undefined when the runtime cannot give a true value. Default: none. */ - v8Heap?: () => V8HeapStats | undefined; - memoryLimit?: () => number | undefined; - availableMemory?: () => number | undefined; - scheduler?: Scheduler; - intervalMs?: number; - onError?: (error: unknown) => void; -} - -// Unref'd so the tracker never keeps a process alive. -const defaultScheduler: Scheduler = { - setInterval: (cb, ms) => { - const h = setInterval(cb, ms); - (h as { unref?: () => void }).unref?.(); - return h; - }, - clearInterval: (h) => clearInterval(h as ReturnType), -}; - -interface ResolvedDeps { - memoryUsage: () => ProcessStats['memory']; - cpuUsage: () => { user: number; system: number }; - systemMemory: () => { total: number; free: number }; - cpuCount: () => number; - monotonicNowMs: () => number; - uptime: () => number; - scheduler: Scheduler; - intervalMs: number; -} - -export class ProcessStatsTracker extends InterceptorBase<{ stats: ProcessStats }> { - readonly name = 'node-process-stats'; - readonly #d: ResolvedDeps; - readonly #eventLoop: EventLoopSource | undefined; - readonly #gc: GcSource | undefined; - readonly #eventLoopUtilization: (() => number | undefined) | undefined; - readonly #onError: ((error: unknown) => void) | undefined; - readonly #v8Heap: (() => V8HeapStats | undefined) | undefined; - readonly #memoryLimit: (() => number | undefined) | undefined; - readonly #availableMemory: (() => number | undefined) | undefined; - #timer: unknown = null; - #eventLoopRunning = false; - #gcRunning = false; - #lastCpu = { user: 0, system: 0 }; - #lastWallMs = 0; - #cached: ProcessStats | undefined; - #activationFailed = false; - - constructor(deps: ProcessStatsDeps = {}) { - super(deps.onError); - // Per-field `??` (not a spread): an explicit `undefined` must fall back to the default. - this.#d = { - memoryUsage: deps.memoryUsage ?? (() => process.memoryUsage()), - cpuUsage: deps.cpuUsage ?? (() => process.cpuUsage()), - systemMemory: deps.systemMemory ?? (() => ({ total: totalmem(), free: freemem() })), - cpuCount: deps.cpuCount ?? (() => cpus().length), - monotonicNowMs: deps.monotonicNowMs ?? (() => performance.now()), - uptime: deps.uptime ?? (() => process.uptime()), - scheduler: deps.scheduler ?? defaultScheduler, - intervalMs: deps.intervalMs ?? 1000, - }; - this.#eventLoop = deps.eventLoop; - this.#gc = deps.gc; - this.#eventLoopUtilization = deps.eventLoopUtilization; - this.#onError = deps.onError; - this.#v8Heap = deps.v8Heap; - this.#memoryLimit = deps.memoryLimit; - this.#availableMemory = deps.availableMemory; - } - - /** - * Latest stats (read once on activation, then replaced on every poll). Safe for many callers. If the - * activation failed, this RETRIES it first (a failure propagates) so a producer never takes a baseline - * from a tracker that has no timer and would otherwise stay silent until every subscriber left. - */ - current(): ProcessStats { - if (this.#activationFailed) { - this.#activate(); - this.#activationFailed = false; - } - this.#cached ??= this.#read(); - return this.#cached; - } - - // Guarded: InterceptorBase marks the tracker active (and the subscriber is already registered) BEFORE - // this runs, so a throw escaping here would leave an "active" tracker with no timer and leak the - // subscribing producer's listener. A failure is reported, everything started is unwound, and the - // failure is remembered so the next current() retries (deactivation clears it; the next activation - // retries too). - protected onActivate(): void { - try { - this.#activate(); - } catch (error) { - this.#activationFailed = true; - this.#onError?.(error); - } - } - - // Starts everything or unwinds what it started and rethrows. - #activate(): void { - try { - this.#lastCpu = this.#d.cpuUsage(); - this.#lastWallMs = this.#d.monotonicNowMs(); - this.#cached = undefined; - if (this.#eventLoop !== undefined) { - this.#eventLoop.start(); - this.#eventLoopRunning = true; - } - if (this.#gc !== undefined) { - this.#gc.start(); - this.#gcRunning = true; - } - this.#timer = this.#d.scheduler.setInterval(() => this.#poll(), this.#d.intervalMs); - } catch (error) { - this.#stopSources(); // best-effort unwind; the original failure is the one thrown - throw error; - } - } - - /** Stops each source only if this activation started it; one failing stop() must not strand the other. */ - #stopSources(): void { - const eventLoop = this.#eventLoopRunning ? this.#eventLoop : undefined; - const gc = this.#gcRunning ? this.#gc : undefined; - this.#eventLoopRunning = false; - this.#gcRunning = false; - for (const source of [eventLoop, gc]) { - try { - source?.stop(); - } catch (error) { - try { - this.#onError?.(error); // reported, never thrown: one failing stop must not strand the other - } catch { - /* a failing reporter must not stop the remaining source either */ - } - } - } - } - - protected override onDeactivate(): void { - if (this.#timer !== null) this.#d.scheduler.clearInterval(this.#timer); // none after a failed activation - this.#timer = null; - this.#stopSources(); - this.#cached = undefined; - this.#activationFailed = false; - } - - #poll(): void { - let stats: ProcessStats; - try { - stats = this.#read(); - } catch (error) { - this.#onError?.(error); - return; - } - this.#cached = stats; - this.emit('stats', stats); - } - - #read(): ProcessStats { - // Read before any baseline moves: a throw here fails the whole poll, and must not advance the CPU window. - const uptimeS = Math.floor(this.#d.uptime()); - const memory = this.#d.memoryUsage(); - const systemMemory = this.#d.systemMemory(); - const cpu = this.#d.cpuUsage(); - const nowMs = this.#d.monotonicNowMs(); - const userDelta = cpu.user - this.#lastCpu.user; - const systemDelta = cpu.system - this.#lastCpu.system; - const wallMsDelta = nowMs - this.#lastWallMs; - this.#lastCpu = cpu; - this.#lastWallMs = nowMs; - // Normalized process CPU %: busy-Β΅s / wall-Β΅s / cores * 100. Guard the zero-window first sample. - const processPct = - wallMsDelta > 0 - ? ((userDelta + systemDelta) / (wallMsDelta * 1000) / this.#d.cpuCount()) * 100 - : 0; - const eventLoop = this.#eventLoop?.read(); - const utilization = this.#eventLoopUtilization?.(); - const v8Heap = this.#optional(this.#v8Heap); - const memoryLimit = this.#optional(this.#memoryLimit); - const availableMemory = this.#optional(this.#availableMemory); - // Read LAST: it drains the interval, so nothing that can still fail the poll may run after it. - const gc = this.#optional(() => this.#gc?.read()); - return { - memory, - systemMemory, - cpu: { userDelta, systemDelta, processPct }, - ...(eventLoop !== undefined ? { eventLoop } : {}), - ...(gc !== undefined ? { gc } : {}), - ...(utilization !== undefined ? { utilization } : {}), - uptimeS, - ...(v8Heap !== undefined ? { v8Heap } : {}), - ...(memoryLimit !== undefined ? { memoryLimit } : {}), - ...(availableMemory !== undefined ? { availableMemory } : {}), - }; - } - - /** An optional reader failing drops only its own field: it must not take the memory/cpu row with it. */ - #optional(read: (() => T | undefined) | undefined): T | undefined { - try { - return read?.(); - } catch (error) { - this.#onError?.(error); - return undefined; - } - } -} diff --git a/packages/trackers/README.md b/packages/trackers/README.md index b04805a4..69acfffb 100644 --- a/packages/trackers/README.md +++ b/packages/trackers/README.md @@ -22,7 +22,9 @@ Trackers are the abstraction over system and runtime APIs. The package root is r - `@bugsee/trackers/node` (`src/node/`) - `@bugsee/trackers/electron` (`src/electron/`) -The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, `resetApplicationTracker`), the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`), the `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; stages `heap`, `mainThreadLag` (timer drift), `idle` (`requestIdleCallback`), `userIdle` (Idle Detection) and `uptime`, each armed only while it has listeners; the SDK never prompts, so `userIdle` runs only when the `idle-detection` permission is already granted; the SDK's `user_idle_state` trace additionally needs the browser/WebView launch option `captureUserIdle: true`, because a page's own grant is not consent to record and upload idle/locked state), the UI/display `UiTracker` (`uiTrackerFor`, `resetUiTracker`: orientation, screenSize, viewport, colorScheme, reducedMotion, displayMode, frameRate), the `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; an approximate origin quota estimate, not device free space: browsers may pad `usage`, and `quota` can roughly reveal the device's disk size, so treat it as potentially identifying), the `EnvironmentTracker` (`environmentTrackerFor`, `resetEnvironmentTracker`; language, time zone, and, only when a consumer sets `observeHints` / `queryPermissions`, environment hints and Permissions API states queried without ever prompting; the private-browsing heuristic runs when `detectPrivateMode` is set (the browser launch sets it by default; opt out with `captureEnvironmentHints: false`) and is never reported as a certainty) and `hostRead`; `./node` and `./electron` are reserved in `exports` and currently export nothing. Its API is internal and may change between releases. +The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, `resetApplicationTracker`), the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`), the `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; stages `heap`, `mainThreadLag` (timer drift), `idle` (`requestIdleCallback`), `userIdle` (Idle Detection) and `uptime`, each armed only while it has listeners; the SDK never prompts, so `userIdle` runs only when the `idle-detection` permission is already granted; the SDK's `user_idle_state` trace additionally needs the browser/WebView launch option `captureUserIdle: true`, because a page's own grant is not consent to record and upload idle/locked state), the UI/display `UiTracker` (`uiTrackerFor`, `resetUiTracker`: orientation, screenSize, viewport, colorScheme, reducedMotion, displayMode, frameRate), the `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; an approximate origin quota estimate, not device free space: browsers may pad `usage`, and `quota` can roughly reveal the device's disk size, so treat it as potentially identifying), the `EnvironmentTracker` (`environmentTrackerFor`, `resetEnvironmentTracker`; language, time zone, and, only when a consumer sets `observeHints` / `queryPermissions`, environment hints and Permissions API states queried without ever prompting; the private-browsing heuristic runs when `detectPrivateMode` is set (the browser launch sets it by default; opt out with `captureEnvironmentHints: false`) and is never reported as a certainty) and `hostRead`; `./electron` is reserved in `exports` and currently exports nothing. Its API is internal and may change between releases. + +The `./node` entry is shared by Node, Bun and Deno and exports the process `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; a per-process singleton, keyed on the `process` object by default). Its ten stages (`memory`, `systemMemory`, `cpu`, `eventLoop`, `utilization`, `gc`, `v8Heap`, `memoryLimit`, `availableMemory`, `uptime`) are each armed only while they have listeners, behind one shared sampling timer. A stage the runtime cannot honestly measure emits nothing rather than zero (event-loop utilization on Bun/Deno, the event-loop delay histogram on Deno, the GC observer on Bun/Deno, the V8 heap on Bun), controlled by the `measures*` flags the platform packages pass in. It also exports the guarded runtime sources it is built from (`createGuardedEventLoopSource`, `createGuardedElu`, `createGcSource`, `createV8HeapReader`, `createMemoryLimitReader`, `createAvailableMemoryReader`). ## Links diff --git a/packages/trackers/package.json b/packages/trackers/package.json index 92079302..222c0ab5 100644 --- a/packages/trackers/package.json +++ b/packages/trackers/package.json @@ -7,7 +7,7 @@ "url": "git+https://github.com/bugsee/bugsee-javascript.git", "directory": "packages/trackers" }, - "description": "Domain-tracker foundation: multi-key emitter, InterceptorBase and the per-window tracker registry, with a ./browser entry (ApplicationTracker, ConnectivityTracker, PowerTracker, ProcessTracker, StorageTracker, UiTracker, EnvironmentTracker, hostRead) and reserved ./node and ./electron platform entries", + "description": "Domain-tracker foundation: multi-key emitter, InterceptorBase and the per-window tracker registry, with a ./browser entry (ApplicationTracker, ConnectivityTracker, PowerTracker, ProcessTracker, StorageTracker, UiTracker, EnvironmentTracker, hostRead), a ./node entry shared by Node, Bun and Deno (ProcessTracker and its guarded runtime sources) and a reserved ./electron platform entry", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", @@ -35,10 +35,13 @@ "sideEffects": false, "scripts": { "build": "tsup", - "typecheck": "tsc --noEmit", + "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.portable.json", "test": "vitest run", "test:coverage": "vitest run --coverage" }, + "devDependencies": { + "@types/node": "^22.20.5" + }, "publishConfig": { "main": "./dist/index.cjs", "module": "./dist/index.js", diff --git a/packages/trackers/src/index.test.ts b/packages/trackers/src/index.test.ts index b34bac5f..a42997cd 100644 --- a/packages/trackers/src/index.test.ts +++ b/packages/trackers/src/index.test.ts @@ -11,10 +11,8 @@ describe('@bugsee/trackers public surface', () => { ]); }); - it('reserves the node and electron entries as empty placeholders', async () => { - for (const entry of ['./node/index', './electron/index']) { - expect(Object.keys(await import(entry))).toEqual([]); - } + it('reserves the electron entry as an empty placeholder', async () => { + expect(Object.keys(await import('./electron/index'))).toEqual([]); }); it('exports the browser tracker values from ./browser', async () => { diff --git a/packages/node/src/trackers/gc-observer.test.ts b/packages/trackers/src/node/gc-observer.test.ts similarity index 100% rename from packages/node/src/trackers/gc-observer.test.ts rename to packages/trackers/src/node/gc-observer.test.ts diff --git a/packages/node/src/trackers/gc-observer.ts b/packages/trackers/src/node/gc-observer.ts similarity index 100% rename from packages/node/src/trackers/gc-observer.ts rename to packages/trackers/src/node/gc-observer.ts diff --git a/packages/node/src/trackers/guarded-event-loop.test.ts b/packages/trackers/src/node/guarded-event-loop.test.ts similarity index 100% rename from packages/node/src/trackers/guarded-event-loop.test.ts rename to packages/trackers/src/node/guarded-event-loop.test.ts diff --git a/packages/node/src/trackers/guarded-event-loop.ts b/packages/trackers/src/node/guarded-event-loop.ts similarity index 95% rename from packages/node/src/trackers/guarded-event-loop.ts rename to packages/trackers/src/node/guarded-event-loop.ts index fd1cb124..6df5683b 100644 --- a/packages/node/src/trackers/guarded-event-loop.ts +++ b/packages/trackers/src/node/guarded-event-loop.ts @@ -1,10 +1,16 @@ import { monitorEventLoopDelay, performance } from 'node:perf_hooks'; -import type { EventLoopSource } from './process-stats-tracker'; // Guarded, LAZY event-loop sources for node-family runtimes with PARTIAL perf_hooks (Bun, Deno). Nothing is // constructed or enabled until start(): a source that is never started costs nothing, and a runtime whose // monitorEventLoopDelay throws degrades to "lag omitted" rather than aborting SDK startup. +export interface EventLoopSource { + /** Mean/max/p99 lag (ms) since the previous read, or undefined when the runtime cannot measure it. */ + read(): { meanMs: number; maxMs: number; p99Ms: number } | undefined; + start(): void; + stop(): void; +} + /** The slice of an event-loop-delay histogram the lag metrics read. */ export interface DelayHistogram { enable(): void; diff --git a/packages/trackers/src/node/index.test.ts b/packages/trackers/src/node/index.test.ts new file mode 100644 index 00000000..925fe5c4 --- /dev/null +++ b/packages/trackers/src/node/index.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest'; +import * as nodeEntry from './index'; + +// Kept beside the entry (not in ../index.test.ts): the portable typecheck program must never reach src/node. +describe('@bugsee/trackers/node public surface', () => { + it('exports the node tracker values', () => { + expect(Object.keys(nodeEntry).sort()).toEqual([ + 'ProcessTracker', + 'createAvailableMemoryReader', + 'createGcSource', + 'createGuardedElu', + 'createGuardedEventLoopSource', + 'createMemoryLimitReader', + 'createV8HeapReader', + 'eluUnavailable', + 'processTrackerFor', + 'realPerfHooks', + 'resetProcessTracker', + ]); + }); +}); diff --git a/packages/trackers/src/node/index.ts b/packages/trackers/src/node/index.ts index 1779d816..522cb183 100644 --- a/packages/trackers/src/node/index.ts +++ b/packages/trackers/src/node/index.ts @@ -1,5 +1,36 @@ -// Reserved `@bugsee/trackers/node` entry. Platform tracker implementations that need node:* APIs live -// under src/node/ and are exported from here; nothing is implemented yet, so this entry is a documented -// placeholder. Keeping the subpath in package.json `exports` now means later slices add files WITHOUT -// changing the package contract. The portable root entry must never import from this directory. -export {}; +// `@bugsee/trackers/node` entry. Platform tracker implementations that need node:* APIs (shared by Node, Bun and +// Deno, which expose a node-compatible surface) live under src/node/ and are exported from here. The portable root +// entry and the browser entry must never import from this directory. +export { + createGcSource, + type GcEntry, + type GcInterval, + type GcSource, + type ObserverCtor, +} from './gc-observer'; +export { + createGuardedElu, + createGuardedEventLoopSource, + type DelayHistogram, + type Elu, + type EventLoopSource, + eluUnavailable, + type PerfHooks, + realPerfHooks, +} from './guarded-event-loop'; +export { + type ProcessEnv, + type ProcessEvents, + type ProcessMemory, + type ProcessTimers, + ProcessTracker, + type ProcessTrackerEnv, + processTrackerFor, + resetProcessTracker, +} from './process-tracker'; +export { + createAvailableMemoryReader, + createMemoryLimitReader, + createV8HeapReader, + type V8HeapStats, +} from './runtime-readers'; diff --git a/packages/trackers/src/node/process-tracker.test.ts b/packages/trackers/src/node/process-tracker.test.ts new file mode 100644 index 00000000..df860d57 --- /dev/null +++ b/packages/trackers/src/node/process-tracker.test.ts @@ -0,0 +1,939 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + type EventLoopSource, + type GcSource, + type ProcessEnv, + type ProcessEvents, + ProcessTracker, + processTrackerFor, + resetProcessTracker, +} from './index'; + +// Every handle is unique, and clearInterval must be handed exactly a live handle setInterval returned, +// so clearing `undefined`/`null` (a handle dropped too early) or the same handle twice fails the test. +function fakeScheduler() { + const callbacks: (() => void)[] = []; + const live = new Set(); + let cleared = 0; + const scheduler = { + setInterval: (cb: () => void) => { + callbacks.push(cb); + const handle = { id: callbacks.length }; + live.add(handle); + return handle; + }, + clearInterval: (h: unknown) => { + expect(live.has(h), 'clearInterval was not given a live handle').toBe(true); + live.delete(h); + cleared += 1; + }, + }; + return { + scheduler, + tick: () => callbacks.at(-1)?.(), + /** A callback from an EARLIER arming (a timer whose clear failed or that the host fired late). */ + callbackAt: (i: number) => callbacks[i], + sets: () => callbacks.length, + cleared: () => cleared, + live: () => live.size, + }; +} + +const mem = { rss: 1, heapTotal: 2, heapUsed: 3, external: 4, arrayBuffers: 5 }; + +function source(label: string, log: string[], read?: () => T) { + return { + start: () => void log.push(`${label}.start`), + stop: () => void log.push(`${label}.stop`), + read: (read ?? (() => undefined)) as () => T | undefined, + }; +} + +function mk(over: ProcessEnv = {}, onError?: (e: unknown) => void) { + let cpu = { user: 0, system: 0 }; + let wall = 0; + const fs = fakeScheduler(); + const tracker = new ProcessTracker( + { + memoryUsage: () => mem, + systemMemory: () => ({ total: 100, free: 40 }), + cpuUsage: () => cpu, + cpuCount: () => 2, + monotonicNowMs: () => wall, + uptime: () => 12.9, + // gated off by default so a test only sees the stages it wires + measuresEventLoopDelay: false, + measuresGc: false, + measuresV8Heap: false, + measuresAvailableMemory: false, + eventLoopUtilization: () => undefined, + memoryLimit: () => undefined, + scheduler: fs.scheduler, + ...over, + }, + onError, + ); + return { + tracker, + fs, + advance: (c: { user: number; system: number }, w: number) => { + cpu = c; + wall = w; + }, + }; +} + +function collect(tracker: ProcessTracker) { + const got: [string, unknown][] = []; + const off = tracker.onAny((name, payload) => void got.push([name, payload])); + return { got, off }; +} + +describe('ProcessTracker', () => { + it('attaches NOTHING at construction or on explicit start()/stop() (activation is per stage)', () => { + const log: string[] = []; + const { tracker, fs } = mk({ eventLoop: source('loop', log), gc: source('gc', log) }); + tracker.start(); + tracker.stop(); + expect(fs.sets()).toBe(0); + expect(log).toEqual([]); + }); + + describe('per-stage activation', () => { + it('arms only the sources of the stages that have a listener, behind ONE shared timer', () => { + const log: string[] = []; + const { tracker, fs } = mk({ eventLoop: source('loop', log), gc: source('gc', log) }); + const offMemory = tracker.on('memory', () => {}); + expect(fs.sets()).toBe(1); + expect(log).toEqual([]); // a memory subscriber starts neither the histogram nor the GC observer + const offGc = tracker.on('gc', () => {}); + expect(log).toEqual(['gc.start']); + expect(fs.sets()).toBe(1); + const offLoop = tracker.on('eventLoop', () => {}); + expect(log).toEqual(['gc.start', 'loop.start']); + offGc(); + expect(log).toEqual(['gc.start', 'loop.start', 'gc.stop']); + expect(fs.cleared()).toBe(0); // still wanted by memory + eventLoop + offMemory(); + offLoop(); + expect(log).toEqual(['gc.start', 'loop.start', 'gc.stop', 'loop.stop']); + expect(fs.cleared()).toBe(1); + expect(fs.live()).toBe(0); + }); + + it('an onAny listener arms every stage', () => { + const log: string[] = []; + const { tracker } = mk({ eventLoop: source('loop', log), gc: source('gc', log) }); + const { off } = collect(tracker); + expect(log).toEqual(['loop.start', 'gc.start']); + off(); + expect(log).toEqual(['loop.start', 'gc.start', 'loop.stop', 'gc.stop']); + }); + + it('restart re-arms and starts every windowed stage FRESH (no retained sample)', () => { + const log: string[] = []; + let n = 0; + const { tracker } = mk({ + eventLoop: source('loop', log, () => ({ meanMs: ++n, maxMs: 0, p99Ms: 0 })), + }); + const off = tracker.on('eventLoop', () => {}); + tracker.on('eventLoop', () => {})(); + expect(tracker.current('eventLoop')).toBeUndefined(); // armed, nothing ticked yet + off(); + expect(tracker.current('eventLoop')).toBeUndefined(); + tracker.on('eventLoop', () => {}); + expect(log).toEqual(['loop.start', 'loop.stop', 'loop.start']); + expect(tracker.current('eventLoop')).toBeUndefined(); + }); + }); + + describe('ticks', () => { + it('emits every stage with exact values; cpu deltas are normalised by cores over the wall window', () => { + const { tracker, fs, advance } = mk({ + eventLoop: source('loop', [], () => ({ meanMs: 1, maxMs: 2, p99Ms: 3 })), + gc: source('gc', [], () => ({ count: 3, pauseMs: 12.5, maxPauseMs: 8 })), + eventLoopUtilization: () => 0.5, + v8Heap: () => ({ limit: 10, used: 4, available: 6, malloced: 1, peakMalloced: 2 }), + memoryLimit: () => 500, + availableMemory: () => 250, + }); + const { got } = collect(tracker); + advance({ user: 100_000, system: 50_000 }, 1000); + fs.tick(); + expect(got).toEqual([ + ['memory', mem], + ['systemMemory', { total: 100, free: 40 }], + // (100 000 + 50 000) Β΅s busy / (1 000 ms * 1 000) Β΅s wall / 2 cores * 100 = 7.5 % + ['cpu', { userDelta: 100_000, systemDelta: 50_000, processPct: 7.5 }], + ['eventLoop', { meanMs: 1, maxMs: 2, p99Ms: 3 }], + ['utilization', { utilization: 0.5 }], + ['v8Heap', { limit: 10, used: 4, available: 6, malloced: 1, peakMalloced: 2 }], + ['memoryLimit', { bytes: 500 }], + ['availableMemory', { bytes: 250 }], + ['uptime', { seconds: 12 }], + ['gc', { count: 3, pauseMs: 12.5, maxPauseMs: 8 }], + ]); + }); + + it('a zero wall window yields processPct 0 (no divide by zero)', () => { + const { tracker, fs, advance } = mk(); + const { got } = collect(tracker); + advance({ user: 500, system: 500 }, 0); + fs.tick(); + expect(got.find(([n]) => n === 'cpu')?.[1]).toEqual({ + userDelta: 500, + systemDelta: 500, + processPct: 0, + }); + }); + + it('the cpu window moves on every tick (each tick covers only its own interval)', () => { + const { tracker, fs, advance } = mk(); + const cpu: unknown[] = []; + tracker.on('cpu', (c) => void cpu.push(c)); + advance({ user: 100_000, system: 0 }, 1000); + fs.tick(); + advance({ user: 300_000, system: 0 }, 3000); + fs.tick(); + expect(cpu).toEqual([ + { userDelta: 100_000, systemDelta: 0, processPct: 5 }, + { userDelta: 200_000, systemDelta: 0, processPct: 5 }, + ]); + }); + + it('a stage that cannot answer emits NOTHING (absence, never zero)', () => { + const { tracker, fs } = mk({ + eventLoop: source('loop', [], () => undefined), + gc: source('gc', [], () => undefined), + v8Heap: () => undefined, + availableMemory: () => undefined, + }); + const { got } = collect(tracker); + fs.tick(); + expect(got.map(([n]) => n)).toEqual(['memory', 'systemMemory', 'cpu', 'uptime']); + }); + + it('emitted payloads are copies: a subscriber cannot corrupt the retained cpu sample', () => { + const { tracker, fs, advance } = mk(); + tracker.on('cpu', (c) => { + c.userDelta = -1; + }); + advance({ user: 10, system: 0 }, 1000); + fs.tick(); + expect(tracker.current('cpu')?.userDelta).toBe(10); + }); + + it('a listener that unsubscribes a later stage mid-tick: that stage is not read', () => { + const log: string[] = []; + const { tracker, fs } = mk({ + eventLoop: source('loop', log, () => ({ meanMs: 1, maxMs: 1, p99Ms: 1 })), + }); + const seen: string[] = []; + let offLoop: () => void = () => {}; + tracker.on('memory', () => { + seen.push('memory'); + offLoop(); + }); + offLoop = tracker.on('eventLoop', () => void seen.push('eventLoop')); + fs.tick(); + expect(seen).toEqual(['memory']); + expect(log).toEqual(['loop.start', 'loop.stop']); + }); + + it('a stale timer callback (an earlier arming) never emits', () => { + const { tracker, fs } = mk(); + const { got, off } = collect(tracker); + off(); // timer cleared, generation moved on + const stale = fs.callbackAt(0); + got.length = 0; + stale?.(); + expect(got).toEqual([]); + tracker.on('memory', () => void got.push(['memory', null])); + stale?.(); // still the OLD run, though a new timer is armed + expect(got).toEqual([]); + fs.tick(); + expect(got).toEqual([['memory', null]]); + }); + }); + + describe('current()', () => { + it('cpu is seeded with a zero-length window when it arms, then follows the ticks; undefined unarmed', () => { + const { tracker, fs, advance } = mk(); + expect(tracker.current('cpu')).toBeUndefined(); + const off = tracker.on('cpu', () => {}); + expect(tracker.current('cpu')).toEqual({ userDelta: 0, systemDelta: 0, processPct: 0 }); + advance({ user: 10, system: 20 }, 1000); + fs.tick(); + expect(tracker.current('cpu')).toEqual({ + userDelta: 10, + systemDelta: 20, + processPct: 0.0015, + }); + off(); + expect(tracker.current('cpu')).toBeUndefined(); + tracker.on('cpu', () => {}); + expect(tracker.current('cpu')).toEqual({ userDelta: 0, systemDelta: 0, processPct: 0 }); + }); + + it('windowed stages answer the last emitted sample of this run', () => { + let reads = 0; + const { tracker, fs } = mk({ + gc: source('gc', [], () => ({ count: ++reads, pauseMs: 0, maxPauseMs: 0 })), + eventLoopUtilization: () => 0.25, + }); + tracker.on('gc', () => {}); + tracker.on('utilization', () => {}); + expect(tracker.current('gc')).toBeUndefined(); + fs.tick(); + expect(tracker.current('gc')).toEqual({ count: 1, pauseMs: 0, maxPauseMs: 0 }); + expect(tracker.current('utilization')).toEqual({ utilization: 0.25 }); + expect(reads).toBe(1); // reading the sample did not consume another window + }); + + it('stateless stages read LIVE, armed or not, and hand out copies', () => { + const { tracker } = mk({ uptime: () => 7.9 }); + expect(tracker.current('uptime')).toEqual({ seconds: 7 }); + expect(tracker.current('memory')).toEqual(mem); + const m = tracker.current('memory'); + if (m) m.rss = 99; + expect(tracker.current('memory')?.rss).toBe(1); + tracker.on('uptime', () => {}); + expect(tracker.current('uptime')).toEqual({ seconds: 7 }); + }); + + it('is undefined for a stage with no reader or no answer', () => { + const { tracker } = mk({ v8Heap: () => undefined }); + expect(tracker.current('v8Heap')).toBeUndefined(); + expect(tracker.current('memoryLimit')).toBeUndefined(); + expect(tracker.current('availableMemory')).toBeUndefined(); // gated off, nothing wired + }); + + it('a throwing live read is reported and answers undefined', () => { + const errors: unknown[] = []; + const boom = new Error('boom'); + const { tracker } = mk( + { + memoryUsage: () => { + throw boom; + }, + }, + (e) => void errors.push(e), + ); + expect(tracker.current('memory')).toBeUndefined(); + expect(errors).toEqual([boom]); + }); + }); + + describe('honest defaults and runtime gates', () => { + it('without injected sources the real node readers answer (uptime, memory, system memory, heap, limit)', () => { + const tracker = new ProcessTracker({ scheduler: fakeScheduler().scheduler }); + expect(tracker.current('memory')?.rss).toBeGreaterThan(0); + expect(tracker.current('systemMemory')?.total).toBeGreaterThan(0); + expect(Number.isInteger(tracker.current('uptime')?.seconds)).toBe(true); + expect(tracker.current('v8Heap')?.limit).toBeGreaterThan(0); + // a real cap only: undefined on an unconstrained host, a positive number inside a cgroup + const cap = tracker.current('memoryLimit'); + if (cap !== undefined) expect(cap.bytes).toBeGreaterThan(0); + const avail = tracker.current('availableMemory'); + if (avail !== undefined) expect(avail.bytes).toBeGreaterThanOrEqual(0); + }); + + it('real cpu defaults: the first tick reports finite deltas and a percentage', () => { + const fs = fakeScheduler(); + const tracker = new ProcessTracker({ scheduler: fs.scheduler }); + const cpu: ProcessEvents['cpu'][] = []; + tracker.on('cpu', (c) => void cpu.push(c)); + for (let i = 0; i < 2e5; i += 1) Math.sqrt(i); + fs.tick(); + expect(cpu).toHaveLength(1); + expect(Number.isFinite(cpu[0]?.processPct)).toBe(true); + expect(cpu[0]?.userDelta).toBeGreaterThanOrEqual(0); + }); + + it('measuresEventLoopDelay:false never constructs a histogram; an injected source still wins', () => { + const monitor = vi.fn(); + const perfHooks = { + monitorEventLoopDelay: monitor, + eventLoopUtilization: () => ({ utilization: 0 }), + }; + const gated = mk({ perfHooks, measuresEventLoopDelay: false }); + gated.tracker.on('eventLoop', () => {}); + gated.fs.tick(); + expect(monitor).not.toHaveBeenCalled(); + const log: string[] = []; + const injected = mk({ + perfHooks, + measuresEventLoopDelay: false, + eventLoop: source('loop', log, () => ({ meanMs: 1, maxMs: 1, p99Ms: 1 })), + }); + injected.tracker.on('eventLoop', () => {}); + expect(log).toEqual(['loop.start']); + }); + + it('the guarded histogram is built lazily, only when the stage arms, and reports real-shaped lag', () => { + const state = { monitor: 0, enabled: false }; + const histogram = { + count: 3, + enable: () => { + state.enabled = true; + }, + disable: () => { + state.enabled = false; + }, + reset: () => {}, + mean: 2e6, + max: 9e6, + percentile: () => 7e6, + }; + const { tracker, fs } = mk({ + measuresEventLoopDelay: undefined, + perfHooks: { + monitorEventLoopDelay: () => { + state.monitor += 1; + return histogram; + }, + eventLoopUtilization: () => ({ utilization: 0 }), + }, + }); + tracker.on('memory', () => {}); + expect(state.monitor).toBe(0); + const lag: unknown[] = []; + const off = tracker.on('eventLoop', (l) => void lag.push(l)); + expect(state.enabled).toBe(true); + fs.tick(); + expect(lag).toEqual([{ meanMs: 2, maxMs: 9, p99Ms: 7 }]); + off(); + expect(state.enabled).toBe(false); + }); + + it('measuresGc:false constructs no observer; the default wires the injected observer for gc entries', () => { + const ctor = vi.fn(); + const gated = mk({ performanceObserver: ctor as never, measuresGc: false }); + gated.tracker.on('gc', () => {}); + expect(ctor).not.toHaveBeenCalled(); + + const seen: string[][] = []; + let disconnected = 0; + class Observer { + observe(o: { entryTypes: string[] }) { + seen.push(o.entryTypes); + } + disconnect() { + disconnected += 1; + } + takeRecords() { + return [{ duration: 4 }]; + } + } + const { tracker, fs } = mk({ performanceObserver: Observer as never, measuresGc: undefined }); + const gc: unknown[] = []; + const off = tracker.on('gc', (g) => void gc.push(g)); + expect(seen).toEqual([['gc']]); + fs.tick(); + expect(gc).toEqual([{ count: 1, pauseMs: 4, maxPauseMs: 4 }]); + off(); + expect(disconnected).toBe(1); + }); + + it('measuresV8Heap:false wires no heap reader even where the runtime answers; an injected reader wins', () => { + const getter = mk({ measuresV8Heap: false }); + expect(getter.tracker.current('v8Heap')).toBeUndefined(); + const injected = mk({ + measuresV8Heap: false, + v8Heap: () => ({ limit: 1, used: 1, available: 1, malloced: 1, peakMalloced: 1 }), + }); + expect(injected.tracker.current('v8Heap')?.limit).toBe(1); + }); + + it('measuresAvailableMemory:false wires no reader; an injected reader wins', () => { + expect( + mk({ measuresAvailableMemory: false }).tracker.current('availableMemory'), + ).toBeUndefined(); + expect( + mk({ measuresAvailableMemory: false, availableMemory: () => 5 }).tracker.current( + 'availableMemory', + ), + ).toEqual({ bytes: 5 }); + }); + + it('guarded ELU: a fresh baseline per arming, and Bun/Deno-style flat zeros are omitted, never reported as 0%', () => { + let calls = 0; + const fs = fakeScheduler(); + const tracker = new ProcessTracker({ + scheduler: fs.scheduler, + eventLoopUtilization: undefined, + perfHooks: { + monitorEventLoopDelay: () => { + throw new Error('unused'); + }, + eventLoopUtilization: (() => { + calls += 1; + return { idle: 0, active: 0, utilization: 0 }; + }) as never, + }, + }); + const got: unknown[] = []; + const off = tracker.on('utilization', (u) => void got.push(u)); + expect(calls).toBe(1); // the baseline read at arming + fs.tick(); + expect(got).toEqual([]); + off(); + tracker.on('utilization', () => {}); + expect(calls).toBe(4); // 1 + (current + delta) on the tick, then a NEW baseline for the new run + }); + + it('guarded ELU reports a real delta', () => { + const fs = fakeScheduler(); + let t = 0; + const tracker = new ProcessTracker({ + scheduler: fs.scheduler, + perfHooks: { + monitorEventLoopDelay: () => { + throw new Error('unused'); + }, + eventLoopUtilization: (( + a?: { idle: number; active: number }, + b?: { idle: number; active: number }, + ) => { + if (a && b) { + const idle = a.idle - b.idle; + const active = a.active - b.active; + return { idle, active, utilization: active / (idle + active) }; + } + t += 1; + return { idle: 30 * t, active: 10 * t, utilization: 0.25 }; + }) as never, + }, + }); + const got: unknown[] = []; + tracker.on('utilization', (u) => void got.push(u)); + fs.tick(); + expect(got).toEqual([{ utilization: 0.25 }]); + }); + }); + + describe('failures', () => { + it('a throwing stage read is reported and drops ONLY that stage for the tick', () => { + const errors: unknown[] = []; + const boom = new Error('uptime'); + const { tracker, fs } = mk( + { + uptime: () => { + throw boom; + }, + }, + (e) => void errors.push(e), + ); + const { got } = collect(tracker); + fs.tick(); + expect(errors).toEqual([boom]); + expect(got.map(([n]) => n)).toEqual(['memory', 'systemMemory', 'cpu']); + fs.tick(); // the timer survives + expect(errors).toEqual([boom, boom]); + }); + + it('a throwing cpu read does not advance the cpu baseline: the next window covers the whole gap', () => { + let fail = true; + let user = 0; + let wall = 0; + const fs = fakeScheduler(); + const tracker = new ProcessTracker({ + cpuUsage: () => { + if (fail && user > 0) throw new Error('cpu'); + return { user, system: 0 }; + }, + monotonicNowMs: () => wall, + cpuCount: () => 1, + scheduler: fs.scheduler, + }); + const cpu: unknown[] = []; + tracker.on('cpu', (c) => void cpu.push(c)); + user = 1000; + wall = 1; + fs.tick(); // throws, swallowed (no reporter) + fail = false; + user = 3000; + wall = 3; + fs.tick(); + expect(cpu).toEqual([{ userDelta: 3000, systemDelta: 0, processPct: 100 }]); + }); + + it('a failing wall-clock read cannot advance the cpu window either', () => { + let wallFails = false; + let user = 0; + let wall = 0; + const fs = fakeScheduler(); + const tracker = new ProcessTracker({ + cpuUsage: () => ({ user, system: 0 }), + monotonicNowMs: () => { + if (wallFails) throw new Error('wall'); + return wall; + }, + cpuCount: () => 1, + scheduler: fs.scheduler, + }); + const cpu: ProcessEvents['cpu'][] = []; + tracker.on('cpu', (c) => void cpu.push(c)); + user = 1000; + wall = 1; + wallFails = true; + fs.tick(); + wallFails = false; + fs.tick(); + expect(cpu).toEqual([{ userDelta: 1000, systemDelta: 0, processPct: 100 }]); + }); + + it('a source whose start() throws is reported and left UNARMED (never stopped); a later listener change retries', () => { + const errors: unknown[] = []; + const log: string[] = []; + let fail = true; + const flaky: EventLoopSource = { + start: () => { + log.push('start'); + if (fail) throw new Error('refused'); + }, + stop: () => void log.push('stop'), + read: () => ({ meanMs: 1, maxMs: 1, p99Ms: 1 }), + }; + const { tracker, fs } = mk({ eventLoop: flaky }, (e) => void errors.push(e)); + const lag: unknown[] = []; + const off = tracker.on('eventLoop', (l) => void lag.push(l)); + expect(errors).toHaveLength(1); + expect(fs.sets()).toBe(0); // nothing armed, so no timer either + off(); + expect(log).toEqual(['start']); // never stopped: it never started + fail = false; + tracker.on('eventLoop', (l) => void lag.push(l)); + fs.tick(); + expect(lag).toEqual([{ meanMs: 1, maxMs: 1, p99Ms: 1 }]); + }); + + it('a failing gc start is isolated from the other stages', () => { + const errors: unknown[] = []; + const gc: GcSource = { + start: () => { + throw new Error('gc'); + }, + stop: () => {}, + read: () => undefined, + }; + const { tracker, fs } = mk({ gc }, (e) => void errors.push(e)); + const mems: unknown[] = []; + tracker.on('memory', (m) => void mems.push(m)); + tracker.on('gc', () => {}); + expect(errors).toHaveLength(1); + fs.tick(); + expect(mems).toHaveLength(1); + }); + + it('one failing stop() is reported and does not strand another stage; a throwing reporter is swallowed', () => { + const log: string[] = []; + const bad = { + start: () => {}, + stop: () => { + log.push('loop.stop'); + throw new Error('stop'); + }, + read: () => undefined, + }; + const reporter = vi.fn(() => { + throw new Error('reporter'); + }); + const { tracker } = mk({ eventLoop: bad, gc: source('gc', log) }, reporter); + const { off } = collect(tracker); + expect(() => off()).not.toThrow(); + expect(log).toEqual(['gc.start', 'loop.stop', 'gc.stop']); + expect(reporter).toHaveBeenCalledTimes(1); + }); + + it('a scheduler that cannot arm the timer unwinds every stage armed for it, and a later change retries', () => { + const errors: unknown[] = []; + const log: string[] = []; + let fail = true; + const fs = fakeScheduler(); + const { tracker } = mk( + { + eventLoop: source('loop', log), + scheduler: { + setInterval: (cb) => { + if (fail) throw new Error('no timers'); + return fs.scheduler.setInterval(cb); + }, + clearInterval: fs.scheduler.clearInterval, + }, + }, + (e) => void errors.push(e), + ); + const off = tracker.on('eventLoop', () => {}); + expect(errors).toHaveLength(1); + expect(log).toEqual(['loop.start', 'loop.stop']); // not left running with nothing to read it + off(); + fail = false; + tracker.on('eventLoop', () => {}); + expect(fs.sets()).toBe(1); + expect(log).toEqual(['loop.start', 'loop.stop', 'loop.start']); + }); + + it('a throwing clearInterval is reported and does not leave the tracker armed', () => { + const errors: unknown[] = []; + const { tracker } = mk( + { + scheduler: { + setInterval: () => 'h', + clearInterval: () => { + throw new Error('clear'); + }, + }, + }, + (e) => void errors.push(e), + ); + const off = tracker.on('memory', () => {}); + off(); + expect(errors).toHaveLength(1); + }); + + it('errors are optional everywhere: no reporter, nothing throws', () => { + const { tracker, fs } = mk({ + uptime: () => { + throw new Error('x'); + }, + eventLoop: { + start: () => { + throw new Error('y'); + }, + stop: () => {}, + read: () => undefined, + }, + }); + expect(() => { + tracker.on('uptime', () => {}); + tracker.on('eventLoop', () => {}); + fs.tick(); + tracker.current('uptime'); + }).not.toThrow(); + }); + }); + + describe('rebind', () => { + it('merges: defined seams replace, undefined never clobber an earlier one', () => { + const { tracker, fs } = mk({ uptime: () => 5 }); + tracker.rebind({ uptime: undefined, memoryUsage: () => ({ ...mem, rss: 77 }) }); + expect(tracker.current('uptime')).toEqual({ seconds: 5 }); + expect(tracker.current('memory')?.rss).toBe(77); + expect(fs.sets()).toBe(0); + }); + + it('an unchanged rebind restarts nothing (a relaunch with the same seams keeps its windows)', () => { + const log: string[] = []; + const loop = source('loop', log); + const { tracker, fs } = mk({ eventLoop: loop }); + tracker.on('eventLoop', () => {}); + tracker.rebind({ eventLoop: loop, scheduler: fs.scheduler }); + expect(log).toEqual(['loop.start']); + expect(fs.sets()).toBe(1); + }); + + it('a changed seam on a RUNNING tracker tears down with the OLD seams, then re-arms on the new ones', () => { + const log: string[] = []; + const first = mk({ eventLoop: source('old', log) }); + const second = fakeScheduler(); + const got: unknown[] = []; + first.tracker.on('eventLoop', (l) => void got.push(l)); + first.tracker.rebind({ + eventLoop: source('new', log, () => ({ meanMs: 9, maxMs: 9, p99Ms: 9 })), + scheduler: second.scheduler, + }); + expect(log).toEqual(['old.start', 'old.stop', 'new.start']); + expect(first.fs.cleared()).toBe(1); // cleared on the scheduler that armed it + expect(first.fs.live()).toBe(0); + expect(second.sets()).toBe(1); + first.fs.callbackAt(0)?.(); // the old timer, fired late + expect(got).toEqual([]); + second.tick(); + expect(got).toEqual([{ meanMs: 9, maxMs: 9, p99Ms: 9 }]); + }); + + it('a changed gate re-resolves the sources: a gate flipped off drops the stage from then on', () => { + const seen: string[] = []; + let disconnected = 0; + class Observer { + observe() { + seen.push('observe'); + } + disconnect() { + disconnected += 1; + } + } + const { tracker, fs } = mk({ performanceObserver: Observer as never, measuresGc: undefined }); + const gc: unknown[] = []; + tracker.on('gc', (g) => void gc.push(g)); + expect(seen).toEqual(['observe']); + tracker.rebind({ measuresGc: false }); + expect(disconnected).toBe(1); + fs.tick(); + expect(gc).toEqual([]); + }); + + it('rebinding an idle tracker only swaps the seams', () => { + const { tracker, fs } = mk(); + tracker.rebind({ intervalMs: 50, scheduler: fs.scheduler }); + expect(fs.sets()).toBe(0); + const seen: number[] = []; + const timers = { + setInterval: (_cb: () => void, ms: number) => { + seen.push(ms); + return 'h'; + }, + clearInterval: () => {}, + }; + tracker.rebind({ scheduler: timers }); + tracker.on('memory', () => {}); + expect(seen).toEqual([50]); + }); + + it('the latest launch error reporter wins; undefined keeps it; a throwing reporter is swallowed', () => { + const first: unknown[] = []; + const second: unknown[] = []; + const { tracker } = mk({}, (e) => void first.push(e)); + const failing = { + memoryUsage: () => { + throw new Error('m'); + }, + }; + tracker.rebind(failing, (e) => void second.push(e)); + tracker.current('memory'); + expect(first).toEqual([]); + expect(second).toHaveLength(1); + tracker.rebind({}, undefined); + tracker.current('memory'); + expect(second).toHaveLength(2); + tracker.rebind({}, () => { + throw new Error('reporter'); + }); + expect(() => tracker.current('memory')).not.toThrow(); + }); + }); + + it('a throwing subscriber is reported, and a throwing reporter never escapes into the timer callback', () => { + const errors: unknown[] = []; + const a = mk({}, (e) => void errors.push(e)); + a.tracker.on('memory', () => { + throw new Error('listener'); + }); + a.fs.tick(); + expect(errors).toHaveLength(1); + const b = mk({}, () => { + throw new Error('reporter'); + }); + b.tracker.on('memory', () => { + throw new Error('listener'); + }); + expect(() => b.fs.tick()).not.toThrow(); + }); + + it('reset() drops every listener and releases the timer and sources', () => { + const log: string[] = []; + const { tracker, fs } = mk({ eventLoop: source('loop', log) }); + collect(tracker); + tracker.reset(); + expect(log).toEqual(['loop.start', 'loop.stop']); + expect(fs.live()).toBe(0); + tracker.on('memory', () => {}); + expect(fs.sets()).toBe(2); + }); + + describe('default scheduler', () => { + it('delivers real ticks, is unref’d, and is silent after the last unsubscribe', async () => { + const tracker = new ProcessTracker({ intervalMs: 5 }); + let n = 0; + const off = tracker.on('uptime', () => { + n += 1; + }); + await new Promise((r) => setTimeout(r, 60)); + expect(n).toBeGreaterThan(0); + off(); + const after = n; + await new Promise((r) => setTimeout(r, 30)); + expect(n).toBe(after); + }); + + it('a handle without unref() is tolerated', () => { + const real = globalThis.setInterval; + let ref: unknown; + globalThis.setInterval = ((cb: () => void, ms: number) => { + ref = { id: 1, cb, ms }; + return ref; + }) as never; + const realClear = globalThis.clearInterval; + let cleared: unknown; + globalThis.clearInterval = ((h: unknown) => { + cleared = h; + }) as never; + try { + const tracker = new ProcessTracker({}); + const off = tracker.on('memory', () => {}); + off(); + expect(cleared).toBe(ref); + } finally { + globalThis.setInterval = real; + globalThis.clearInterval = realClear; + } + }); + }); +}); + +describe('processTrackerFor (per-process singleton)', () => { + const key = {}; + const idle = (over: Partial = {}): ProcessEnv => ({ + scheduler: fakeScheduler().scheduler, + ...over, + }); + + it('returns ONE tracker per key, and a different one for another key', () => { + const a = processTrackerFor({ key, ...idle() }); + expect(processTrackerFor({ key, ...idle() })).toBe(a); + const other = {}; + expect(processTrackerFor({ key: other, ...idle() })).not.toBe(a); + resetProcessTracker(key); + resetProcessTracker(other); + }); + + it('defaults to the `process` object as the key', () => { + const a = processTrackerFor({ scheduler: fakeScheduler().scheduler }); + expect(processTrackerFor()).toBe(a); + resetProcessTracker(); + expect(processTrackerFor()).not.toBe(a); + resetProcessTracker(); + }); + + it('a second request rebinds the shared tracker (latest launch wins, merge never drops, onError replaced)', () => { + const first = fakeScheduler(); + const second = fakeScheduler(); + const errors: unknown[] = []; + const tracker = processTrackerFor({ key, scheduler: first.scheduler, uptime: () => 3 }); + tracker.on('uptime', () => {}); + expect(first.sets()).toBe(1); + const again = processTrackerFor( + { + key, + scheduler: second.scheduler, + memoryUsage: () => { + throw new Error('m'); + }, + }, + (e) => void errors.push(e), + ); + expect(again).toBe(tracker); + expect(first.live()).toBe(0); + expect(second.sets()).toBe(1); // re-armed on the latest launch's scheduler + expect(tracker.current('uptime')).toEqual({ seconds: 3 }); // earlier seam kept + tracker.current('memory'); + expect(errors).toHaveLength(1); + resetProcessTracker(key); + expect(second.live()).toBe(0); // reset released the timer + }); + + it('resetProcessTracker of an unknown key is a no-op', () => { + expect(() => resetProcessTracker({})).not.toThrow(); + }); +}); diff --git a/packages/trackers/src/node/process-tracker.ts b/packages/trackers/src/node/process-tracker.ts new file mode 100644 index 00000000..7868a5ee --- /dev/null +++ b/packages/trackers/src/node/process-tracker.ts @@ -0,0 +1,541 @@ +import { cpus, freemem, totalmem } from 'node:os'; +import { performance } from 'node:perf_hooks'; +import nodeProcess from 'node:process'; +import { getHeapStatistics } from 'node:v8'; +import { InterceptorBase } from '../interceptor-base'; +import { createTrackerRegistry } from '../tracker-registry'; +import { createGcSource, type GcInterval, type GcSource, type ObserverCtor } from './gc-observer'; +import { + createGuardedElu, + createGuardedEventLoopSource, + type EventLoopSource, + type PerfHooks, + realPerfHooks, +} from './guarded-event-loop'; +import { + createAvailableMemoryReader, + createMemoryLimitReader, + createV8HeapReader, + type V8HeapStats, +} from './runtime-readers'; + +// Node/Bun/Deno PROCESS tracker (domain tracker, design Β§15.2/Β§15.3; Android reference: BugseeTrackerProcess). It +// owns everything the runtime can say about its own process, as TEN independent stages: +// +// memory process.memoryUsage() -> { rss, heapTotal, heapUsed, external, arrayBuffers } +// systemMemory os.totalmem()/freemem() -> { total, free } +// cpu process.cpuUsage() deltas over the wall window -> { userDelta, systemDelta, processPct } +// eventLoop monitorEventLoopDelay histogram (guarded) -> { meanMs, maxMs, p99Ms } +// utilization performance.eventLoopUtilization() (guarded) -> { utilization } +// gc PerformanceObserver('gc') interval -> { count, pauseMs, maxPauseMs } +// v8Heap v8.getHeapStatistics() -> { limit, used, available, malloced, peakMalloced } +// memoryLimit process.constrainedMemory() (a real cap only) -> { bytes } +// availableMemory process.availableMemory() -> { bytes } +// uptime process.uptime(), whole seconds -> { seconds } +// +// PER-STAGE ACTIVATION. Nothing runs at construction. ONE shared sampling timer exists only while some stage has a +// listener (`listenerCount`, re-evaluated after every listener mutation via `onListenersChanged`; an `onAny` listener +// counts for every stage), and each stage's own machinery exists only while THAT stage is wanted: the GC observer +// only for `gc`, the histogram for `eventLoop`, the ELU baseline for `utilization`, the CPU baseline for `cpu`. +// `start()`/`stop()` (InterceptorBase) therefore do nothing here. Every tick reads each armed stage on its own and +// emits it; a stage whose read throws is reported and drops ONLY itself for that tick. +// +// ABSENCE IS NEVER ZERO. A stage whose runtime cannot answer emits nothing: ELU on Bun/Deno (flat idle/active zeros), +// the event-loop histogram when it has no sample yet or when the platform gated it off (Deno's never sees a blocked +// loop), the GC observer where it is blind (Bun/Deno) or refused, the heap/limit/available-memory readers when their +// numbers are not true. The platform GATES (`measures*`) are runtime-identity facts the composition root passes in; +// the tracker only honours them. An injected source/reader always wins over its gate. +// +// SINGLETON per key object (see `processTrackerFor`: the `process` object by default). RETENTION rule β€” what survives +// a stage's last unsubscribe: ONLY the resolved seams, and the "this runtime refused" memory inside the guarded +// sources (a refusing histogram/observer is not hammered again until a rebind swaps the seams). Everything windowed +// starts FRESH on the next subscription: the CPU baseline, the ELU baseline, the last-emitted samples +// (`current()` of a windowed stage), the histogram and the GC interval β€” a stale window would be a lie. Every timer +// callback is guarded by the run that armed it, so a timer whose clear failed can never emit. +// +// FAILURE. A source that fails to start is reported and the stage is left unarmed (never half-armed); it is retried +// on the next listener change or rebind. A timer that cannot be armed unwinds every stage armed for it. + +export type { GcInterval, GcSource } from './gc-observer'; +export type { EventLoopSource } from './guarded-event-loop'; + +export interface ProcessMemory { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; +} +export interface ProcessEvents { + memory: ProcessMemory; + systemMemory: { total: number; free: number }; + /** Deltas since the previous tick (Β΅s), and the process's share of all cores (%) over that window. */ + cpu: { userDelta: number; systemDelta: number; processPct: number }; + eventLoop: { meanMs: number; maxMs: number; p99Ms: number }; + /** Event-loop utilization over the previous tick, 0..1. */ + utilization: { utilization: number }; + /** GC activity since the previous tick (a quiet interval is a TRUE zero: the observer is running). */ + gc: GcInterval; + v8Heap: V8HeapStats; + memoryLimit: { bytes: number }; + availableMemory: { bytes: number }; + /** Whole seconds since process start. */ + uptime: { seconds: number }; +} +type Stage = keyof ProcessEvents; +// Read order of a tick. GC is last: its read drains the interval, so nothing after it may fail the tick. +const STAGES: readonly Stage[] = [ + 'memory', + 'systemMemory', + 'cpu', + 'eventLoop', + 'utilization', + 'v8Heap', + 'memoryLimit', + 'availableMemory', + 'uptime', + 'gc', +]; +/** Stages whose reading is a window since the previous read: they cannot be re-read on demand. */ +const WINDOWED: ReadonlySet = new Set(['cpu', 'eventLoop', 'utilization', 'gc']); + +export interface ProcessTimers { + setInterval(callback: () => void, ms: number): unknown; + clearInterval(handle: unknown): void; +} + +/** What the tracker needs from a launch. Every member is optional; an absent one falls back to the runtime default. */ +export interface ProcessEnv { + memoryUsage?: () => ProcessMemory; + cpuUsage?: () => { user: number; system: number }; + systemMemory?: () => { total: number; free: number }; + cpuCount?: () => number; + monotonicNowMs?: () => number; + /** Seconds since process start (fractions floored). Default `process.uptime()`. */ + uptime?: () => number; + /** Overrides the guarded histogram source (and its gate). */ + eventLoop?: EventLoopSource; + /** Overrides the GC observer source (and its gate). */ + gc?: GcSource; + /** ELU delta 0..1 per call, or undefined when unavailable. Overrides the guarded ELU reader. */ + eventLoopUtilization?: () => number | undefined; + /** Each reader answers undefined when the runtime cannot give a true value. Override their defaults and gates. */ + v8Heap?: () => V8HeapStats | undefined; + memoryLimit?: () => number | undefined; + availableMemory?: () => number | undefined; + /** perf_hooks primitives for the event-loop metrics (partial on Bun/Deno). Default node:perf_hooks. */ + perfHooks?: PerfHooks; + /** Test seam for the GC observer constructor. Default `node:perf_hooks`. */ + performanceObserver?: ObserverCtor; + /** + * Does this runtime's `monitorEventLoopDelay` observe a BLOCKED loop? Default `true`. Deno's does not (answers, + * never throws, never registers a stall), so `@bugsee/deno` passes `false` and the histogram is never constructed. + */ + measuresEventLoopDelay?: boolean; + /** + * Is `v8.getHeapStatistics()` a real V8 heap with a ceiling? Default `true`. Bun's is JSC-derived (not a ceiling, + * and ~1000x Node's cost per call), so `@bugsee/bun` passes `false`. + */ + measuresV8Heap?: boolean; + /** Is `process.availableMemory()` comparable to the Node figure? Default `true`; not on Bun/Deno. */ + measuresAvailableMemory?: boolean; + /** Does `PerformanceObserver({entryTypes:['gc']})` see collections? Default `true`; blind on Bun/Deno. */ + measuresGc?: boolean; + /** Drives the shared sampling timer; default the global timers, unref'd so the tracker never holds a process alive. */ + scheduler?: ProcessTimers; + /** Sampling period in ms (default 1000). */ + intervalMs?: number; +} + +const DEFAULT_INTERVAL_MS = 1000; + +const defaultScheduler: ProcessTimers = { + setInterval: (cb, ms) => { + const h = setInterval(cb, ms); + (h as { unref?: () => void }).unref?.(); + return h; + }, + clearInterval: (h) => clearInterval(h as ReturnType), +}; + +const SEAM_KEYS = [ + 'memoryUsage', + 'cpuUsage', + 'systemMemory', + 'cpuCount', + 'monotonicNowMs', + 'uptime', + 'eventLoop', + 'gc', + 'eventLoopUtilization', + 'v8Heap', + 'memoryLimit', + 'availableMemory', + 'perfHooks', + 'performanceObserver', + 'measuresEventLoopDelay', + 'measuresV8Heap', + 'measuresAvailableMemory', + 'measuresGc', + 'scheduler', + 'intervalMs', +] as const satisfies readonly (keyof ProcessEnv)[]; + +/** One armed stage. `read` may throw; `stop` is called once on teardown. */ +interface StageRun { + read(): unknown; + stop(): void; +} + +/** The sources/readers an env resolves to; built lazily and kept until the seams are swapped. */ +interface Resolved { + eventLoop: EventLoopSource | undefined; + gc: GcSource | undefined; + v8Heap: (() => V8HeapStats | undefined) | undefined; + memoryLimit: () => number | undefined; + availableMemory: (() => number | undefined) | undefined; +} + +const NOOP_RUN: StageRun = { read: () => undefined, stop: () => {} }; + +export class ProcessTracker extends InterceptorBase { + readonly name = 'node-process'; + #env: ProcessEnv; + #resolved: Resolved | undefined; + /** Armed stages (and their teardown). */ + readonly #armed = new Map(); + /** The last emitted/seeded sample of each WINDOWED stage, for the current run only. */ + readonly #last = new Map(); + #timer: { handle: unknown; scheduler: ProcessTimers } | null = null; + /** Bumped whenever the timer is torn down: a callback of an older run never emits. */ + #gen = 0; + // Mutable indirection: the SHARED tracker outlives launches, so the reporter is always the latest launch's. + readonly #report: { fn: ((error: unknown) => void) | undefined }; + + constructor(env: ProcessEnv = {}, onError?: (error: unknown) => void) { + const report = { fn: onError }; + // A throwing reporter must not escape into the emitter's dispatch (which runs inside the host's timers). + super((error) => { + try { + report.fn?.(error); + } catch { + /* the reporter itself failed */ + } + }); + this.#report = report; + this.#env = env; + } + + /** + * Hand the latest launch's seams to this shared tracker. A defined `onError` replaces the reporter (undefined keeps + * it). Every defined seam REPLACES ours; an undefined one never clobbers an earlier one (merge, never drop). When a + * seam actually changed, every armed stage is first torn down with the seams it was ARMED with (the timer is + * cleared on the scheduler that armed it), then the merged seams are swapped in and the stages that still have + * listeners start again against them (fresh baselines). An unchanged relaunch restarts nothing. + */ + rebind(env: ProcessEnv, onError?: (error: unknown) => void): void { + if (onError !== undefined) this.#report.fn = onError; + const merged: Record = {}; + let changed = false; + for (const key of SEAM_KEYS) { + const next = env[key] ?? this.#env[key]; + if (next !== undefined) merged[key] = next; + if (next !== this.#env[key]) changed = true; + } + if (!changed) return; + this.#stopAll(); // OLD seams + this.#env = merged as ProcessEnv; + this.#resolved = undefined; + this.#sync(); + } + + /** + * The latest reading of `stage`. Stateless stages are read LIVE (guarded: undefined when the runtime cannot answer + * or the read threw, which is reported). A WINDOWED stage (cpu, eventLoop, utilization, gc) cannot be re-read + * without consuming its window, so it answers the last sample of the current run: `cpu` is seeded with a + * zero-length window the moment it arms (so a producer has a baseline), the others are undefined until their first + * tick; all are undefined while the stage is not armed. + */ + current(stage: S): ProcessEvents[S] | undefined { + if (WINDOWED.has(stage)) { + const run = this.#armed.get(stage); + return run === undefined + ? undefined + : (this.#last.get(stage) as ProcessEvents[S] | undefined); + } + try { + const value = this.#makeRun(stage).read() as ProcessEvents[S] | undefined; + return value === undefined ? undefined : { ...value }; + } catch (error) { + this.#onError(error); + return undefined; + } + } + + /** Test/teardown: drop EVERY listener (which releases every stage and the timer). */ + reset(): void { + this.removeAllListeners(); + } + + // Activation is per stage (onListenersChanged); the whole-tracker hook has nothing to do. + protected onActivate(): void {} + + protected override onListenersChanged(): void { + this.#sync(); + } + + #onError(error: unknown): void { + try { + this.#report.fn?.(error); + } catch { + /* the reporter itself failed */ + } + } + + #sync(): void { + for (const stage of STAGES) { + if (this.listenerCount(stage) === 0) this.#stopStage(stage); + else if (!this.#armed.has(stage)) this.#startStage(stage); + } + this.#syncTimer(); + } + + #startStage(stage: Stage): void { + try { + const run = this.#makeRun(stage); + this.#armed.set(stage, run); + if (stage === 'cpu') this.#last.set(stage, { userDelta: 0, systemDelta: 0, processPct: 0 }); + } catch (error) { + this.#onError(error); // left unarmed: retried on the next listener change / rebind + } + } + + #stopStage(stage: Stage): void { + const run = this.#armed.get(stage); + this.#armed.delete(stage); + this.#last.delete(stage); + if (run === undefined) return; + try { + run.stop(); + } catch (error) { + this.#onError(error); // one failing stop must not strand another stage + } + } + + #stopAll(): void { + for (const stage of [...this.#armed.keys()]) this.#stopStage(stage); + this.#clearTimer(); + } + + #syncTimer(): void { + if (this.#armed.size === 0) { + this.#clearTimer(); + return; + } + if (this.#timer !== null) return; + const scheduler = this.#env.scheduler ?? defaultScheduler; + const gen = ++this.#gen; + try { + const handle = scheduler.setInterval(() => { + if (gen === this.#gen) this.#tick(); + }, this.#env.intervalMs ?? DEFAULT_INTERVAL_MS); + this.#timer = { handle, scheduler }; + } catch (error) { + this.#gen += 1; + this.#onError(error); + // Nothing would ever read these stages: do not leave an observer/histogram running for them. + this.#stopAll(); + } + } + + #clearTimer(): void { + const timer = this.#timer; + this.#timer = null; + this.#gen += 1; + if (timer === null) return; + try { + timer.scheduler.clearInterval(timer.handle); + } catch (error) { + this.#onError(error); + } + } + + #tick(): void { + for (const stage of [...this.#armed.keys()]) { + const run = this.#armed.get(stage); // a listener may have removed it mid-tick + if (run === undefined) continue; + let value: unknown; + try { + value = run.read(); + } catch (error) { + this.#onError(error); + continue; + } + if (value === undefined) continue; // absence, never zero + if (WINDOWED.has(stage)) this.#last.set(stage, value); + // Emitted payloads are copies: a subscriber cannot mutate the retained sample. + this.emit(stage, { ...(value as object) } as never); + } + } + + #resolve(): Resolved { + if (this.#resolved !== undefined) return this.#resolved; + const env = this.#env; + const perf = env.perfHooks ?? realPerfHooks; + // `??` / explicit gates (never a spread over defaults): an injected source wins; otherwise the default is wired + // only where the runtime can give a true value, and an unwired source means the stage is ABSENT. + const resolved: Resolved = { + eventLoop: + env.eventLoop ?? + (env.measuresEventLoopDelay !== false + ? createGuardedEventLoopSource(perf.monitorEventLoopDelay) + : undefined), + gc: + env.gc ?? (env.measuresGc !== false ? createGcSource(env.performanceObserver) : undefined), + v8Heap: + env.v8Heap ?? + (env.measuresV8Heap !== false ? createV8HeapReader(getHeapStatistics) : undefined), + memoryLimit: env.memoryLimit ?? createMemoryLimitReader(nodeProcess, totalmem), + availableMemory: + env.availableMemory ?? + (env.measuresAvailableMemory !== false + ? createAvailableMemoryReader(nodeProcess) + : undefined), + }; + this.#resolved = resolved; + return resolved; + } + + /** Builds the machinery of one stage against the CURRENT seams. May throw (the caller reports it). */ + #makeRun(stage: Stage): StageRun { + const env = this.#env; + const res = this.#resolve(); + switch (stage) { + case 'memory': { + const read = env.memoryUsage ?? (() => nodeProcess.memoryUsage()); + return { read, stop: () => {} }; + } + case 'systemMemory': { + const read = env.systemMemory ?? (() => ({ total: totalmem(), free: freemem() })); + return { read, stop: () => {} }; + } + case 'uptime': { + const uptime = env.uptime ?? (() => nodeProcess.uptime()); + return { read: () => ({ seconds: Math.floor(uptime()) }), stop: () => {} }; + } + case 'v8Heap': + return optionalRun(res.v8Heap); + case 'memoryLimit': + return optionalRun(res.memoryLimit, (bytes) => ({ bytes })); + case 'availableMemory': + return optionalRun(res.availableMemory, (bytes) => ({ bytes })); + case 'cpu': + return this.#cpuRun(); + case 'eventLoop': { + const source = res.eventLoop; + if (source === undefined) return NOOP_RUN; + source.start(); + return { read: () => source.read(), stop: () => source.stop() }; + } + case 'gc': { + const source = res.gc; + if (source === undefined) return NOOP_RUN; + source.start(); + return { read: () => source.read(), stop: () => source.stop() }; + } + case 'utilization': { + // Created per run: a fresh baseline, so the first tick never spans a period nobody was listening. + const perf = env.perfHooks ?? realPerfHooks; + const elu = env.eventLoopUtilization ?? createGuardedElu(perf.eventLoopUtilization); + return { + read: () => { + const utilization = elu(); + return utilization === undefined ? undefined : { utilization }; + }, + stop: () => {}, + }; + } + } + } + + #cpuRun(): StageRun { + const env = this.#env; + const cpuUsage = env.cpuUsage ?? (() => nodeProcess.cpuUsage()); + const nowMs = env.monotonicNowMs ?? (() => performance.now()); + const cpuCount = env.cpuCount ?? (() => cpus().length); + let last = cpuUsage(); + let lastWallMs = nowMs(); + return { + read: () => { + // Read BEFORE any baseline moves: a throw here fails this read and must not advance the CPU window. + const cpu = cpuUsage(); + const wall = nowMs(); + const userDelta = cpu.user - last.user; + const systemDelta = cpu.system - last.system; + const wallMsDelta = wall - lastWallMs; + last = cpu; + lastWallMs = wall; + // Normalized process CPU %: busy-Β΅s / wall-Β΅s / cores * 100. Guard the zero-window first sample. + const processPct = + wallMsDelta > 0 + ? ((userDelta + systemDelta) / (wallMsDelta * 1000) / cpuCount()) * 100 + : 0; + return { userDelta, systemDelta, processPct }; + }, + stop: () => {}, + }; + } +} + +/** A stateless run over a reader that may be unwired (absent) or answer undefined (cannot give a true value). */ +function optionalRun( + reader: (() => T | undefined) | undefined, + wrap: (value: T) => unknown = (value) => value, +): StageRun { + if (reader === undefined) return NOOP_RUN; + return { + read: () => { + const value = reader(); + return value === undefined ? undefined : wrap(value); + }, + stop: () => {}, + }; +} + +const registry = createTrackerRegistry(); + +/** A {@link ProcessEnv} plus the object the singleton is keyed on (default: the `process` object). */ +export interface ProcessTrackerEnv extends ProcessEnv { + key?: object; +} + +function seamsOf(env: ProcessTrackerEnv): ProcessEnv { + const seams: Record = {}; + for (const key of SEAM_KEYS) { + const value = env[key]; + if (value !== undefined) seams[key] = value; + } + return seams as ProcessEnv; +} + +/** + * The singleton ProcessTracker for the env's key (the `process` object by default). Every call (a relaunch + * included) hands the shared tracker the latest launch's `onError` and seams (see {@link ProcessTracker.rebind}); + * nothing else of the env is kept. + */ +export function processTrackerFor( + env: ProcessTrackerEnv = {}, + onError?: (error: unknown) => void, +): ProcessTracker { + const seams = seamsOf(env); + return registry.for( + env.key ?? nodeProcess, + () => new ProcessTracker(seams, onError), + (tracker) => tracker.rebind(seams, onError), + ); +} + +/** Test/teardown: drop the key's tracker (resetting it, so its timer and sources are released). */ +export function resetProcessTracker(key: object = nodeProcess): void { + registry.reset(key); +} diff --git a/packages/node/src/trackers/runtime-readers.test.ts b/packages/trackers/src/node/runtime-readers.test.ts similarity index 100% rename from packages/node/src/trackers/runtime-readers.test.ts rename to packages/trackers/src/node/runtime-readers.test.ts diff --git a/packages/node/src/trackers/runtime-readers.ts b/packages/trackers/src/node/runtime-readers.ts similarity index 99% rename from packages/node/src/trackers/runtime-readers.ts rename to packages/trackers/src/node/runtime-readers.ts index 490e47f0..87290bef 100644 --- a/packages/node/src/trackers/runtime-readers.ts +++ b/packages/trackers/src/node/runtime-readers.ts @@ -1,6 +1,6 @@ // Readers for the node runtime-depth traces (V8 heap, cgroup memory cap, available memory). Each answers // `undefined` when this runtime cannot give a TRUE reading, so its trace is omitted rather than invented. -// The process/os/v8 sources are injected: the defaults are wired in trace-producers.ts. +// The process/os/v8 sources are injected: the defaults are wired in process-tracker.ts. /** The V8 heap numbers the traces read, from `v8.getHeapStatistics()`. */ export interface V8HeapStats { diff --git a/packages/trackers/tsconfig.json b/packages/trackers/tsconfig.json index 5a24989c..3fbff51d 100644 --- a/packages/trackers/tsconfig.json +++ b/packages/trackers/tsconfig.json @@ -2,7 +2,8 @@ "extends": "../../tsconfig.base.json", "compilerOptions": { "outDir": "dist", - "rootDir": "src" + "rootDir": "src", + "types": ["node"] }, "include": ["src"] } diff --git a/packages/trackers/tsconfig.portable.json b/packages/trackers/tsconfig.portable.json new file mode 100644 index 00000000..5f0be479 --- /dev/null +++ b/packages/trackers/tsconfig.portable.json @@ -0,0 +1,11 @@ +{ + // The portable root + browser entries must typecheck WITHOUT node types: `types: ["node"]` in tsconfig.json exists + // only for src/node, and would otherwise let a node global leak into code that ships to browsers. + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"], + "exclude": ["src/node", "src/electron", "node_modules", "dist", "coverage"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a545be40..5be68fb6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -936,6 +936,9 @@ importers: '@bugsee/protocol': specifier: workspace:* version: link:../protocol + '@bugsee/trackers': + specifier: workspace:* + version: link:../trackers devDependencies: '@bugsee/util': specifier: workspace:* @@ -1251,7 +1254,11 @@ importers: specifier: ^4.0.0 version: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.9.1)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) - packages/trackers: {} + packages/trackers: + devDependencies: + '@types/node': + specifier: ^22.20.5 + version: 22.20.5 packages/types: {} From 78bd9472f63aad7a082ce4c5c2e6aa12afb90ed0 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 01:01:16 +0500 Subject: [PATCH 2/3] fix(trackers,node): no fabricated CPU start value; review hardening for ProcessTracker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CpuProducer has no baseline (a zero-length window has no CPU share); an unusable core count omits the sample; tick ends when its run is torn down mid-tick; real unref/restart/utilization/producer-restart tests; document merge-never-drop seams; bun/deno changesets minor. πŸ€– Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/node-process-tracker.md | 6 +- docs/PROGRESS.md | 2 +- packages/bun/src/launch.test.ts | 2 +- packages/deno/src/launch.test.ts | 2 +- .../elysia/src/elysia-integration.test.ts | 3 +- packages/node/src/event-loop-watchdog.test.ts | 8 +- packages/node/src/launch.test.ts | 11 +- packages/node/src/local-variables.test.ts | 8 +- packages/node/src/trace-producers.test.ts | 49 +++++++- packages/node/src/trace-producers.ts | 2 + packages/trackers/README.md | 2 +- .../trackers/src/node/process-tracker.test.ts | 111 ++++++++++++++++-- packages/trackers/src/node/process-tracker.ts | 23 ++-- 13 files changed, 189 insertions(+), 40 deletions(-) diff --git a/.changeset/node-process-tracker.md b/.changeset/node-process-tracker.md index 90ba22e2..5539511b 100644 --- a/.changeset/node-process-tracker.md +++ b/.changeset/node-process-tracker.md @@ -1,8 +1,8 @@ --- '@bugsee/node': minor -'@bugsee/bun': patch -'@bugsee/deno': patch +'@bugsee/bun': minor +'@bugsee/deno': minor '@bugsee/trackers': minor --- -Node, Bun and Deno system traces now come from a per-process `ProcessTracker` in the new `@bugsee/trackers/node` entry, which replaces `@bugsee/node`'s `ProcessStatsTracker`. Trace names and values are unchanged; the GC observer and event-loop histogram now run only while their traces are enabled, and the runtime gates for Bun and Deno still omit the traces those runtimes cannot measure honestly. `@bugsee/node` no longer exports `ProcessStatsTracker` and `ProcessStats`; it now exports `processTrackerFor`, `resetProcessTracker` and the `ProcessTracker` type instead. +Node, Bun and Deno system traces now come from a per-process `ProcessTracker` in the new `@bugsee/trackers/node` entry, which replaces `@bugsee/node`'s `ProcessStatsTracker`. Trace names are unchanged, the GC observer and event-loop histogram now run only while their traces are enabled, and the runtime gates for Bun and Deno still omit the traces those runtimes cannot measure honestly. The `cpu_usage_*` traces no longer record a start value (it was a microsecond-window noise reading); they begin with the first sample. `@bugsee/node` (and so `@bugsee/bun` and `@bugsee/deno`, which re-export it) no longer exports `ProcessStatsTracker` and `ProcessStats`; it exports `processTrackerFor`, `resetProcessTracker` and the `ProcessTracker` type instead. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index bbeac916..5bc10f56 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -413,7 +413,7 @@ solid), in slices: - **TR6 (DONE, `feat/storage-tracker`):** domain **`StorageTracker`** (`packages/trackers/src/browser/storage-tracker.ts`), singleton per window via `createTrackerRegistry` (`storageTrackerFor(env, onError?)`, `resetStorageTracker`; keyed window -> navigator -> env object, `rebind` as PowerTracker). Wraps `navigator.storage.estimate()` + `persisted()`; ONE stage `storageEstimate` `{usageBytes?, quotaBytes?, persisted?}`. This is an ORIGIN quota ESTIMATE (browsers fuzz/pad it), NOT device free space. No change event, so it polls sparsely: on activation, on `visibilitychange` -> visible, then a slow timer (default 5 min via an injectable scheduler; ticks while the page is hidden are skipped). A field that is non-finite/negative/non-number is omitted (never 0); `persisted` only when boolean; an estimate with no usable field emits nothing. A rejected/throwing `estimate()`/`persisted()` is reported via `onError` and costs only its own field (host getters through `hostRead`); launch is never failed. **Retention rule (tested):** the LAST estimate survives the last unsubscribe (`current()` answers at once; a failed poll never erases it); timer and visibility listener do not (released, re-armed on the next subscriber, which also polls afresh). A single epoch counter is bumped by every poll/stop/reset, so a stale in-flight promise (after stop/reset, or superseded by a newer poll) is inert. `rebind` keeps every defined seam (undefined never clobbers) and applies it from the NEXT activation; a tracker that is attached keeps the navigator/document/scheduler it armed (only `onError` changes at once). Visibility-triggered polls are throttled to one per 60 s (`VISIBILITY_MIN_GAP_MS`, injectable `now`); the slow timer is not. Poll failures are reported ONCE per failure streak (reset by a poll without failures, and by `reset()`), not on every tick. A PARTIAL poll (one of `estimate()`/`persisted()` failed) merges: the failed call's retained fields are kept, answered fields replace, and the estimate's age advances only when usage/quota were refreshed. `currentFresh()` returns the retained estimate only while younger than 2x the poll interval (`current()` still returns it regardless). `StorageProducer` (browser `trace-producers.ts`, built after the `sensors:false` gate like the other sensor producers, so a `systemMetricsSampler` replaces it) emits the NEW JS-specific trace `storage_estimate` `{usage, quota}` in integer MB (`bytesToMegabytes`, floored; a missing key is omitted, `persisted` is not a trace) - NOT the Android `disk_mem_*` group. It is held/de-duplicated (`emitIfChanged`) because the poll period (5 min) far exceeds the default 60 s recording window; a non-held value would almost never appear in a report. `StorageProducer.onStart` seeds only from `currentFresh()` (never a snapshot older than 2x the interval). **OWNER DECISION PENDING:** a held polled value cannot be retracted, so after failed polls the last known estimate keeps being re-recorded every `refreshMs`. Alternatives: plain `emit` (the value would rarely land in a 60 s window) or a provider retract/release mechanism (same open question as the TR4 time traces). Usage under 1 MiB floors to 0 MB (an honest floor, not a measurement of zero). Shared by the WebView launch via the browser producers. Launch-level test proves launch goes through `storageTrackerFor` (the window's singleton holds the estimate). - **TR7 (DONE, `feat/environment-tracker`):** domain **`EnvironmentTracker`** (`packages/trackers/src/browser/environment-tracker.ts`), singleton per window via `createTrackerRegistry` (`environmentTrackerFor(env, onError?)`, `resetEnvironmentTracker`; keyed window -> navigator -> env object; `rebind` merges seams, never drops a defined one; a RUNNING tracker whose window/navigator/document/scheduler/interval changed detaches with the OLD seams, swaps in place, then re-attaches; `detectPrivateMode` turned on while running probes at once, turned off drops the result and any in-flight probe). Five stages: `language` `{language?, languages?, previous}` (`navigator.language(s)` + `languagechange`), `timezone` `{timeZone?, utcOffsetMinutes?, previous}` (no browser event, so re-read on a slow injectable timer, default 60 s with hidden-page ticks skipped, and on visibility -> visible; a DST shift is an offset change), `hints` `{cookiesEnabled?, secureContext?, crossOriginIsolated?, serviceWorkerControlled?, automation?, doNotTrack?, globalPrivacyControl?}`, `permissions` `{camera?, microphone?, geolocation?, notifications?, 'idle-detection'?: 'granted'|'denied'|'prompt'}` and `privateMode` `{private: 'yes'|'no'|'unknown', method?}`. `language`/`timezone` are CHANGE-ONLY (the first reading is a silent baseline held in `current()`, because they back `*_changed` events); `hints`/`permissions` are SNAPSHOT stages (first reading + every change); `privateMode` emits when its answer first arrives and when it changes. **Never prompts:** only `navigator.permissions.query()` is called (never requestPermission/getUserMedia/...), only the state STRING is kept, a PermissionStatus `change` refreshes it; a name the browser rejects with TypeError is omitted silently (Firefox does not know `camera`), other rejections are reported once per failure streak. **Private mode** is a HEURISTIC, never a certainty: one method `storage-quota` (`estimate().quota` under 120 MiB -> `yes`, at/over 1 GiB -> `no`, between or unreadable -> `unknown`; Chromium gives incognito a small fixed quota, Safari fuzzes). Omit-never-fabricate everywhere (empty/non-string language, NaN offset, non-boolean hints, unusable permission states are omitted; unknown DNT values omitted). Every host read goes through `hostRead` (a hostile getter costs only its field and is reported), a throwing `onError` never escapes. **Retention rule (tested):** the last language/time zone/hints/permissions/private-mode readings survive the last unsubscribe (and the change-only stages compare a restart against them); DOM listeners (languagechange, visibilitychange, PermissionStatus change), the timer and async work in flight do not (epoch tokens make a stale query/probe inert). **Events (`events.system`, `createBrowserSystemEventsSource`; the WebView launch shares the same source):** `language_changed` `{language?, languages?, previousLanguage?}`, `timezone_changed` `{timezone?, utcOffsetMinutes?, previousTimezone?, previousUtcOffsetMinutes?}`, `private_mode_detected` `{method?}` (ONLY for a `yes`; `no`/`unknown` never produce an event). Event names are free-form in `SystemEvent` (no registry/schema list exists to extend). **Launch option `captureEnvironmentHints`** (canonical `com.bugsee.option.capture.environment-hints`, browser launch only, default TRUE (opt-out), fail-closed boolean: anything but a boolean is OFF and reported) -> tracker `detectPrivateMode`; the WebView launch never enables it. **OWNER DECISION (2026-10-20, binding): private/incognito detection is OPT-OUT, ON by default** (the launch option keeps its name `captureEnvironmentHints`, default TRUE, `false` opts out, an invalid value is OFF and reported); still a tri-state heuristic (`yes`/`no`/`unknown`, method `storage-quota`), never a certainty. The decision covers private mode only, not other sensitive signals. The WebView launch still passes `detectPrivateMode: false` (no launch option there; a WebView's storage quota is not a private-window signal). **Not done / scope notes:** no `displayMode` stage (the UiTracker owns display-mode; `display_mode_changed` will be derived from it later); `hints` and `permissions` are tracker-level only, they have no wire consumer (the environment envelope schema is closed and has no field for them, so language/timezone were NOT added to `environment` either: `platform.locale`/`utc_offset` are still read once at launch by `buildBrowserEnvironment`, and the new events carry the later changes); **hints and permissions are NOT read by default (PR #84 review):** tracker env flags `observeHints` / `queryPermissions` (default false; a change while running re-attaches, turning one off drops its reading and, for permissions, the status listeners and in-flight queries); the browser system-events source passes both `false` explicitly (never inherited from the window's shared tracker), so a launch issues no `permissions.query()` and reads no hints until a real consumer sets them. Launch tests prove launch goes through `environmentTrackerFor` (the window's singleton holds the readings; mutating the source to `new EnvironmentTracker` fails them) and that private mode is ON by default and off with `captureEnvironmentHints: false`; the WebView launch has the same singleton test. **Review round 2:** persistent host-read failures of language/timezone/hints/visibility are reported once per failure streak (a clean run or `reset()` ends it); emitted stage payloads are copies, so a subscriber cannot mutate retained readings; the WebView launch now passes `document` + `scheduler` to the environment source; `resetEnvironmentTracker` is NOT re-exported from `@bugsee/browser` (reach teardown via `environmentTrackerFor(env).reset()`). **Round 3:** a host read that THROWS keeps that field's retained value (language, languages, time zone id, offset, each hint), so a transient failure never yields a fake `language_changed`/`timezone_changed`; `reset()` now drops all subscribers (`removeAllListeners`, as ApplicationTracker does) so the tracker re-activates for the next subscriber; a throwing `PermissionStatus.state` getter is reported once per streak. **Round 4:** per-permission-name streaks; a throwing state read, or a name whose re-query is rejected with a non-TypeError, keeps that name's retained state (a TypeError still omits it). **Round 5:** the browser system-events source subscribes to the tracker with ONE `onAny` (the activation read can emit a change made while the SDK was stopped, so per-stage subscriptions lost the later stages: a zone change alongside a language change vanished); the WebView launch passes `detectPrivateMode: false` explicitly (never inherits ON from an earlier launch on the window); stage payloads copy `previous` as well (a kept field shares its array). **PR review:** `privateMode` is no longer re-emitted on every activation: it emits when the answer first arrives and when it changes, a retained yes/no is not re-probed on a restart or a seam-moving rebind (an `unknown` is retried), and turning detection off then on re-detects; the browser events source always passes `detectPrivateMode` explicitly (omitted = false, never inherited); an answered-but-unusable permission state clears the stale entry (a failed/throwing read still retains it); private-probe getter failures (storage/estimate/quota) are reported once per streak; it stays a heuristic (constrained storage can false-positive). **Per-session delivery:** the tracker outlives sessions and never re-probes a retained yes/no, so the browser events source reads `current().privateMode` right after subscribing and re-emits `private_mode_detected` once for a retained `yes` (never for `no`/`unknown`, and never when this source opted out; the sink-side `detectPrivateMode` guard also covers the retained read). - **TR5 (implemented on `feat/process-tracker`, PR #83; multi-agent review rounds still in progress, one owner decision open β€” see "Known limit" below):** domain **`ProcessTracker`** (`packages/trackers/src/browser/process-tracker.ts`), singleton per window via `createTrackerRegistry` (`processTrackerFor(env, onError?)`, `resetProcessTracker`; keyed window -> performance -> env object, `rebind` merge-not-drop: a seam change on a RUNNING tracker first detaches every armed stage with the seams it was armed with, then swaps and restarts). It ABSORBS and replaces the per-signal `MemoryTracker` and `MainThreadLagTracker` (files + tests deleted; `MemoryProducer`/`MainThreadLagProducer` now subscribe to it; trace names and wire shapes unchanged). Five stages, each armed ONLY while it has listeners (via the `listenerCount(name)` / `onListenersChanged()` hooks `MultiKeyEmitterBase` already has on `main` from TR2; this PR does not touch the emitter; `start()`/`stop()` do nothing here): `heap` `{used, limit}` (`performance.memory`, polled; a figure that is not a finite non-negative number omits the reading), `mainThreadLag` `{lagMs}` (TIMER DRIFT, algorithm and visible-only gating unchanged: block >= 1 s always shows, shorter that crosses no due tick reads 0, reported once, fresh baseline each visible start), `idle` `{idleMs}` (NEW, ONE `requestIdleCallback` probe per sampling tick, never a loop and at most one in flight, visible pages only, `timeRemaining()` clamped to <= 50 ms; a tick whose callback never runs yields NO sample, never 0; omitted without rIC, e.g. Safari), `userIdle` `{userState: 'active'|'idle', screenState?: 'locked'|'unlocked'}` (NEW, Idle Detection API), `uptime` `{uptimeMs}` (`performance.now()`, omitted without a clock; no trace consumes it yet). **Idle Detection permission rule (binding): the SDK NEVER prompts.** `IdleDetector.requestPermission()` is never called; the detector starts ONLY when `navigator.permissions.query({name:'idle-detection'})` ALREADY reports `granted` (an engine that does not know the name rejects = stage inert, silent). The permission is re-queried on every activation and watched through its `change` event (granted later -> starts; revoked -> aborts and drops the tracker's retained state). Threshold floored at the spec's 60 s; stop aborts via `AbortController`; every async continuation is guarded by its run. **Retention rule (tested):** the last `userIdle` state survives the last unsubscribe (`currentUserIdle()`; `currentUserIdleFresh()`, which `UserIdleProducer` seeds from, answers only once the ARMED stage's detector has PUBLISHED in this run (permission re-confirmed and its `start()` settled; no age bound, a live detector reports changes only) and is undefined while the async permission re-query or `start()` is pending, or after a refusal/revoke; with NO armed stage it serves the state only while younger than 2 detector thresholds, via a new injectable `now` seam defaulting to `Date.now`, mirroring TR6's `currentFresh()`. A revoke while no stage is armed is therefore only noticed by the next activation's re-query (the plain `currentUserIdle()` read keeps the snapshot until then), but it can never seed a held trace); heap is read live; idle/lag/uptime keep nothing (a stale baseline would be a lie); timers, lifecycle subscription, pending probe and detector are released. New JS-specific traces (`BrowserTraceEnv` gains `requestIdleCallback`/`cancelIdleCallback`/`IdleDetector`/`AbortController`, bound/taken from the injected window by `browserTraceEnvFrom`): `main_thread_idle_ms` (ms, polled/not held; built under the same lifecycle gate as lag/fps) and `user_idle_state` (a STRING like `app_state`: `active` | `idle` | `locked`, where a locked screen wins over `userState`; held, de-duplicated; no trace at all unless the permission was already granted). **`user_idle_state` is OPT-IN (review P2; the maintainer's decision, PENDING OWNER CONFIRMATION): the host page's `idle-detection` grant shows only that the page was given the permission, not consent to record and upload idle/locked state. So `createBrowserSystemTraceProducers` builds `UserIdleProducer` only for `BrowserTraceEnv.captureUserIdle === true`, fed by the new browser + WebView launch option `captureUserIdle` (default false, strict boolean: any other value stays off and is reported; local key `com.bugsee.option.browser.capture-user-idle`, exported as `CAPTURE_USER_IDLE_OPTION_KEY`). Even when on, the tracker starts a detector only if the permission ALREADY reports `granted` (the SDK still never prompts). Without the opt-in the permission is not even queried. This applies ONLY to `user_idle_state`; private-mode detection is opt-out by a separate owner decision.** The viewer has no definition for either name yet (generic value block, design Β§13.3). **Known limit (OWNER DECISION PENDING β€” no retract mechanism invented):** `user_idle_state` is a HELD trace and the tracker emits nothing when the permission is revoked, so a producer that already published a value keeps having it re-recorded every `refreshMs` until the producer stops (the revoke only drops the tracker's retained copy and so stops NEW seeds; the seed is gated as above). Resolving it needs a decision on a retract/clear signal for held traces (same family as TR6's held `storage_estimate`). Other hardening from review: a hostile `performance.now` getter is reported exactly once in total (the factory reads silently, the tracker reports; only a SUCCESSFUL clock read is memoised per env, a failed one is retried on the next activation); `ProcessTracker.reset()` now drops every listener (like `ApplicationTracker`), so a later listener change cannot re-arm a stage for a gone subscriber; `browserTraceEnvFrom` now hands back stable bound closures per (window, function), so a no-op relaunch no longer restarts armed stages; a non-finite lag baseline omits that tick's `main_thread_lag_ms` instead of sending NaN; the gated teardown always closes the run. Launch-level test proves browser launch goes through `processTrackerFor` (the window's singleton can read the heap through launch's seams); the WebView launch shares the producers. `sensors:false` (a `systemMetricsSampler`) still builds only the battery producer. -- **TR8 part 1 (implemented on `feat/node-process-tracker`; Process only, Storage/disk is a later slice):** the node/bun/deno **`ProcessTracker`** (`packages/trackers/src/node/process-tracker.ts`, `@bugsee/trackers/node`) ABSORBS and REPLACES `@bugsee/node`'s per-signal `ProcessStatsTracker` (files + tests deleted from `packages/node/src/trackers/`); `gc-observer`, `guarded-event-loop` and `runtime-readers` moved (with their tests) to `packages/trackers/src/node/` unchanged apart from `EventLoopSource` now living beside the histogram source. Singleton per process via the registry (`processTrackerFor(env, onError?)`, key `env.key` else the `process` object; `resetProcessTracker(key?)`); `rebind` merges (defined seams replace, undefined never clobber; an UNCHANGED relaunch restarts nothing; a changed seam tears every armed stage down with the OLD seams, the timer is cleared on the scheduler that armed it, then re-arms on the new ones; latest `onError` wins). Ten **per-stage-activated** stages (one shared unref'd timer exists only while some stage has a listener; each stage's machinery only while it is wanted): `memory`, `systemMemory`, `cpu` `{userDelta, systemDelta, processPct}`, `eventLoop` `{meanMs, maxMs, p99Ms}`, `utilization` `{utilization}`, `gc` `{count, pauseMs, maxPauseMs}`, `v8Heap`, `memoryLimit` `{bytes}`, `availableMemory` `{bytes}`, `uptime` `{seconds}`. Trace names and wire values are unchanged. Honesty rules are unchanged and still tracker-owned: a stage that cannot answer EMITS NOTHING (ELU zeros on Bun/Deno, an unsampled histogram, a blind/refusing GC observer, untrue heap/limit/available readings), and the runtime-identity GATES (`measuresEventLoopDelay`/`measuresV8Heap`/`measuresAvailableMemory`/`measuresGc`) are now tracker env flags that the platform composition roots (`@bugsee/{deno,bun}` via `createNodeSystemTraceProducers`) pass through; an injected source/reader wins over its gate. **Retention rule (stated and tested):** only the resolved seams and the "this runtime refused" memory inside the guarded sources survive the last unsubscribe; the CPU baseline, ELU baseline, histogram, GC interval and the last windowed sample all start FRESH on the next subscription. `current(stage)` reads stateless stages LIVE (guarded, copies) and answers the last emitted sample of a windowed stage (`cpu` is seeded with a zero-length window when it arms, so a producer has a baseline). Hardening: reporter indirection that swallows a throwing `onError`, generation-guarded timer callbacks (a timer whose clear failed never emits), each stage read isolated (one throwing reader drops only itself; a failed CPU read never advances the baseline), a failing source start leaves its stage unarmed (never half-armed, retried on the next listener change/rebind), a timer that cannot be armed unwinds the stages armed for it, one failing stop never strands another, emitted payloads are copies. `@bugsee/node`'s `trace-producers.ts` is now composition only (ten producers, each subscribed to ONE stage; `NodeTraceProducerDeps` = tracker env + `onError`), and `@bugsee/node` re-exports `processTrackerFor`/`resetProcessTracker`/`ProcessTracker` (and drops the `ProcessStatsTracker`/`ProcessStats` exports). **Behaviour notes:** (1) the tracker is one per PROCESS now, so a second producer set / relaunch shares it and its seams are rebound (tests that inject fakes must pass a private `key` or call `resetProcessTracker()`); (2) per-stage activation means the GC observer and the delay histogram exist only while their producer is subscribed (before, they ran whenever any producer was); (3) the ELU baseline is taken when its stage arms (before: when the producers were built), so the first sample no longer spans an idle gap; (4) the activation CPU/baseline read and the poll are per stage, so one failing reader no longer fails the whole poll (before: an `uptime` failure dropped the whole row); (5) the `current()` cpu baseline is an explicit zero-length window `{0,0,0}` (before: a ~0-length read, same values in practice). **Tooling:** `@bugsee/trackers` gained `@types/node` (devDependency) and `tsconfig.json` now carries `types: ["node"]` for `src/node`; `tsconfig.portable.json` re-typechecks the portable root + browser entries WITHOUT node types (`pnpm typecheck` runs both) so a node global cannot leak into code shipped to browsers. `@bugsee/node` gained the `@bugsee/trackers` workspace dependency. Launch tests prove the default producers go through the registry accessor (mutating the producer factory to `new ProcessTracker` fails them) and that the Bun/Deno gates reach the shared tracker end to end. +- **TR8 part 1 (implemented on `feat/node-process-tracker`; Process only, Storage/disk is a later slice):** the node/bun/deno **`ProcessTracker`** (`packages/trackers/src/node/process-tracker.ts`, `@bugsee/trackers/node`) ABSORBS and REPLACES `@bugsee/node`'s per-signal `ProcessStatsTracker` (files + tests deleted from `packages/node/src/trackers/`); `gc-observer`, `guarded-event-loop` and `runtime-readers` moved (with their tests) to `packages/trackers/src/node/` unchanged apart from `EventLoopSource` now living beside the histogram source. Singleton per process via the registry (`processTrackerFor(env, onError?)`, key `env.key` else the `process` object; `resetProcessTracker(key?)`); `rebind` merges (defined seams replace, undefined never clobber; an UNCHANGED relaunch restarts nothing; a changed seam tears every armed stage down with the OLD seams, the timer is cleared on the scheduler that armed it, then re-arms on the new ones; latest `onError` wins). Ten **per-stage-activated** stages (one shared unref'd timer exists only while some stage has a listener; each stage's machinery only while it is wanted): `memory`, `systemMemory`, `cpu` `{userDelta, systemDelta, processPct}`, `eventLoop` `{meanMs, maxMs, p99Ms}`, `utilization` `{utilization}`, `gc` `{count, pauseMs, maxPauseMs}`, `v8Heap`, `memoryLimit` `{bytes}`, `availableMemory` `{bytes}`, `uptime` `{seconds}`. Trace names and wire values are unchanged. Honesty rules are unchanged and still tracker-owned: a stage that cannot answer EMITS NOTHING (ELU zeros on Bun/Deno, an unsampled histogram, a blind/refusing GC observer, untrue heap/limit/available readings), and the runtime-identity GATES (`measuresEventLoopDelay`/`measuresV8Heap`/`measuresAvailableMemory`/`measuresGc`) are now tracker env flags that the platform composition roots (`@bugsee/{deno,bun}` via `createNodeSystemTraceProducers`) pass through; an injected source/reader wins over its gate. **Retention rule (stated and tested):** only the resolved seams and the "this runtime refused" memory inside the guarded sources survive the last unsubscribe; the CPU baseline, ELU baseline, histogram, GC interval and the last windowed sample all start FRESH on the next subscription. `current(stage)` reads stateless stages LIVE (guarded, copies) and answers the last emitted sample of a windowed stage (`cpu` is seeded with a zero-length window when it arms, so a producer has a baseline). Hardening: reporter indirection that swallows a throwing `onError`, generation-guarded timer callbacks (a timer whose clear failed never emits), each stage read isolated (one throwing reader drops only itself; a failed CPU read never advances the baseline), a failing source start leaves its stage unarmed (never half-armed, retried on the next listener change/rebind), a timer that cannot be armed unwinds the stages armed for it, one failing stop never strands another, emitted payloads are copies. `@bugsee/node`'s `trace-producers.ts` is now composition only (ten producers, each subscribed to ONE stage; `NodeTraceProducerDeps` = tracker env + `onError`), and `@bugsee/node` re-exports `processTrackerFor`/`resetProcessTracker`/`ProcessTracker` (and drops the `ProcessStatsTracker`/`ProcessStats` exports). **Behaviour notes:** (1) the tracker is one per PROCESS now, so a second producer set / relaunch shares it and its seams are rebound (tests that inject fakes must pass a private `key` or call `resetProcessTracker()`); (2) per-stage activation means the GC observer and the delay histogram exist only while their producer is subscribed (before, they ran whenever any producer was); (3) the ELU baseline is taken when its stage arms (before: when the producers were built), so the first sample no longer spans an idle gap; (4) the activation CPU/baseline read and the poll are per stage, so one failing reader no longer fails the whole poll (before: an `uptime` failure dropped the whole row); (5) there is NO CPU start value any more: before, the producer published a microsecond-window noise reading at start (`processPct` 7-43%, never a true share), now the tracker keeps its internal counters but the CPU producer has an empty `baseline()` and `current('cpu')` is undefined until the first tick (as for gc/event-loop-lag/utilization); an unusable core count (`os.cpus()` empty) now omits the cpu sample instead of emitting Infinity/NaN; (6) **seams merge, never drop:** the tracker outlives launches, so a later launch that omits `scheduler`/`onError`/a reader KEEPS the previous launch's (it can replace a seam, never shed one), and merely BUILDING a producer set rebinds the shared tracker (including the Bun/Deno default sets built before `...options` in their `launch.ts`); tests must use a private `key` or `resetProcessTracker()` (added to the afterEach of the node, bun, deno and elysia launch tests). **Tooling:** `@bugsee/trackers` gained `@types/node` (devDependency) and `tsconfig.json` now carries `types: ["node"]` for `src/node`; `tsconfig.portable.json` re-typechecks the portable root + browser entries WITHOUT node types (`pnpm typecheck` runs both) so a node global cannot leak into code shipped to browsers. `@bugsee/node` gained the `@bugsee/trackers` workspace dependency. Launch tests prove the default producers go through the registry accessor (mutating the producer factory to `new ProcessTracker` fails them) and that the Bun/Deno gates reach the shared tracker end to end. - **ST0β€² (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/bun/src/launch.test.ts b/packages/bun/src/launch.test.ts index c14503eb..22ef0648 100644 --- a/packages/bun/src/launch.test.ts +++ b/packages/bun/src/launch.test.ts @@ -126,7 +126,7 @@ describe('@bugsee/bun launch', () => { const names = traces.map((e) => (e.data as { name: string }).name); expect(names).toContain('process_memory_rss'); expect(names).toContain('ram_system_total'); - expect(names).toContain('cpu_usage_process'); + 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)', () => { diff --git a/packages/deno/src/launch.test.ts b/packages/deno/src/launch.test.ts index 7cc830be..842c5e32 100644 --- a/packages/deno/src/launch.test.ts +++ b/packages/deno/src/launch.test.ts @@ -335,7 +335,7 @@ describe('@bugsee/deno β€” the event-loop metrics Deno cannot measure', () => { const names = traces.map((e) => (e.data as { name: string }).name); expect(names).toContain('process_memory_rss'); expect(names).toContain('ram_system_total'); - expect(names).toContain('cpu_usage_process'); + expect(names).not.toContain('cpu_usage_process'); // no CPU start value: it begins with the first sampled window // Deno cannot observe a blocked loop, so no lag trace is fabricated. expect(names.some((n) => n.startsWith('event_loop_lag'))).toBe(false); }); diff --git a/packages/elysia/src/elysia-integration.test.ts b/packages/elysia/src/elysia-integration.test.ts index abc1d910..d1b772ee 100644 --- a/packages/elysia/src/elysia-integration.test.ts +++ b/packages/elysia/src/elysia-integration.test.ts @@ -1,5 +1,5 @@ import { SchedulerToken } from '@bugsee/core'; -import { type Bugsee, launch, type NodeRuntime } from '@bugsee/node'; +import { type Bugsee, launch, type NodeRuntime, resetProcessTracker } from '@bugsee/node'; import { wirePerformance } from '@bugsee/performance'; import { strFromU8, unzipSync } from '@bugsee/util'; import { Elysia } from 'elysia'; @@ -63,6 +63,7 @@ const parseBundle = (zip: Uint8Array): ParsedBundle => { const clients: Bugsee[] = []; afterEach(async () => { await Promise.all(clients.splice(0).map((c) => c.stop())); + resetProcessTracker(); // the shared per-process tracker merges seams across launches delete (globalThis as { __BUGSEE__?: unknown }).__BUGSEE__; }); diff --git a/packages/node/src/event-loop-watchdog.test.ts b/packages/node/src/event-loop-watchdog.test.ts index ddb4a181..d2dc3317 100644 --- a/packages/node/src/event-loop-watchdog.test.ts +++ b/packages/node/src/event-loop-watchdog.test.ts @@ -1,5 +1,6 @@ import type { Scheduler } from '@bugsee/core'; -import { describe, expect, it, vi } from 'vitest'; +import { resetProcessTracker } from '@bugsee/trackers/node'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { createEventLoopWatchdog, evaluateHang, @@ -10,6 +11,11 @@ import { type WatchdogWorker, } from './event-loop-watchdog'; +// The per-process ProcessTracker singleton merges seams across launches: never carry one test's fakes into the next. +afterEach(() => { + resetProcessTracker(); +}); + const T: HangThresholds = { fairMs: 3000, mediumMs: 5000, severeMs: 10000 }; function fakeWorkerSetup() { diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index 22eca3c9..3544903e 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -1383,11 +1383,14 @@ describe('launch β€” system trace producers', () => { systemMetricsSampler: undefined, }), ); - // the launch's producers are subscribed to THE `process` singleton: its cpu stage is armed (seeded baseline) - // and its tick is driven by the launch's scheduler + // the launch's producers are subscribed to THE `process` singleton: its cpu stage is armed and the tick is + // driven by the launch's scheduler (no sample exists before the first tick) const tracker = processTrackerFor(); - expect(tracker.current('cpu')).toEqual({ userDelta: 0, systemDelta: 0, processPct: 0 }); - expect(fs.calls.some((c) => c.ms === 1000)).toBe(true); + expect(tracker.current('cpu')).toBeUndefined(); + const ticks = fs.calls.filter((c) => c.ms === 1000); + expect(ticks.length).toBeGreaterThan(0); + for (const t of ticks) t.cb(); + expect(typeof tracker.current('cpu')?.processPct).toBe('number'); // a relaunch shares the SAME tracker (no second instance, no second set of sources) expect(processTrackerFor()).toBe(tracker); }); diff --git a/packages/node/src/local-variables.test.ts b/packages/node/src/local-variables.test.ts index cbea8ad4..61d14471 100644 --- a/packages/node/src/local-variables.test.ts +++ b/packages/node/src/local-variables.test.ts @@ -1,6 +1,7 @@ import type { StackFrame } from '@bugsee/core'; import { REDACTED } from '@bugsee/protocol'; -import { describe, expect, it, vi } from 'vitest'; +import { resetProcessTracker } from '@bugsee/trackers/node'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { alignReportSite, attachLocals, @@ -16,6 +17,11 @@ import { } from './local-variables'; /** A fake inspector session: records posts, answers `Runtime.getProperties` from a script. */ +// The per-process ProcessTracker singleton merges seams across launches: never carry one test's fakes into the next. +afterEach(() => { + resetProcessTracker(); +}); + function fakeSession(properties: Record = {}) { const posts: Array<{ method: string; params?: unknown }> = []; let paused: ((message: { params: unknown }) => void) | undefined; diff --git a/packages/node/src/trace-producers.test.ts b/packages/node/src/trace-producers.test.ts index b96af068..4cb3f050 100644 --- a/packages/node/src/trace-producers.test.ts +++ b/packages/node/src/trace-producers.test.ts @@ -1,12 +1,16 @@ +import { processTrackerFor } from '@bugsee/trackers/node'; import { describe, expect, it } from 'vitest'; import { createNodeSystemTraceProducers, type NodeTraceProducerDeps } from './trace-producers'; +const harnessKey: object[] = []; function harness(deps: NodeTraceProducerDeps) { + const key = {}; + harnessKey.push(key); const got = new Map(); const spy = { set: 0, cleared: 0 }; let tick: (() => void) | undefined; const producers = createNodeSystemTraceProducers({ - key: {}, // a private tracker per test: the per-process singleton must not leak state between cases + key, // a private tracker per test: the per-process singleton must not leak state between cases ...deps, scheduler: { setInterval: (cb) => { @@ -312,7 +316,43 @@ describe('createNodeSystemTraceProducers', () => { const h = harness(constDeps()); h.startAll(); expect(h.got.get('process_memory_rss')).toBe(10); - expect(h.got.get('cpu_usage_process')).toBe(0); + // no CPU baseline: no window has elapsed, so a start value would be invented + expect(h.got.has('cpu_usage_user')).toBe(false); + expect(h.got.has('cpu_usage_system')).toBe(false); + expect(h.got.has('cpu_usage_process')).toBe(false); + h.tick(); + expect(h.got.has('cpu_usage_process')).toBe(true); + }); + + it('a restart while the stage stays armed re-emits NO window (cpu, event-loop lag, utilization)', () => { + const h = harness( + constDeps({ + eventLoop: { start() {}, stop() {}, read: () => ({ meanMs: 1, maxMs: 2, p99Ms: 3 }) }, + eventLoopUtilization: () => 0.5, + }), + ); + h.startAll(); + h.tick(); + expect(h.got.has('event_loop_lag_ms')).toBe(true); + // keep every windowed stage armed through another subscriber, then restart the producers + const tracker = processTrackerFor({ key: harnessKey.at(-1) as object }); + const keep = [ + tracker.on('cpu', () => {}), + tracker.on('eventLoop', () => {}), + tracker.on('utilization', () => {}), + ]; + h.stopAll(); + h.got.clear(); + h.startAll(); + for (const name of [ + 'cpu_usage_user', + 'cpu_usage_process', + 'event_loop_lag_ms', + 'event_loop_utilization', + ]) { + expect(h.got.has(name), name).toBe(false); + } + for (const off of keep) off(); }); it('omits lag and utilization when no eventLoop / utilization source answers', () => { @@ -437,11 +477,10 @@ describe('createNodeSystemTraceProducers', () => { }), ); h.startAll(); - const baselineUser = h.got.get('cpu_usage_user'); + expect(h.got.has('cpu_usage_user')).toBe(false); // no start value h.tick(); - // arming reads 100k (the baseline, seeded as a zero-length window); the single tick reads 200k => one window of + // arming reads 100k (the internal baseline); the single tick reads 200k => one window of // 100k no matter how many producers share the tracker - expect(baselineUser).toBe(0); expect(h.got.get('cpu_usage_user')).toBe(100_000); }); diff --git a/packages/node/src/trace-producers.ts b/packages/node/src/trace-producers.ts index 33194b30..b4ff7de8 100644 --- a/packages/node/src/trace-producers.ts +++ b/packages/node/src/trace-producers.ts @@ -68,6 +68,8 @@ class CpuProducer extends StageProducer<'cpu'> { constructor(tracker: ProcessTracker) { super(tracker, 'cpu'); } + // No baseline: no window has elapsed at start, so any value would be invented (a zero-length window has no CPU share). + protected override baseline(): void {} protected publish(c: ProcessEvents['cpu']): void { this.emit('cpu_usage_user', c.userDelta); this.emit('cpu_usage_system', c.systemDelta); diff --git a/packages/trackers/README.md b/packages/trackers/README.md index 69acfffb..6f2f33ad 100644 --- a/packages/trackers/README.md +++ b/packages/trackers/README.md @@ -24,7 +24,7 @@ Trackers are the abstraction over system and runtime APIs. The package root is r The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, `resetApplicationTracker`), the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`), the `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; stages `heap`, `mainThreadLag` (timer drift), `idle` (`requestIdleCallback`), `userIdle` (Idle Detection) and `uptime`, each armed only while it has listeners; the SDK never prompts, so `userIdle` runs only when the `idle-detection` permission is already granted; the SDK's `user_idle_state` trace additionally needs the browser/WebView launch option `captureUserIdle: true`, because a page's own grant is not consent to record and upload idle/locked state), the UI/display `UiTracker` (`uiTrackerFor`, `resetUiTracker`: orientation, screenSize, viewport, colorScheme, reducedMotion, displayMode, frameRate), the `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; an approximate origin quota estimate, not device free space: browsers may pad `usage`, and `quota` can roughly reveal the device's disk size, so treat it as potentially identifying), the `EnvironmentTracker` (`environmentTrackerFor`, `resetEnvironmentTracker`; language, time zone, and, only when a consumer sets `observeHints` / `queryPermissions`, environment hints and Permissions API states queried without ever prompting; the private-browsing heuristic runs when `detectPrivateMode` is set (the browser launch sets it by default; opt out with `captureEnvironmentHints: false`) and is never reported as a certainty) and `hostRead`; `./electron` is reserved in `exports` and currently exports nothing. Its API is internal and may change between releases. -The `./node` entry is shared by Node, Bun and Deno and exports the process `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; a per-process singleton, keyed on the `process` object by default). Its ten stages (`memory`, `systemMemory`, `cpu`, `eventLoop`, `utilization`, `gc`, `v8Heap`, `memoryLimit`, `availableMemory`, `uptime`) are each armed only while they have listeners, behind one shared sampling timer. A stage the runtime cannot honestly measure emits nothing rather than zero (event-loop utilization on Bun/Deno, the event-loop delay histogram on Deno, the GC observer on Bun/Deno, the V8 heap on Bun), controlled by the `measures*` flags the platform packages pass in. It also exports the guarded runtime sources it is built from (`createGuardedEventLoopSource`, `createGuardedElu`, `createGcSource`, `createV8HeapReader`, `createMemoryLimitReader`, `createAvailableMemoryReader`). +The `./node` entry is shared by Node, Bun and Deno and exports the process `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; a per-process singleton, keyed on the `process` object by default). Its ten stages (`memory`, `systemMemory`, `cpu`, `eventLoop`, `utilization`, `gc`, `v8Heap`, `memoryLimit`, `availableMemory`, `uptime`) are each armed only while they have listeners, behind one shared sampling timer. A stage the runtime cannot honestly measure emits nothing rather than zero (event-loop utilization on Bun/Deno is dropped by its own tell, idle and active both zero; the event-loop delay histogram on Deno, the GC observer on Bun/Deno, the V8 heap on Bun and available memory on Bun/Deno are gated by the `measures*` flags the platform packages pass in). The CPU stage has no start value: it reports from the first tick. Seams merge and are never dropped: a later launch that omits `scheduler` or `onError` keeps the previous launch's, and building a producer set already rebinds the shared tracker, so tests that inject fakes need a private `key` or `resetProcessTracker()`. It also exports the guarded runtime sources it is built from (`createGuardedEventLoopSource`, `createGuardedElu`, `createGcSource`, `createV8HeapReader`, `createMemoryLimitReader`, `createAvailableMemoryReader`). ## Links diff --git a/packages/trackers/src/node/process-tracker.test.ts b/packages/trackers/src/node/process-tracker.test.ts index df860d57..c47f53c2 100644 --- a/packages/trackers/src/node/process-tracker.test.ts +++ b/packages/trackers/src/node/process-tracker.test.ts @@ -130,20 +130,46 @@ describe('ProcessTracker', () => { expect(log).toEqual(['loop.start', 'gc.start', 'loop.stop', 'gc.stop']); }); - it('restart re-arms and starts every windowed stage FRESH (no retained sample)', () => { + it('restart re-arms and starts every windowed stage FRESH: a sample taken by a TICK does not survive', () => { const log: string[] = []; let n = 0; - const { tracker } = mk({ + const { tracker, fs, advance } = mk({ eventLoop: source('loop', log, () => ({ meanMs: ++n, maxMs: 0, p99Ms: 0 })), + gc: source('gc', log, () => ({ count: 1, pauseMs: 1, maxPauseMs: 1 })), + eventLoopUtilization: () => 0.5, }); - const off = tracker.on('eventLoop', () => {}); - tracker.on('eventLoop', () => {})(); - expect(tracker.current('eventLoop')).toBeUndefined(); // armed, nothing ticked yet - off(); - expect(tracker.current('eventLoop')).toBeUndefined(); - tracker.on('eventLoop', () => {}); - expect(log).toEqual(['loop.start', 'loop.stop', 'loop.start']); - expect(tracker.current('eventLoop')).toBeUndefined(); + const off = [ + tracker.on('eventLoop', () => {}), + tracker.on('gc', () => {}), + tracker.on('utilization', () => {}), + tracker.on('cpu', () => {}), + ]; + advance({ user: 10, system: 0 }, 1000); + fs.tick(); + for (const stage of ['eventLoop', 'gc', 'utilization', 'cpu'] as const) { + expect(tracker.current(stage), stage).toBeDefined(); + } + for (const o of off) o(); + for (const stage of ['eventLoop', 'gc', 'utilization', 'cpu'] as const) { + expect(tracker.current(stage), stage).toBeUndefined(); // unarmed + tracker.on(stage, () => {}); + expect(tracker.current(stage), `${stage} after restart`).toBeUndefined(); // armed again, nothing ticked + } + expect(log.filter((l) => l.endsWith('.start'))).toHaveLength(4); // loop+gc started twice + }); + + it("utilization is windowed: each tick answers the reader's CURRENT value, not a retained one", () => { + let u: number | undefined = 0.25; + const { tracker, fs } = mk({ eventLoopUtilization: () => u }); + const got: unknown[] = []; + tracker.on('utilization', (x) => void got.push(x)); + fs.tick(); + u = 0.75; + fs.tick(); + u = undefined; + fs.tick(); + expect(got).toEqual([{ utilization: 0.25 }, { utilization: 0.75 }]); + expect(tracker.current('utilization')).toEqual({ utilization: 0.75 }); }); }); @@ -240,6 +266,34 @@ describe('ProcessTracker', () => { expect(log).toEqual(['loop.start', 'loop.stop']); }); + it('a listener that tears the run down mid-tick stops the rest of that tick', () => { + const { tracker, fs } = mk(); + const seen: string[] = []; + const offs: (() => void)[] = []; + offs.push( + tracker.on('memory', () => { + seen.push('memory'); + for (const o of offs) o(); // every listener leaves: the timer is cleared mid-tick + tracker.on('uptime', () => void seen.push('uptime')); // and a NEW run starts + }), + ); + offs.push(tracker.on('systemMemory', () => void seen.push('systemMemory'))); + fs.tick(); + expect(seen).toEqual(['memory']); // the old run emitted nothing more + }); + + it('a listener that REBINDS mid-tick (stages re-armed on the new run) ends the old run’s tick', () => { + const { tracker, fs } = mk(); + const seen: string[] = []; + tracker.on('memory', () => { + seen.push('memory'); + tracker.rebind({ intervalMs: 5 }); // changed seam: every stage is torn down and re-armed + }); + tracker.on('systemMemory', () => void seen.push('systemMemory')); + fs.callbackAt(0)?.(); + expect(seen).toEqual(['memory']); + }); + it('a stale timer callback (an earlier arming) never emits', () => { const { tracker, fs } = mk(); const { got, off } = collect(tracker); @@ -257,11 +311,11 @@ describe('ProcessTracker', () => { }); describe('current()', () => { - it('cpu is seeded with a zero-length window when it arms, then follows the ticks; undefined unarmed', () => { + it('cpu has NO sample until its first tick (a zero-length window is not a reading); undefined unarmed', () => { const { tracker, fs, advance } = mk(); expect(tracker.current('cpu')).toBeUndefined(); const off = tracker.on('cpu', () => {}); - expect(tracker.current('cpu')).toEqual({ userDelta: 0, systemDelta: 0, processPct: 0 }); + expect(tracker.current('cpu')).toBeUndefined(); advance({ user: 10, system: 20 }, 1000); fs.tick(); expect(tracker.current('cpu')).toEqual({ @@ -272,7 +326,21 @@ describe('ProcessTracker', () => { off(); expect(tracker.current('cpu')).toBeUndefined(); tracker.on('cpu', () => {}); - expect(tracker.current('cpu')).toEqual({ userDelta: 0, systemDelta: 0, processPct: 0 }); + expect(tracker.current('cpu')).toBeUndefined(); // the previous run's sample did not survive + }); + + it('an unusable core count omits the cpu sample (never Infinity/NaN) and keeps the window', () => { + let cores = 0; + const { tracker, fs, advance } = mk({ cpuCount: () => cores }); + const cpu: unknown[] = []; + tracker.on('cpu', (c) => void cpu.push(c)); + advance({ user: 1000, system: 0 }, 1000); + fs.tick(); + expect(cpu).toEqual([]); + cores = 1; + advance({ user: 2000, system: 0 }, 2000); + fs.tick(); + expect(cpu).toEqual([{ userDelta: 2000, systemDelta: 0, processPct: 0.1 }]); }); it('windowed stages answer the last emitted sample of this run', () => { @@ -857,6 +925,23 @@ describe('ProcessTracker', () => { expect(n).toBe(after); }); + it('the sampling timer is unref’d: it can never keep the process alive', () => { + const real = globalThis.setInterval; + let unrefs = 0; + globalThis.setInterval = (() => ({ + unref: () => { + unrefs += 1; + }, + })) as never; + try { + const off = new ProcessTracker({}).on('memory', () => {}); + expect(unrefs).toBe(1); + off(); + } finally { + globalThis.setInterval = real; + } + }); + it('a handle without unref() is tolerated', () => { const real = globalThis.setInterval; let ref: unknown; diff --git a/packages/trackers/src/node/process-tracker.ts b/packages/trackers/src/node/process-tracker.ts index 7868a5ee..4326e0a9 100644 --- a/packages/trackers/src/node/process-tracker.ts +++ b/packages/trackers/src/node/process-tracker.ts @@ -46,7 +46,11 @@ import { // numbers are not true. The platform GATES (`measures*`) are runtime-identity facts the composition root passes in; // the tracker only honours them. An injected source/reader always wins over its gate. // -// SINGLETON per key object (see `processTrackerFor`: the `process` object by default). RETENTION rule β€” what survives +// SINGLETON per key object (see `processTrackerFor`: the `process` object by default). SEAMS MERGE, NEVER DROP: the +// tracker outlives launches, so a later launch that omits `scheduler`/`onError`/a reader KEEPS the previous launch's +// (it can replace a seam, never shed one). Merely BUILDING a producer set (`createNodeSystemTraceProducers`) rebinds +// the shared tracker, so a Bun/Deno default set built before `...options` in their launch.ts already hands its seams over. +// Tests that inject fakes must use a private `key` or call `resetProcessTracker()`. RETENTION rule β€” what survives // a stage's last unsubscribe: ONLY the resolved seams, and the "this runtime refused" memory inside the guarded // sources (a refusing histogram/observer is not hammered again until a rebind swaps the seams). Everything windowed // starts FRESH on the next subscription: the CPU baseline, the ELU baseline, the last-emitted samples @@ -252,9 +256,9 @@ export class ProcessTracker extends InterceptorBase { /** * The latest reading of `stage`. Stateless stages are read LIVE (guarded: undefined when the runtime cannot answer * or the read threw, which is reported). A WINDOWED stage (cpu, eventLoop, utilization, gc) cannot be re-read - * without consuming its window, so it answers the last sample of the current run: `cpu` is seeded with a - * zero-length window the moment it arms (so a producer has a baseline), the others are undefined until their first - * tick; all are undefined while the stage is not armed. + * without consuming its window, so it answers the last sample of the current run: undefined until the first + * tick (a baseline would be a made-up reading: a zero-length window has no CPU share to report), and undefined + * while the stage is not armed. */ current(stage: S): ProcessEvents[S] | undefined { if (WINDOWED.has(stage)) { @@ -304,7 +308,6 @@ export class ProcessTracker extends InterceptorBase { try { const run = this.#makeRun(stage); this.#armed.set(stage, run); - if (stage === 'cpu') this.#last.set(stage, { userDelta: 0, systemDelta: 0, processPct: 0 }); } catch (error) { this.#onError(error); // left unarmed: retried on the next listener change / rebind } @@ -361,7 +364,9 @@ export class ProcessTracker extends InterceptorBase { } #tick(): void { + const gen = this.#gen; for (const stage of [...this.#armed.keys()]) { + if (gen !== this.#gen) return; // a listener tore this run down (or rebound the seams) mid-tick const run = this.#armed.get(stage); // a listener may have removed it mid-tick if (run === undefined) continue; let value: unknown; @@ -470,6 +475,10 @@ export class ProcessTracker extends InterceptorBase { // Read BEFORE any baseline moves: a throw here fails this read and must not advance the CPU window. const cpu = cpuUsage(); const wall = nowMs(); + // `os.cpus()` can be empty (some containers/Android): a share of "no cores" is unknowable, so omit the sample + // rather than emit Infinity/NaN. Checked before the baseline moves. + const cores = cpuCount(); + if (!(cores >= 1)) return undefined; const userDelta = cpu.user - last.user; const systemDelta = cpu.system - last.system; const wallMsDelta = wall - lastWallMs; @@ -477,9 +486,7 @@ export class ProcessTracker extends InterceptorBase { lastWallMs = wall; // Normalized process CPU %: busy-Β΅s / wall-Β΅s / cores * 100. Guard the zero-window first sample. const processPct = - wallMsDelta > 0 - ? ((userDelta + systemDelta) / (wallMsDelta * 1000) / cpuCount()) * 100 - : 0; + wallMsDelta > 0 ? ((userDelta + systemDelta) / (wallMsDelta * 1000) / cores) * 100 : 0; return { userDelta, systemDelta, processPct }; }, stop: () => {}, From b762e36f407e1dc651485bae5798ac8aa74e248c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 01:23:05 +0500 Subject: [PATCH 3/3] test(node): deterministic cpuCount seam in the ProcessTracker registry launch test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit πŸ€– Generated with [Claude Code](https://claude.com/claude-code) --- packages/node/src/launch.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index 3544903e..4a74eadc 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -1374,6 +1374,9 @@ function seedPriorGeneration( describe('launch β€” system trace producers', () => { it('the default producers go through the per-process ProcessTracker registry accessor', async () => { const fs = fakeScheduler(); + // Deterministic core count: the real os.cpus() can be empty (some containers), which omits the cpu sample. The + // launch's rebind merges, so this seam survives it. + processTrackerFor({ cpuCount: () => 2 }); launchTracked( 'tok', baseOptions({