Repository navigation
perf_hooks: add node:perf_hooks/pprof time profiler - #67779
jsumners-nr wants to merge 4 commits into
Conversation
Add an experimental node:perf_hooks/pprof module that collects wall time profiles of the current thread and encodes them in the pprof format, so that they can be consumed by the pprof command-line tool and continuous profiling services without a native addon. The wall time profiler is ported from @datadog/pprof (Apache-2.0): the native profiler now lives in src/node_pprof.cc and src/pprof/ on top of Node.js internals instead of nan, and the JavaScript in lib/internal/perf/pprof/. The pprof protobuf encoder is ported from the pprof-format package (MIT). Both licenses are added to LICENSE. Profiles can optionally attribute thread CPU time to samples on POSIX systems, by intercepting the SIGPROF signals of V8's sampler, which is also used to work around a V8 bug that can leave the profiler stuck when it is restarted. The heap profiler, sampling contexts and source map support of @datadog/pprof are not included. The module emits an ExperimentalWarning when loaded. Assisted-by: Claude Code Signed-off-by: James Sumners <jsumners@newrelic.com>
|
@bengl are you ok? |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #67779 +/- ##
==========================================
+ Coverage 90.54% 90.56% +0.01%
==========================================
Files 801 820 +19
Lines 284215 288700 +4485
Branches 54889 55511 +622
==========================================
+ Hits 257340 261456 +4116
- Misses 17034 17267 +233
- Partials 9841 9977 +136
🚀 New features to boost your workflow:
|
Fetch the pprof-format LICENSE and NOTICE into separate variables, so that the command substitutions are not embedded in a larger string. Assisted-by: Claude Code Signed-off-by: James Sumners <jsumners@newrelic.com>
When `time.profile()` finished, it stopped whichever profiler was running, so a profiler that another caller started in the meantime was stopped and its profile returned. It now rejects with `ERR_INVALID_STATE` when the profiler that it started was stopped before the duration elapsed. Add tests for `time.profile()`, the heap snapshot of `WallProfiler`, and protobuf encoding cases that were not covered. Assisted-by: Claude Code Signed-off-by: James Sumners <jsumners@newrelic.com>
| * payload lengths of the message and of its fields are recorded in. | ||
| * @returns {number} The number of bytes that the field takes. | ||
| */ | ||
| function measureMessageField(field, message, context) { |
There was a problem hiding this comment.
protobufjs has removed the two-pass encoder and only use a single-pass writer. It was proven that the measurement does not give much and it can be more than 30% faster without the measurement.
The go pprof impl has a same simple writer: https://github.com/golang/go/blob/master/src/runtime/pprof/protobuf.go.
A started `WallProfiler` is held strongly until it is stopped, so a process that exits with the time profiler running failed the `--verify-base-objects` check that debug builds enable by default. Report the profiler as not indicative of a memory leak at exit, and verify base objects in the exit test. Assisted-by: Claude Code Signed-off-by: James Sumners <jsumners@newrelic.com>
| thread additionally report the CPU time of the threads that do not run | ||
| JavaScript, as [`pprof.time.constants.NON_JS_THREADS_FUNCTION_NAME`][]. Not | ||
| supported on Windows, nor with `lineNumbers`. **Default:** `false`. | ||
| * `workaroundV8Bug` {boolean} When `true`, works around a V8 bug that can |
There was a problem hiding this comment.
Which V8 bug? This does not seem to be a good fit in the public API option. Please add a link to V8 issue tracker and document a TODO instead.
There was a problem hiding this comment.
There was a problem hiding this comment.
Yes, I know this was port from pprof-nodejs. I mean DataDog/pprof-nodejs#125 has no linked V8 issue, and I don't think Node.js core should do this. We should figure out which V8 issue and not exposing an API named like workaroundV8Bug.
| case CollectionMode::kNoCollect: | ||
| // Drop the sample, and let WaitForSignal() know that a signal arrived. | ||
| no_collect_call_count_.fetch_add(1, std::memory_order_relaxed); | ||
| return; |
There was a problem hiding this comment.
With https://chromium-review.googlesource.com/c/v8/v8/+/8612887 soon arriving in V8 15.9, V8 must be called on every SIGPROF signal. I think we should not workaround V8 profiler in the node core.
👋 This PR starts the process of natively supporting profiling in the runtime. This is a port of the
@datadog/pprofmodule. This specific PR limits the implementation to profiling the CPU wall time. Heap and context/label sampling, and source map support are left for subsequent PRs.@mcollina and I discussed this at the OpenJSF conference in 2025. We agreed that this sort of thing should be provided by the runtime. In support of that assertion, I instructed Claude to review the dependents of the
@datadog/pprofmodule and generate a report of how it is used across the ecosystem. This is what it came up with:Ecosystem Report
How
@datadog/pprofis used across the JavaScript observability ecosystemData collected 2026-11-25. Sources:
@datadog/pprof;api.npmjs.org, for the last week;latestmanifest of each package;@datadog/pprofAPIs it calls.Scale
@datadog/pprofis downloaded about 17.6 million times a week.dd-trace, because it declares@datadog/pprofas anoptionalDependency. At about 15.2 million downloads a week,dd-traceaccounts for most of the module's installs.Who uses it
dd-trace(Datadog)@pyroscope/nodejs(Grafana)@polarsignals/pprof(Polar Signals)@platformatic/flame(Platformatic)@coralogix/opentelemetry-profiling(Coralogix)@platformatic/wattpm-pprof-capture,@platformatic/watt-extra(Platformatic)harperdb,@harperfast/harper-pro(Harper)@rsdk/profiling.common(R-Vision)flamegraph-middleware,express-pprof-middleware(Tesla)time.profile(), heap profiler, encoding@beacon-observability/profiler-nodejs,@cloudcare/profiler-nodejspprof-itThe remaining dependents each get fewer than 100 downloads a week:
dd-trace(dd-trace-andreas,dd-trace-sbs-dl,@e-one/dd-trace,trace-ts);@rudderstack/pyroscope-nodejs,rudderstack-pyroscope-nodejs,@popfendicollars/pyroscope-nodejs);@beincom/node-profile,@cornie-js/backend-monitoring,@yoniplayground/o11y,@swapnil454/tracepilot,perf-skill);@chatlayer/tracer, which still pins the obsolete^0.1.3.Observations
It's the de facto Node.js profiler, beyond Datadog. Competing vendors ship it inside their own agents: Grafana Pyroscope, Polar Signals and Coralogix. So do runtimes and platforms (Platformatic, Harper) and tools that expose pprof endpoints. None of the other major vendors checked has a replacement:
@sentry/node-cpu-profiler.DataDog/pprof-nodejsas prior art.Everyone depends on one native addon. Each consumer inherits its prebuilt binaries, nan, and V8 workarounds that are specific to each Node.js major version. Several consumers pin exact versions, for example:
@pyroscope/nodejspins5.14.4;@platformatic/flameandharperdbpin5.15.1;5.4.1.So the ecosystem gets fixes and new Node.js support unevenly.
The wall time profiler is the common core. Almost every agent and tool calls
time.start()/time.stop()ortime.profile(), then encodes the result as pprof. That's the partnode:perf_hooks/pprofprovides.Many consumers also use features this port leaves out. The tarball search shows how often each one appears:
SourceMapper): most dependents;pprof-it;withContexts,useCPED,time.setContext): Datadog, Pyroscope, Coralogix, R-Vision and Beacon.These features decide how many consumers could move to the core module without also keeping the addon.
A few caveats:
Additionally, Sentry has their own native module to accomplish the same goal:
I have reviewed all of the JavaScript code in this PR, mainly coercing useful jsdoc into the code. Everything seems reasonable to me. But I am unable to provide insight into the C++ code, as my knowledge there is basically zero. The C++ code was heavily rewritten, though. The original upstream code relied on Nan and node-gyp. By directly integrating this functionality into core, we are able to skip those requirements. I asked Claude for a description of what it changed, and it reported:
C++ Port Details
It was modified heavily. The C++ is a port of the upstream design and algorithms, rewritten against Node.js internals; very little was copied as is. I compared it with upstream at the commit it was ported from, 3905f38, just now.
Size and overlap
What changed
Why the upstream headers stay
Because the logic is derived from upstream, the files keep the Apache-2.0 copyright headers, with a "Modified for inclusion in Node.js core" notice and a pinned link to what each was ported from. tools/license-builder.sh adds the license to LICENSE. That attribution is required whatever the amount of verbatim text.
The overlap figure is a rough line-level measure, not a formal similarity analysis, and I didn't compare the files line by line.
Claude Code Description
Adds an experimental
node:perf_hooks/pprofmodule. It collects wall time profiles of the current thread and encodes them in the pprof format, so they can be used with thepprofcommand-line tool and continuous profiling services without a native addon. Loading the module emits anExperimentalWarning; there is no flag.Where it comes from
@datadog/pprof(Apache-2.0).src/node_pprof.ccandsrc/pprof/, built on Node.js internals instead of nan and node-gyp.lib/internal/perf/pprof/.pprof-format(MIT). Only the encoding half is included.LICENSEthroughtools/license-builder.sh.API
time.start([options]),time.stop([restart])andtime.isStarted().time.profile([options]), which profiles fordurationMillisand can be stopped early with anAbortSignal.time.v8ProfilerStuckEventLoopDetected()andtime.constants.encode(profile)andencodeSync(profile), which return a gzip-compressed pprofBuffer.@datadog/pprofare kept (intervalMicros,durationMillis,lineNumbers,collectCpuTime,workaroundV8Bug) so users can migrate easily.On POSIX systems,
collectCpuTimeattributes the thread's CPU time to samples by intercepting theSIGPROFsignals of V8's sampler. The same interception works around a V8 bug that can leave the CPU profiler stuck when it is restarted. If restarting after that bug fails,stop(true)still returns the profile and leaves the profiler stopped.The profiler owns its own
v8::CpuProfiler, so it can run alongsidev8.startCpuProfile()and the inspector'sProfilerdomain. It refuses to start while a startup snapshot is being built.Not included
Tests
test/parallel/test-perf-hooks-pprof-*.jscover:v8.startCpuProfile()and the inspector;test/cctest/test_pprof.cccovers sample attribution, the thread CPU clock and signal chaining.test/common/pprof.jsis a minimal pprof decoder, written independently of the encoder, so that tests check the encoded bytes. It also providespprofTestBusyLoop(), a loop bounded by CPU time rather than wall time, so that it gets about as many samples on a loaded machine as on an idle one.Docs
pprof APIsection indoc/api/perf_hooks.md.type-map.jsonentry forpprof.Profile.🤖 Generated with Claude Code