Skip to content

Commit abaee7d

Browse files
authored
v8: add heap profiling setSampleInterval
Signed-off-by: ishabi <ilyasshabi94@gmail.com> PR-URL: #67626 Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent c58ccfa commit abaee7d

14 files changed

Lines changed: 554 additions & 10 deletions

File tree

‎doc/api/errors.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1528,6 +1528,13 @@ file in chunks.
15281528
The number of file system events queued without being handled exceeded the size specified in
15291529
`maxQueue` in `fs.watch()`.
15301530

1531+
<a id="ERR_HEAP_PROFILE_NOT_STARTED"></a>
1532+
1533+
### `ERR_HEAP_PROFILE_NOT_STARTED`
1534+
1535+
An operation was attempted on a heap profile that has not been started or has
1536+
already been stopped or disposed.
1537+
15311538
<a id="ERR_HTTP2_ALTSVC_INVALID_ORIGIN"></a>
15321539

15331540
### `ERR_HTTP2_ALTSVC_INVALID_ORIGIN`

‎doc/api/v8.md‎

Lines changed: 94 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1618,6 +1618,62 @@ added: v26.1.0
16181618
16191619
> Stability: 1 - Experimental
16201620
1621+
### `syncHeapProfileHandle.getSamples()`
1622+
1623+
<!-- YAML
1624+
added: REPLACEME
1625+
-->
1626+
1627+
* Returns: {Object\[]}
1628+
* `size` {number} Estimated total allocation size in bytes, equal to
1629+
`objectSize * objectCount`.
1630+
* `objectSize` {number} Size of the sampled object in bytes.
1631+
* `objectCount` {number} Estimated number of objects represented by the sample.
1632+
* `nodeId` {number} Identifier of the allocation's node in the profile call tree.
1633+
* `ordinal` {number} Unique, time-ordered identifier of the sample.
1634+
* `isLive` {boolean} Whether the sampled object is still live.
1635+
* `sampleInterval` {number} Sampling interval in bytes used when the sample
1636+
was selected.
1637+
1638+
Returns the currently retained allocation samples without stopping profiling or
1639+
building the full profile call tree and resolving its script metadata. The sample
1640+
fields match those in the JSON returned by `stop()`. Use `ordinal` to identify
1641+
samples across calls; array order is unspecified.
1642+
1643+
Live allocation samples are available with the default profiling options.
1644+
To also retain samples after their objects are collected, enable
1645+
`includeObjectsCollectedByMajorGC` or `includeObjectsCollectedByMinorGC` when
1646+
starting the profile. These samples have `isLive` set to `false`. The `forceGC`
1647+
option also applies to `getSamples()`.
1648+
1649+
Throws `ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or disposed.
1650+
1651+
### `syncHeapProfileHandle.setSampleInterval(sampleInterval)`
1652+
1653+
<!-- YAML
1654+
added: REPLACEME
1655+
-->
1656+
1657+
* `sampleInterval` {integer} Average sampling interval in bytes. Must be between
1658+
`1` and `Number.MAX_SAFE_INTEGER`, inclusive.
1659+
1660+
Updates the sampling interval for future sample scheduling without restarting
1661+
profiling or discarding existing samples. A larger interval reduces sampling
1662+
frequency. Each sample retains the `sampleInterval` used when it was selected.
1663+
1664+
Throws `ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or disposed.
1665+
1666+
```cjs
1667+
const v8 = require('node:v8');
1668+
1669+
const handle = v8.startHeapProfile({ sampleInterval: 1024 });
1670+
// Run the workload to profile.
1671+
const samples = handle.getSamples();
1672+
handle.setSampleInterval(4096);
1673+
// Continue profiling with less frequent sampling.
1674+
const profile = handle.stop();
1675+
```
1676+
16211677
### `syncHeapProfileHandle.stop()`
16221678
16231679
<!-- YAML
@@ -1634,7 +1690,9 @@ fields, the following are added:
16341690
16351691
* Each node reports `selfCount`, the number of sampled objects allocated by the
16361692
node (`selfSize` is the existing total in bytes).
1637-
* Each sample reports `objectSize`, `objectCount`, and `isLive`.
1693+
* Each sample reports `objectSize`, `objectCount`, `isLive`, and `sampleInterval`.
1694+
`sampleInterval` records the sampling interval in bytes used when the sample
1695+
was selected, even if the interval was subsequently changed.
16381696
16391697
The DevTools `size` field stays `objectSize * objectCount` for compatibility.
16401698
@@ -1679,6 +1737,40 @@ Stopping collecting the profile and the profile will be discarded.
16791737
added: v24.9.0
16801738
-->
16811739
1740+
### `heapProfileHandle.getSamples()`
1741+
1742+
<!-- YAML
1743+
added: REPLACEME
1744+
-->
1745+
1746+
* Returns: {Promise} Fulfills with an {Object\[]} of allocation samples.
1747+
1748+
Asynchronously retrieves the worker's retained allocation samples without
1749+
stopping profiling or building the full profile call tree. The sample fields and
1750+
profiling options are described in
1751+
[`syncHeapProfileHandle.getSamples()`][].
1752+
1753+
Rejects with `ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or
1754+
disposed, or `ERR_WORKER_NOT_RUNNING` if the worker is no longer running.
1755+
1756+
### `heapProfileHandle.setSampleInterval(sampleInterval)`
1757+
1758+
<!-- YAML
1759+
added: REPLACEME
1760+
-->
1761+
1762+
* `sampleInterval` {integer} Average sampling interval in bytes. Must be between
1763+
`1` and `Number.MAX_SAFE_INTEGER`, inclusive.
1764+
* Returns: {Promise} Fulfills with `undefined` after the interval is updated.
1765+
1766+
Asynchronously updates the worker's sampling interval for future sample
1767+
scheduling without restarting profiling or discarding existing samples. Each
1768+
sample retains the `sampleInterval` used when it was selected.
1769+
1770+
Invalid arguments throw synchronously. The returned promise rejects with
1771+
`ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or disposed, or
1772+
`ERR_WORKER_NOT_RUNNING` if the worker is no longer running.
1773+
16821774
### `heapProfileHandle.stop()`
16831775
16841776
<!-- YAML
@@ -1930,6 +2022,7 @@ must be a positive integer.
19302022
[`serializer.transferArrayBuffer()`]: #serializertransferarraybufferid-arraybuffer
19312023
[`serializer.writeRawBytes()`]: #serializerwriterawbytesbuffer
19322024
[`settled` callback]: #settledpromise
2025+
[`syncHeapProfileHandle.getSamples()`]: #syncheapprofilehandlegetsamples
19332026
[`v8.setHeapSnapshotNearHeapLimit()`]: #v8setheapsnapshotnearheaplimitlimit
19342027
[`v8.startHeapProfile()`]: #v8startheapprofileoptions
19352028
[`v8.stopCoverage()`]: #v8stopcoverage

‎lib/internal/errors.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1257,6 +1257,7 @@ E('ERR_FS_CP_UNKNOWN', 'Cannot copy an unknown file type', SystemError);
12571257
E('ERR_FS_EISDIR', 'Path is a directory', SystemError, HideStackFramesError);
12581258
E('ERR_FS_FILE_TOO_LARGE', 'File size (%s) is greater than 2 GiB', RangeError);
12591259
E('ERR_FS_WATCH_QUEUE_OVERFLOW', 'fs.watch() queued more than %d events', Error);
1260+
E('ERR_HEAP_PROFILE_NOT_STARTED', 'Heap profile not started', Error);
12601261
E('ERR_HTTP2_ALTSVC_INVALID_ORIGIN',
12611262
'HTTP/2 ALTSVC frames require a valid origin', TypeError);
12621263
E('ERR_HTTP2_ALTSVC_LENGTH',

‎lib/internal/worker.js‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
NumberMAX_SAFE_INTEGER,
1313
ObjectEntries,
1414
Promise,
15+
PromiseReject,
1516
PromiseResolve,
1617
PromiseWithResolvers,
1718
ReflectApply,
@@ -33,6 +34,7 @@ const path = require('path');
3334
const errorCodes = require('internal/errors').codes;
3435
const {
3536
ERR_WORKER_NOT_RUNNING,
37+
ERR_HEAP_PROFILE_NOT_STARTED,
3638
ERR_WORKER_PATH,
3739
ERR_WORKER_UNSERIALIZABLE_ERROR,
3840
ERR_WORKER_INVALID_EXEC_ARGV,
@@ -65,6 +67,7 @@ const {
6567
validateString,
6668
validateObject,
6769
validateNumber,
70+
validateInteger,
6871
} = require('internal/validators');
6972
const {
7073
throwIfBuildingSnapshot,
@@ -175,6 +178,35 @@ class HeapProfileHandle {
175178
this.#worker = worker;
176179
}
177180

181+
setSampleInterval(sampleInterval) {
182+
validateInteger(sampleInterval, 'sampleInterval', 1);
183+
if (this.#promise) {
184+
return PromiseReject(new ERR_HEAP_PROFILE_NOT_STARTED());
185+
}
186+
const taker = this.#worker[kHandle]?.setHeapProfileSampleInterval(sampleInterval);
187+
return new Promise((resolve, reject) => {
188+
if (!taker) return reject(new ERR_WORKER_NOT_RUNNING());
189+
taker.ondone = (err) => {
190+
if (err) return reject(err);
191+
resolve();
192+
};
193+
});
194+
}
195+
196+
getSamples() {
197+
if (this.#promise) {
198+
return PromiseReject(new ERR_HEAP_PROFILE_NOT_STARTED());
199+
}
200+
const taker = this.#worker[kHandle]?.getHeapProfileSamples();
201+
return new Promise((resolve, reject) => {
202+
if (!taker) return reject(new ERR_WORKER_NOT_RUNNING());
203+
taker.ondone = (err, samples) => {
204+
if (err) return reject(err);
205+
resolve(samples);
206+
};
207+
});
208+
}
209+
178210
stop() {
179211
if (this.#promise) {
180212
return this.#promise;

‎lib/v8.js‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ const {
4242
validateString,
4343
validateOneOf,
4444
validateUint32,
45+
validateInteger,
4546
} = require('internal/validators');
4647
const {
4748
Serializer,
@@ -70,6 +71,7 @@ if (hasInspector) {
7071
const assert = require('internal/assert');
7172
const {
7273
codes: {
74+
ERR_HEAP_PROFILE_NOT_STARTED,
7375
ERR_INVALID_STATE,
7476
},
7577
} = require('internal/errors');
@@ -133,6 +135,8 @@ const {
133135
stopCpuProfile: _stopCpuProfile,
134136
startHeapProfile: _startHeapProfile,
135137
stopHeapProfile: _stopHeapProfile,
138+
setHeapProfileSampleInterval: _setHeapProfileSampleInterval,
139+
getHeapProfileSamples: _getHeapProfileSamples,
136140
isStringOneByteRepresentation: _isStringOneByteRepresentation,
137141
updateHeapStatisticsBuffer,
138142
updateHeapSpaceStatisticsBuffer,
@@ -213,6 +217,21 @@ class SyncCPUProfileHandle {
213217
class SyncHeapProfileHandle {
214218
#stopped = false;
215219

220+
setSampleInterval(sampleInterval) {
221+
validateInteger(sampleInterval, 'sampleInterval', 1);
222+
if (this.#stopped) {
223+
throw new ERR_HEAP_PROFILE_NOT_STARTED();
224+
}
225+
_setHeapProfileSampleInterval(sampleInterval);
226+
}
227+
228+
getSamples() {
229+
if (this.#stopped) {
230+
throw new ERR_HEAP_PROFILE_NOT_STARTED();
231+
}
232+
return _getHeapProfileSamples();
233+
}
234+
216235
stop() {
217236
if (this.#stopped) {
218237
return;

‎src/env_properties.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,7 @@
425425
V(free_list_statistics_template, v8::DictionaryTemplate) \
426426
V(fsreqpromise_constructor_template, v8::ObjectTemplate) \
427427
V(handle_wrap_ctor_template, v8::FunctionTemplate) \
428+
V(heap_profile_sample_template, v8::DictionaryTemplate) \
428429
V(heap_statistics_template, v8::DictionaryTemplate) \
429430
V(v8_heap_statistics_template, v8::DictionaryTemplate) \
430431
V(histogram_ctor_template, v8::FunctionTemplate) \

‎src/node_profiling.cc‎

Lines changed: 66 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,31 @@
11
#include "node_profiling.h"
22

3+
#include "env-inl.h"
34
#include "json_utils.h"
4-
#include "util.h"
5+
#include "util-inl.h"
56

67
#include <memory>
8+
#include <string_view>
79

810
namespace node {
911

1012
using v8::AllocationProfile;
13+
using v8::Array;
14+
using v8::Boolean;
15+
using v8::Context;
16+
using v8::DictionaryTemplate;
17+
using v8::FunctionCallbackInfo;
1118
using v8::HandleScope;
1219
using v8::HeapProfiler;
20+
using v8::Int32;
21+
using v8::Integer;
1322
using v8::Isolate;
23+
using v8::Local;
24+
using v8::LocalVector;
25+
using v8::MaybeLocal;
26+
using v8::Number;
27+
using v8::Object;
28+
using v8::Uint32;
1429
using v8::Value;
1530

1631
static void BuildHeapProfileNode(Isolate* isolate,
@@ -64,6 +79,7 @@ bool SerializeHeapProfile(Isolate* isolate, std::string& out) {
6479
writer.json_keyvalue("nodeId", sample.node_id);
6580
writer.json_keyvalue("ordinal", static_cast<double>(sample.sample_id));
6681
writer.json_keyvalue("isLive", sample.is_live);
82+
writer.json_keyvalue("sampleInterval", sample.sample_interval);
6783
writer.json_end();
6884
}
6985
writer.json_arrayend();
@@ -76,38 +92,79 @@ bool SerializeHeapProfile(Isolate* isolate, std::string& out) {
7692
return true;
7793
}
7894

95+
MaybeLocal<Array> HeapProfileSamplesToV8Value(
96+
Isolate* isolate,
97+
Local<Context> context,
98+
const std::vector<AllocationProfile::Sample>& samples) {
99+
Environment* env = Environment::GetCurrent(context);
100+
auto tmpl = env->heap_profile_sample_template();
101+
if (tmpl.IsEmpty()) {
102+
static constexpr std::string_view names[] = {
103+
"size",
104+
"objectSize",
105+
"objectCount",
106+
"nodeId",
107+
"ordinal",
108+
"isLive",
109+
"sampleInterval",
110+
};
111+
tmpl = DictionaryTemplate::New(isolate, names);
112+
env->set_heap_profile_sample_template(tmpl);
113+
}
114+
LocalVector<Value> result(isolate);
115+
result.reserve(samples.size());
116+
for (const auto& sample : samples) {
117+
MaybeLocal<Value> values[] = {
118+
Number::New(isolate, sample.size * sample.count),
119+
Number::New(isolate, sample.size),
120+
Integer::NewFromUnsigned(isolate, sample.count),
121+
Integer::NewFromUnsigned(isolate, sample.node_id),
122+
Number::New(isolate, static_cast<double>(sample.sample_id)),
123+
Boolean::New(isolate, sample.is_live),
124+
Number::New(isolate, static_cast<double>(sample.sample_interval)),
125+
};
126+
Local<Object> object;
127+
if (!NewDictionaryInstanceNullProto(context, tmpl, values)
128+
.ToLocal(&object)) {
129+
return {};
130+
}
131+
result.emplace_back(object);
132+
}
133+
return Array::New(isolate, result.data(), result.size());
134+
}
135+
79136
HeapProfileOptions ParseHeapProfileOptions(
80-
const v8::FunctionCallbackInfo<Value>& args) {
137+
const FunctionCallbackInfo<Value>& args) {
81138
HeapProfileOptions options;
82139
CHECK_LE(args.Length(), 3);
83140
if (args.Length() > 0) {
84141
CHECK(args[0]->IsNumber());
85142
options.sample_interval =
86-
static_cast<uint64_t>(args[0].As<v8::Number>()->Value());
143+
static_cast<uint64_t>(args[0].As<Number>()->Value());
87144
}
88145
if (args.Length() > 1) {
89146
CHECK(args[1]->IsInt32());
90-
options.stack_depth = args[1].As<v8::Int32>()->Value();
147+
options.stack_depth = args[1].As<Int32>()->Value();
91148
}
92149
if (args.Length() > 2) {
93150
CHECK(args[2]->IsUint32());
94-
options.flags = static_cast<v8::HeapProfiler::SamplingFlags>(
95-
args[2].As<v8::Uint32>()->Value());
151+
options.flags =
152+
static_cast<HeapProfiler::SamplingFlags>(args[2].As<Uint32>()->Value());
96153
}
97154
return options;
98155
}
99156

100157
CpuProfileOptions ParseCpuProfileOptions(
101-
const v8::FunctionCallbackInfo<Value>& args) {
158+
const FunctionCallbackInfo<Value>& args) {
102159
CpuProfileOptions options;
103160
CHECK_LE(args.Length(), 2);
104161
if (args.Length() > 0) {
105162
CHECK(args[0]->IsInt32());
106-
options.sampling_interval_us = args[0].As<v8::Int32>()->Value();
163+
options.sampling_interval_us = args[0].As<Int32>()->Value();
107164
}
108165
if (args.Length() > 1) {
109166
CHECK(args[1]->IsUint32());
110-
options.max_samples = args[1].As<v8::Uint32>()->Value();
167+
options.max_samples = args[1].As<Uint32>()->Value();
111168
}
112169
return options;
113170
}

0 commit comments

Comments
 (0)