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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/node-process-tracker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@bugsee/node': minor
'@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 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.
3 changes: 2 additions & 1 deletion docs/PROGRESS.md

Large diffs are not rendered by default.

36 changes: 34 additions & 2 deletions packages/bun/src/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -96,6 +102,7 @@ beforeEach(() => {
const clients: Array<{ stop: (t?: number) => Promise<boolean> }> = [];
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 = <T extends { stop: (t?: number) => Promise<boolean> }>(c: T): T => {
Expand All @@ -119,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)', () => {
Expand Down Expand Up @@ -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');
});
});
36 changes: 34 additions & 2 deletions packages/deno/src/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -98,6 +104,7 @@ beforeEach(() => {
const clients: Array<{ stop: (t?: number) => Promise<boolean> }> = [];
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 = <T extends { stop: (t?: number) => Promise<boolean> }>(c: T): T => {
Expand Down Expand Up @@ -328,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);
});
Expand Down Expand Up @@ -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');
});
});
3 changes: 2 additions & 1 deletion packages/elysia/src/elysia-integration.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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__;
});

Expand Down
3 changes: 2 additions & 1 deletion packages/node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand Down
8 changes: 7 additions & 1 deletion packages/node/src/event-loop-watchdog.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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() {
Expand Down
3 changes: 2 additions & 1 deletion packages/node/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ const EXPECTED_EXPORTS = [
'createNodeRequestContextStore',
'createNodeSystemEventsSource',
'createNodeSystemTraceProducers',
'ProcessStatsTracker',
'createProfilingController',
'createRequestScopedActiveSpanStore',
'createUncaughtExceptionProvider',
Expand All @@ -63,6 +62,8 @@ const EXPECTED_EXPORTS = [
'neverThrow',
'openServerContext',
'openServerRequest',
'processTrackerFor',
'resetProcessTracker',
'realSystemProbe',
'runServerRequest',
'sanitizeHardwareGpu',
Expand Down
13 changes: 7 additions & 6 deletions packages/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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';
51 changes: 51 additions & 0 deletions packages/node/src/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -176,6 +177,7 @@ const clients: ReturnType<typeof launch>[] = [];
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__;
Expand Down Expand Up @@ -1370,6 +1372,55 @@ 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({
captureStore: memStore(),
clock: fixedClock,
scheduler: fs.scheduler,
systemMetricsSampler: undefined,
}),
);
// 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')).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);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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<typeof fakeScheduler>) => {
const calls: string[] = [];
const perfHooks = {
Expand Down
8 changes: 7 additions & 1 deletion packages/node/src/local-variables.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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<string, readonly unknown[]> = {}) {
const posts: Array<{ method: string; params?: unknown }> = [];
let paused: ((message: { params: unknown }) => void) | undefined;
Expand Down
Loading