Commit abaee7dbade for nodejs

commit abaee7dbadee274fa560b95d8b9f5a071f4a8a5b
Author: Ilyas Shabi <ilyasshabi94@gmail.com>
Date:   Sat Nov 28 07:24:11 2026 +0100

    v8: add heap profiling setSampleInterval

    Signed-off-by: ishabi <ilyasshabi94@gmail.com>
    PR-URL: https://github.com/nodejs/node/pull/67626
    Reviewed-By: James M Snell <jasnell@gmail.com>

diff --git a/doc/api/errors.md b/doc/api/errors.md
index 0d621087bd4..6948ada70cf 100644
--- a/doc/api/errors.md
+++ b/doc/api/errors.md
@@ -1528,6 +1528,13 @@ file in chunks.
 The number of file system events queued without being handled exceeded the size specified in
 `maxQueue` in `fs.watch()`.

+<a id="ERR_HEAP_PROFILE_NOT_STARTED"></a>
+
+### `ERR_HEAP_PROFILE_NOT_STARTED`
+
+An operation was attempted on a heap profile that has not been started or has
+already been stopped or disposed.
+
 <a id="ERR_HTTP2_ALTSVC_INVALID_ORIGIN"></a>

 ### `ERR_HTTP2_ALTSVC_INVALID_ORIGIN`
diff --git a/doc/api/v8.md b/doc/api/v8.md
index 2517866581e..85785b65cf3 100644
--- a/doc/api/v8.md
+++ b/doc/api/v8.md
@@ -1618,6 +1618,62 @@ added: v26.1.0

 > Stability: 1 - Experimental

+### `syncHeapProfileHandle.getSamples()`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+* Returns: {Object\[]}
+  * `size` {number} Estimated total allocation size in bytes, equal to
+    `objectSize * objectCount`.
+  * `objectSize` {number} Size of the sampled object in bytes.
+  * `objectCount` {number} Estimated number of objects represented by the sample.
+  * `nodeId` {number} Identifier of the allocation's node in the profile call tree.
+  * `ordinal` {number} Unique, time-ordered identifier of the sample.
+  * `isLive` {boolean} Whether the sampled object is still live.
+  * `sampleInterval` {number} Sampling interval in bytes used when the sample
+    was selected.
+
+Returns the currently retained allocation samples without stopping profiling or
+building the full profile call tree and resolving its script metadata. The sample
+fields match those in the JSON returned by `stop()`. Use `ordinal` to identify
+samples across calls; array order is unspecified.
+
+Live allocation samples are available with the default profiling options.
+To also retain samples after their objects are collected, enable
+`includeObjectsCollectedByMajorGC` or `includeObjectsCollectedByMinorGC` when
+starting the profile. These samples have `isLive` set to `false`. The `forceGC`
+option also applies to `getSamples()`.
+
+Throws `ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or disposed.
+
+### `syncHeapProfileHandle.setSampleInterval(sampleInterval)`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+* `sampleInterval` {integer} Average sampling interval in bytes. Must be between
+  `1` and `Number.MAX_SAFE_INTEGER`, inclusive.
+
+Updates the sampling interval for future sample scheduling without restarting
+profiling or discarding existing samples. A larger interval reduces sampling
+frequency. Each sample retains the `sampleInterval` used when it was selected.
+
+Throws `ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or disposed.
+
+```cjs
+const v8 = require('node:v8');
+
+const handle = v8.startHeapProfile({ sampleInterval: 1024 });
+// Run the workload to profile.
+const samples = handle.getSamples();
+handle.setSampleInterval(4096);
+// Continue profiling with less frequent sampling.
+const profile = handle.stop();
+```
+
 ### `syncHeapProfileHandle.stop()`

 <!-- YAML
@@ -1634,7 +1690,9 @@ fields, the following are added:

 * Each node reports `selfCount`, the number of sampled objects allocated by the
   node (`selfSize` is the existing total in bytes).
-* Each sample reports `objectSize`, `objectCount`, and `isLive`.
+* Each sample reports `objectSize`, `objectCount`, `isLive`, and `sampleInterval`.
+  `sampleInterval` records the sampling interval in bytes used when the sample
+  was selected, even if the interval was subsequently changed.

 The DevTools `size` field stays `objectSize * objectCount` for compatibility.

@@ -1679,6 +1737,40 @@ Stopping collecting the profile and the profile will be discarded.
 added: v24.9.0
 -->

+### `heapProfileHandle.getSamples()`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+* Returns: {Promise} Fulfills with an {Object\[]} of allocation samples.
+
+Asynchronously retrieves the worker's retained allocation samples without
+stopping profiling or building the full profile call tree. The sample fields and
+profiling options are described in
+[`syncHeapProfileHandle.getSamples()`][].
+
+Rejects with `ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or
+disposed, or `ERR_WORKER_NOT_RUNNING` if the worker is no longer running.
+
+### `heapProfileHandle.setSampleInterval(sampleInterval)`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+* `sampleInterval` {integer} Average sampling interval in bytes. Must be between
+  `1` and `Number.MAX_SAFE_INTEGER`, inclusive.
+* Returns: {Promise} Fulfills with `undefined` after the interval is updated.
+
+Asynchronously updates the worker's sampling interval for future sample
+scheduling without restarting profiling or discarding existing samples. Each
+sample retains the `sampleInterval` used when it was selected.
+
+Invalid arguments throw synchronously. The returned promise rejects with
+`ERR_HEAP_PROFILE_NOT_STARTED` if this handle has been stopped or disposed, or
+`ERR_WORKER_NOT_RUNNING` if the worker is no longer running.
+
 ### `heapProfileHandle.stop()`

 <!-- YAML
@@ -1930,6 +2022,7 @@ must be a positive integer.
 [`serializer.transferArrayBuffer()`]: #serializertransferarraybufferid-arraybuffer
 [`serializer.writeRawBytes()`]: #serializerwriterawbytesbuffer
 [`settled` callback]: #settledpromise
+[`syncHeapProfileHandle.getSamples()`]: #syncheapprofilehandlegetsamples
 [`v8.setHeapSnapshotNearHeapLimit()`]: #v8setheapsnapshotnearheaplimitlimit
 [`v8.startHeapProfile()`]: #v8startheapprofileoptions
 [`v8.stopCoverage()`]: #v8stopcoverage
diff --git a/lib/internal/errors.js b/lib/internal/errors.js
index 28f7409ec7f..711ceb4b109 100644
--- a/lib/internal/errors.js
+++ b/lib/internal/errors.js
@@ -1257,6 +1257,7 @@ E('ERR_FS_CP_UNKNOWN', 'Cannot copy an unknown file type', SystemError);
 E('ERR_FS_EISDIR', 'Path is a directory', SystemError, HideStackFramesError);
 E('ERR_FS_FILE_TOO_LARGE', 'File size (%s) is greater than 2 GiB', RangeError);
 E('ERR_FS_WATCH_QUEUE_OVERFLOW', 'fs.watch() queued more than %d events', Error);
+E('ERR_HEAP_PROFILE_NOT_STARTED', 'Heap profile not started', Error);
 E('ERR_HTTP2_ALTSVC_INVALID_ORIGIN',
   'HTTP/2 ALTSVC frames require a valid origin', TypeError);
 E('ERR_HTTP2_ALTSVC_LENGTH',
diff --git a/lib/internal/worker.js b/lib/internal/worker.js
index 00b0293e85d..bf4ce276d53 100644
--- a/lib/internal/worker.js
+++ b/lib/internal/worker.js
@@ -12,6 +12,7 @@ const {
   NumberMAX_SAFE_INTEGER,
   ObjectEntries,
   Promise,
+  PromiseReject,
   PromiseResolve,
   PromiseWithResolvers,
   ReflectApply,
@@ -33,6 +34,7 @@ const path = require('path');
 const errorCodes = require('internal/errors').codes;
 const {
   ERR_WORKER_NOT_RUNNING,
+  ERR_HEAP_PROFILE_NOT_STARTED,
   ERR_WORKER_PATH,
   ERR_WORKER_UNSERIALIZABLE_ERROR,
   ERR_WORKER_INVALID_EXEC_ARGV,
@@ -65,6 +67,7 @@ const {
   validateString,
   validateObject,
   validateNumber,
+  validateInteger,
 } = require('internal/validators');
 const {
   throwIfBuildingSnapshot,
@@ -175,6 +178,35 @@ class HeapProfileHandle {
     this.#worker = worker;
   }

+  setSampleInterval(sampleInterval) {
+    validateInteger(sampleInterval, 'sampleInterval', 1);
+    if (this.#promise) {
+      return PromiseReject(new ERR_HEAP_PROFILE_NOT_STARTED());
+    }
+    const taker = this.#worker[kHandle]?.setHeapProfileSampleInterval(sampleInterval);
+    return new Promise((resolve, reject) => {
+      if (!taker) return reject(new ERR_WORKER_NOT_RUNNING());
+      taker.ondone = (err) => {
+        if (err) return reject(err);
+        resolve();
+      };
+    });
+  }
+
+  getSamples() {
+    if (this.#promise) {
+      return PromiseReject(new ERR_HEAP_PROFILE_NOT_STARTED());
+    }
+    const taker = this.#worker[kHandle]?.getHeapProfileSamples();
+    return new Promise((resolve, reject) => {
+      if (!taker) return reject(new ERR_WORKER_NOT_RUNNING());
+      taker.ondone = (err, samples) => {
+        if (err) return reject(err);
+        resolve(samples);
+      };
+    });
+  }
+
   stop() {
     if (this.#promise) {
       return this.#promise;
diff --git a/lib/v8.js b/lib/v8.js
index 6ae1d2c8ee6..118e9713ce3 100644
--- a/lib/v8.js
+++ b/lib/v8.js
@@ -42,6 +42,7 @@ const {
   validateString,
   validateOneOf,
   validateUint32,
+  validateInteger,
 } = require('internal/validators');
 const {
   Serializer,
@@ -70,6 +71,7 @@ if (hasInspector) {
 const assert = require('internal/assert');
 const {
   codes: {
+    ERR_HEAP_PROFILE_NOT_STARTED,
     ERR_INVALID_STATE,
   },
 } = require('internal/errors');
@@ -133,6 +135,8 @@ const {
   stopCpuProfile: _stopCpuProfile,
   startHeapProfile: _startHeapProfile,
   stopHeapProfile: _stopHeapProfile,
+  setHeapProfileSampleInterval: _setHeapProfileSampleInterval,
+  getHeapProfileSamples: _getHeapProfileSamples,
   isStringOneByteRepresentation: _isStringOneByteRepresentation,
   updateHeapStatisticsBuffer,
   updateHeapSpaceStatisticsBuffer,
@@ -213,6 +217,21 @@ class SyncCPUProfileHandle {
 class SyncHeapProfileHandle {
   #stopped = false;

+  setSampleInterval(sampleInterval) {
+    validateInteger(sampleInterval, 'sampleInterval', 1);
+    if (this.#stopped) {
+      throw new ERR_HEAP_PROFILE_NOT_STARTED();
+    }
+    _setHeapProfileSampleInterval(sampleInterval);
+  }
+
+  getSamples() {
+    if (this.#stopped) {
+      throw new ERR_HEAP_PROFILE_NOT_STARTED();
+    }
+    return _getHeapProfileSamples();
+  }
+
   stop() {
     if (this.#stopped) {
       return;
diff --git a/src/env_properties.h b/src/env_properties.h
index 2f3d814ff49..79ef3010df6 100644
--- a/src/env_properties.h
+++ b/src/env_properties.h
@@ -425,6 +425,7 @@
   V(free_list_statistics_template, v8::DictionaryTemplate)                     \
   V(fsreqpromise_constructor_template, v8::ObjectTemplate)                     \
   V(handle_wrap_ctor_template, v8::FunctionTemplate)                           \
+  V(heap_profile_sample_template, v8::DictionaryTemplate)                      \
   V(heap_statistics_template, v8::DictionaryTemplate)                          \
   V(v8_heap_statistics_template, v8::DictionaryTemplate)                       \
   V(histogram_ctor_template, v8::FunctionTemplate)                             \
diff --git a/src/node_profiling.cc b/src/node_profiling.cc
index 07757d39217..eaaafe6fc65 100644
--- a/src/node_profiling.cc
+++ b/src/node_profiling.cc
@@ -1,16 +1,31 @@
 #include "node_profiling.h"

+#include "env-inl.h"
 #include "json_utils.h"
-#include "util.h"
+#include "util-inl.h"

 #include <memory>
+#include <string_view>

 namespace node {

 using v8::AllocationProfile;
+using v8::Array;
+using v8::Boolean;
+using v8::Context;
+using v8::DictionaryTemplate;
+using v8::FunctionCallbackInfo;
 using v8::HandleScope;
 using v8::HeapProfiler;
+using v8::Int32;
+using v8::Integer;
 using v8::Isolate;
+using v8::Local;
+using v8::LocalVector;
+using v8::MaybeLocal;
+using v8::Number;
+using v8::Object;
+using v8::Uint32;
 using v8::Value;

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

+MaybeLocal<Array> HeapProfileSamplesToV8Value(
+    Isolate* isolate,
+    Local<Context> context,
+    const std::vector<AllocationProfile::Sample>& samples) {
+  Environment* env = Environment::GetCurrent(context);
+  auto tmpl = env->heap_profile_sample_template();
+  if (tmpl.IsEmpty()) {
+    static constexpr std::string_view names[] = {
+        "size",
+        "objectSize",
+        "objectCount",
+        "nodeId",
+        "ordinal",
+        "isLive",
+        "sampleInterval",
+    };
+    tmpl = DictionaryTemplate::New(isolate, names);
+    env->set_heap_profile_sample_template(tmpl);
+  }
+  LocalVector<Value> result(isolate);
+  result.reserve(samples.size());
+  for (const auto& sample : samples) {
+    MaybeLocal<Value> values[] = {
+        Number::New(isolate, sample.size * sample.count),
+        Number::New(isolate, sample.size),
+        Integer::NewFromUnsigned(isolate, sample.count),
+        Integer::NewFromUnsigned(isolate, sample.node_id),
+        Number::New(isolate, static_cast<double>(sample.sample_id)),
+        Boolean::New(isolate, sample.is_live),
+        Number::New(isolate, static_cast<double>(sample.sample_interval)),
+    };
+    Local<Object> object;
+    if (!NewDictionaryInstanceNullProto(context, tmpl, values)
+             .ToLocal(&object)) {
+      return {};
+    }
+    result.emplace_back(object);
+  }
+  return Array::New(isolate, result.data(), result.size());
+}
+
 HeapProfileOptions ParseHeapProfileOptions(
-    const v8::FunctionCallbackInfo<Value>& args) {
+    const FunctionCallbackInfo<Value>& args) {
   HeapProfileOptions options;
   CHECK_LE(args.Length(), 3);
   if (args.Length() > 0) {
     CHECK(args[0]->IsNumber());
     options.sample_interval =
-        static_cast<uint64_t>(args[0].As<v8::Number>()->Value());
+        static_cast<uint64_t>(args[0].As<Number>()->Value());
   }
   if (args.Length() > 1) {
     CHECK(args[1]->IsInt32());
-    options.stack_depth = args[1].As<v8::Int32>()->Value();
+    options.stack_depth = args[1].As<Int32>()->Value();
   }
   if (args.Length() > 2) {
     CHECK(args[2]->IsUint32());
-    options.flags = static_cast<v8::HeapProfiler::SamplingFlags>(
-        args[2].As<v8::Uint32>()->Value());
+    options.flags =
+        static_cast<HeapProfiler::SamplingFlags>(args[2].As<Uint32>()->Value());
   }
   return options;
 }

 CpuProfileOptions ParseCpuProfileOptions(
-    const v8::FunctionCallbackInfo<Value>& args) {
+    const FunctionCallbackInfo<Value>& args) {
   CpuProfileOptions options;
   CHECK_LE(args.Length(), 2);
   if (args.Length() > 0) {
     CHECK(args[0]->IsInt32());
-    options.sampling_interval_us = args[0].As<v8::Int32>()->Value();
+    options.sampling_interval_us = args[0].As<Int32>()->Value();
   }
   if (args.Length() > 1) {
     CHECK(args[1]->IsUint32());
-    options.max_samples = args[1].As<v8::Uint32>()->Value();
+    options.max_samples = args[1].As<Uint32>()->Value();
   }
   return options;
 }
diff --git a/src/node_profiling.h b/src/node_profiling.h
index 08f40ee04f6..6fa5f2cee9a 100644
--- a/src/node_profiling.h
+++ b/src/node_profiling.h
@@ -8,6 +8,7 @@

 #include <cstdint>
 #include <string>
+#include <vector>

 namespace node {

@@ -23,6 +24,11 @@ HeapProfileOptions ParseHeapProfileOptions(

 bool SerializeHeapProfile(v8::Isolate* isolate, std::string& out);

+v8::MaybeLocal<v8::Array> HeapProfileSamplesToV8Value(
+    v8::Isolate* isolate,
+    v8::Local<v8::Context> context,
+    const std::vector<v8::AllocationProfile::Sample>& samples);
+
 struct CpuProfileOptions {
   int sampling_interval_us = 0;
   uint32_t max_samples = v8::CpuProfilingOptions::kNoSampleLimit;
diff --git a/src/node_v8.cc b/src/node_v8.cc
index 49e4a0ca113..ebacf346ba2 100644
--- a/src/node_v8.cc
+++ b/src/node_v8.cc
@@ -348,6 +348,27 @@ void StopHeapProfile(const FunctionCallbackInfo<Value>& args) {
   }
 }

+void SetHeapProfileSampleInterval(const FunctionCallbackInfo<Value>& args) {
+  CHECK_EQ(args.Length(), 1);
+  CHECK(args[0]->IsNumber());
+  double sample_interval = args[0].As<Number>()->Value();
+  CHECK_GE(sample_interval, 1);
+  CHECK_LE(sample_interval, kMaxSafeJsInteger);
+  args.GetIsolate()->GetHeapProfiler()->SetSamplingHeapProfilerInterval(
+      static_cast<uint64_t>(sample_interval));
+}
+
+void GetHeapProfileSamples(const FunctionCallbackInfo<Value>& args) {
+  Environment* env = Environment::GetCurrent(args);
+  auto samples =
+      env->isolate()->GetHeapProfiler()->GetSamplingHeapProfilerSamples();
+  Local<Array> result;
+  if (HeapProfileSamplesToV8Value(env->isolate(), env->context(), samples)
+          .ToLocal(&result)) {
+    args.GetReturnValue().Set(result);
+  }
+}
+
 static void IsStringOneByteRepresentation(
     const FunctionCallbackInfo<Value>& args) {
   CHECK_EQ(args.Length(), 1);
@@ -820,6 +841,11 @@ void Initialize(Local<Object> target,
   SetMethod(context, target, "stopCpuProfile", StopCpuProfile);
   SetMethod(context, target, "startHeapProfile", StartHeapProfile);
   SetMethod(context, target, "stopHeapProfile", StopHeapProfile);
+  SetMethod(context,
+            target,
+            "setHeapProfileSampleInterval",
+            SetHeapProfileSampleInterval);
+  SetMethod(context, target, "getHeapProfileSamples", GetHeapProfileSamples);

   {
     constexpr uint32_t kSamplingNoFlags =
@@ -889,6 +915,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
   registry->Register(StopCpuProfile);
   registry->Register(StartHeapProfile);
   registry->Register(StopHeapProfile);
+  registry->Register(SetHeapProfileSampleInterval);
+  registry->Register(GetHeapProfileSamples);
 }

 }  // namespace v8_utils
diff --git a/src/node_worker.cc b/src/node_worker.cc
index 36cf67dd730..a9f0614b4c3 100644
--- a/src/node_worker.cc
+++ b/src/node_worker.cc
@@ -1062,6 +1062,84 @@ class WorkerHeapProfileTaker final : public AsyncWrap {
   SET_SELF_SIZE(WorkerHeapProfileTaker)
 };

+void Worker::SetHeapProfileSampleInterval(
+    const FunctionCallbackInfo<Value>& args) {
+  Worker* w;
+  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
+  Environment* env = w->env();
+  CHECK_EQ(args.Length(), 1);
+  CHECK(args[0]->IsNumber());
+  double interval = args[0].As<Number>()->Value();
+  CHECK_GE(interval, 1);
+  CHECK_LE(interval, kMaxSafeJsInteger);
+
+  AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(w);
+  Local<Object> wrap;
+  if (!env->worker_heap_profile_taker_template()
+           ->NewInstance(env->context())
+           .ToLocal(&wrap)) {
+    return;
+  }
+  BaseObjectPtr<WorkerHeapProfileTaker> taker =
+      MakeDetachedBaseObject<WorkerHeapProfileTaker>(env, wrap);
+  bool queued = w->RequestInterrupt([taker = std::move(taker), env, interval](
+                                        Environment* worker_env) mutable {
+    auto* profiler = worker_env->isolate()->GetHeapProfiler();
+    profiler->SetSamplingHeapProfilerInterval(static_cast<uint64_t>(interval));
+    env->SetImmediateThreadsafe(
+        [taker = std::move(taker)](Environment* env) mutable {
+          Isolate* isolate = env->isolate();
+          HandleScope handle_scope(isolate);
+          Context::Scope context_scope(env->context());
+          AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(taker.get());
+          Local<Value> argv[] = {Null(isolate)};
+          taker->MakeCallback(env->ondone_string(), arraysize(argv), argv);
+        },
+        CallbackFlags::kUnrefed);
+  });
+  if (queued) {
+    args.GetReturnValue().Set(wrap);
+  }
+}
+
+void Worker::GetHeapProfileSamples(const FunctionCallbackInfo<Value>& args) {
+  Worker* w;
+  ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
+  Environment* env = w->env();
+  AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(w);
+  Local<Object> wrap;
+  if (!env->worker_heap_profile_taker_template()
+           ->NewInstance(env->context())
+           .ToLocal(&wrap)) {
+    return;
+  }
+  BaseObjectPtr<WorkerHeapProfileTaker> taker =
+      MakeDetachedBaseObject<WorkerHeapProfileTaker>(env, wrap);
+  bool scheduled = w->RequestInterrupt([taker = std::move(taker),
+                                        env](Environment* worker_env) mutable {
+    auto* profiler = worker_env->isolate()->GetHeapProfiler();
+    auto samples = profiler->GetSamplingHeapProfilerSamples();
+    env->SetImmediateThreadsafe(
+        [taker = std::move(taker),
+         samples = std::move(samples)](Environment* env) mutable {
+          Isolate* isolate = env->isolate();
+          HandleScope handle_scope(isolate);
+          Context::Scope context_scope(env->context());
+          AsyncHooks::DefaultTriggerAsyncIdScope trigger_id_scope(taker.get());
+          Local<Value> argv[] = {Null(isolate), Undefined(isolate)};
+          if (!HeapProfileSamplesToV8Value(isolate, env->context(), samples)
+                   .ToLocal(&argv[1])) {
+            return;
+          }
+          taker->MakeCallback(env->ondone_string(), arraysize(argv), argv);
+        },
+        CallbackFlags::kUnrefed);
+  });
+  if (scheduled) {
+    args.GetReturnValue().Set(wrap);
+  }
+}
+
 void Worker::StartHeapProfile(const FunctionCallbackInfo<Value>& args) {
   Worker* w;
   ASSIGN_OR_RETURN_UNWRAP(&w, args.This());
@@ -1512,6 +1590,12 @@ void CreateWorkerPerIsolateProperties(IsolateData* isolate_data,
     SetProtoMethod(isolate, w, "stopCpuProfile", Worker::StopCpuProfile);
     SetProtoMethod(isolate, w, "startHeapProfile", Worker::StartHeapProfile);
     SetProtoMethod(isolate, w, "stopHeapProfile", Worker::StopHeapProfile);
+    SetProtoMethod(isolate,
+                   w,
+                   "setHeapProfileSampleInterval",
+                   Worker::SetHeapProfileSampleInterval);
+    SetProtoMethod(
+        isolate, w, "getHeapProfileSamples", Worker::GetHeapProfileSamples);

     SetConstructorFunction(isolate, target, "Worker", w);
   }
@@ -1625,6 +1709,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
   registry->Register(Worker::StopCpuProfile);
   registry->Register(Worker::StartHeapProfile);
   registry->Register(Worker::StopHeapProfile);
+  registry->Register(Worker::SetHeapProfileSampleInterval);
+  registry->Register(Worker::GetHeapProfileSamples);
 }

 }  // anonymous namespace
diff --git a/src/node_worker.h b/src/node_worker.h
index 4261db0c18f..09fb3f58047 100644
--- a/src/node_worker.h
+++ b/src/node_worker.h
@@ -88,6 +88,10 @@ class Worker : public AsyncWrap {
   static void StopCpuProfile(const v8::FunctionCallbackInfo<v8::Value>& args);
   static void StartHeapProfile(const v8::FunctionCallbackInfo<v8::Value>& args);
   static void StopHeapProfile(const v8::FunctionCallbackInfo<v8::Value>& args);
+  static void SetHeapProfileSampleInterval(
+      const v8::FunctionCallbackInfo<v8::Value>& args);
+  static void GetHeapProfileSamples(
+      const v8::FunctionCallbackInfo<v8::Value>& args);

  private:
   bool CreateEnvMessagePort(Environment* env);
diff --git a/test/parallel/test-v8-heap-profile-samples.js b/test/parallel/test-v8-heap-profile-samples.js
new file mode 100644
index 00000000000..511262dd372
--- /dev/null
+++ b/test/parallel/test-v8-heap-profile-samples.js
@@ -0,0 +1,104 @@
+// Flags: --expose-gc --sampling-heap-profiler-suppress-randomness
+'use strict';
+
+require('../common');
+const assert = require('assert');
+const v8 = require('v8');
+
+function allocate() {
+  return Array.from({ length: 512 }, () => new Array(64).fill(42));
+}
+
+const handle = v8.startHeapProfile({
+  sampleInterval: 1024,
+  includeObjectsCollectedByMajorGC: true,
+  includeObjectsCollectedByMinorGC: true,
+});
+
+for (const value of [undefined, null, true, '1024', {}, 1n]) {
+  assert.throws(() => handle.setSampleInterval(value), {
+    code: 'ERR_INVALID_ARG_TYPE',
+  });
+}
+for (const value of [0, -1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1]) {
+  assert.throws(() => handle.setSampleInterval(value), {
+    code: 'ERR_OUT_OF_RANGE',
+  });
+}
+
+const retained = allocate();
+const before = handle.getSamples();
+assert(before.length > 0);
+for (const sample of before) {
+  assert.strictEqual(sample.sampleInterval, 1024);
+  assert.strictEqual(sample.size, sample.objectSize * sample.objectCount);
+  assert.strictEqual(typeof sample.nodeId, 'number');
+  assert.strictEqual(typeof sample.ordinal, 'number');
+  assert.strictEqual(typeof sample.isLive, 'boolean');
+}
+
+assert.strictEqual(handle.setSampleInterval(4096), undefined);
+const moreRetained = allocate();
+const after = handle.getSamples();
+assert(after.some((sample) => sample.sampleInterval === 4096));
+const byOrdinal = new Map(after.map((sample) => [sample.ordinal, sample]));
+for (const sample of before) {
+  const current = byOrdinal.get(sample.ordinal);
+  assert(current, `Sample ${sample.ordinal} was lost after changing the interval`);
+  assert.strictEqual(current.sampleInterval, sample.sampleInterval);
+  assert.strictEqual(current.objectSize, sample.objectSize);
+  assert.strictEqual(current.objectCount, sample.objectCount);
+}
+
+global.gc();
+const afterGC = handle.getSamples();
+assert(afterGC.some((sample) => !sample.isLive));
+assert(afterGC.some((sample) => sample.sampleInterval === 1024));
+assert(afterGC.some((sample) => sample.sampleInterval === 4096));
+
+const profile = JSON.parse(handle.stop());
+const saved = new Map(profile.samples.map((sample) => [sample.ordinal, sample]));
+const nodeIds = new Set();
+function visit(node) {
+  nodeIds.add(node.id);
+  node.children.forEach(visit);
+}
+visit(profile.head);
+for (const sample of afterGC) {
+  const current = saved.get(sample.ordinal);
+  assert(current);
+  assert.strictEqual(current.sampleInterval, sample.sampleInterval);
+  assert.strictEqual(current.size, sample.size);
+  assert(nodeIds.has(sample.nodeId));
+}
+assert.strictEqual(retained.length, 512);
+assert.strictEqual(moreRetained.length, 512);
+
+// A stopped handle must not poll or update a new profiling session.
+const next = v8.startHeapProfile({ sampleInterval: 1024 });
+assert.throws(() => handle.getSamples(), {
+  code: 'ERR_HEAP_PROFILE_NOT_STARTED',
+});
+assert.throws(() => handle.setSampleInterval(1), {
+  code: 'ERR_HEAP_PROFILE_NOT_STARTED',
+});
+const nextRetained = allocate();
+const nextSamples = next.getSamples();
+assert(nextSamples.length > 0);
+assert(nextSamples.every((sample) => sample.sampleInterval === 1024));
+assert.strictEqual(nextRetained.length, 512);
+next[Symbol.dispose]();
+assert.throws(() => next.getSamples(), {
+  code: 'ERR_HEAP_PROFILE_NOT_STARTED',
+});
+
+// Polling honors the forceGC option and retains collected samples when enabled.
+const forceGC = v8.startHeapProfile({
+  sampleInterval: 1024,
+  forceGC: true,
+  includeObjectsCollectedByMajorGC: true,
+  includeObjectsCollectedByMinorGC: true,
+});
+allocate();
+assert(forceGC.getSamples().some((sample) => !sample.isLive));
+forceGC.stop();
diff --git a/test/parallel/test-worker-heap-profile-samples.js b/test/parallel/test-worker-heap-profile-samples.js
new file mode 100644
index 00000000000..1e738dd7fd0
--- /dev/null
+++ b/test/parallel/test-worker-heap-profile-samples.js
@@ -0,0 +1,94 @@
+// Flags: --sampling-heap-profiler-suppress-randomness
+'use strict';
+
+const common = require('../common');
+const assert = require('assert');
+const { once } = require('events');
+const { Worker } = require('worker_threads');
+
+async function main() {
+  const worker = new Worker(`
+    const { parentPort } = require('worker_threads');
+    const retained = [];
+    parentPort.on('message', () => {
+      for (let i = 0; i < 512; i++) {
+        retained.push(new Array(64).fill(i));
+      }
+      parentPort.postMessage('allocated');
+    });
+  `, { eval: true });
+  await once(worker, 'online');
+  const handle = await worker.startHeapProfile({
+    sampleInterval: 1024,
+    includeObjectsCollectedByMajorGC: true,
+    includeObjectsCollectedByMinorGC: true,
+  });
+
+  for (const value of [undefined, null, true, '1024', {}, 1n]) {
+    assert.throws(() => handle.setSampleInterval(value), {
+      code: 'ERR_INVALID_ARG_TYPE',
+    });
+  }
+  for (const value of [0, -1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1]) {
+    assert.throws(() => handle.setSampleInterval(value), {
+      code: 'ERR_OUT_OF_RANGE',
+    });
+  }
+
+  worker.postMessage('allocate');
+  await once(worker, 'message');
+  const before = await handle.getSamples();
+  assert(before.length > 0);
+  assert(before.every((sample) => sample.sampleInterval === 1024));
+
+  assert.strictEqual(await handle.setSampleInterval(4096), undefined);
+  worker.postMessage('allocate');
+  await once(worker, 'message');
+  const after = await handle.getSamples();
+  assert(after.some((sample) => sample.sampleInterval === 4096));
+  const byOrdinal = new Map(after.map((sample) => [sample.ordinal, sample]));
+  for (const sample of before) {
+    const current = byOrdinal.get(sample.ordinal);
+    assert(current);
+    assert.strictEqual(current.sampleInterval, sample.sampleInterval);
+    assert.strictEqual(current.objectCount, sample.objectCount);
+  }
+
+  const stop = handle.stop();
+  await assert.rejects(handle.getSamples(), {
+    code: 'ERR_HEAP_PROFILE_NOT_STARTED',
+  });
+  await assert.rejects(handle.setSampleInterval(1), {
+    code: 'ERR_HEAP_PROFILE_NOT_STARTED',
+  });
+  const profile = JSON.parse(await stop);
+  const saved = new Map(profile.samples.map((sample) => [sample.ordinal, sample]));
+  for (const sample of after) {
+    assert.strictEqual(saved.get(sample.ordinal).sampleInterval, sample.sampleInterval);
+    assert.strictEqual(sample.size, sample.objectSize * sample.objectCount);
+    assert.strictEqual(typeof sample.nodeId, 'number');
+    assert.strictEqual(typeof sample.ordinal, 'number');
+    assert.strictEqual(typeof sample.isLive, 'boolean');
+  }
+
+  const next = await worker.startHeapProfile({ sampleInterval: 1024 });
+  await assert.rejects(handle.setSampleInterval(1), {
+    code: 'ERR_HEAP_PROFILE_NOT_STARTED',
+  });
+  await assert.rejects(handle.getSamples(), {
+    code: 'ERR_HEAP_PROFILE_NOT_STARTED',
+  });
+  worker.postMessage('allocate');
+  await once(worker, 'message');
+  const nextSamples = await next.getSamples();
+  assert(nextSamples.length > 0);
+  assert(nextSamples.every((sample) => sample.sampleInterval === 1024));
+  await next[Symbol.asyncDispose]();
+  await assert.rejects(next.getSamples(), {
+    code: 'ERR_HEAP_PROFILE_NOT_STARTED',
+  });
+
+  await worker.terminate();
+}
+
+main().then(common.mustCall());
diff --git a/typings/internalBinding/worker.d.ts b/typings/internalBinding/worker.d.ts
index 7801b2c569d..6a507cdbb74 100644
--- a/typings/internalBinding/worker.d.ts
+++ b/typings/internalBinding/worker.d.ts
@@ -31,10 +31,22 @@ export interface CPUProfileHandle {
 }

 export interface HeapProfileHandle {
+  setSampleInterval(sampleInterval: number): Promise<void>;
+  getSamples(): Promise<HeapProfileSample[]>;
   stop(): Promise<string>;
   [Symbol.asyncDispose](): Promise<void>;
 }

+export interface HeapProfileSample {
+  size: number;
+  objectSize: number;
+  objectCount: number;
+  nodeId: number;
+  ordinal: number;
+  isLive: boolean;
+  sampleInterval: number;
+}
+
 export interface WorkerBinding {
   Worker: typeof InternalWorkerBinding.Worker;
   getEnvMessagePort(): InternalMessagingBinding.MessagePort;