Skip to content

[1/4] fix(heap): harden heap profiler lifecycle, translation, and OOM callbacks - #459

Open
IlyasShabi wants to merge 1 commit into
mainfrom
ishabi/heap-pruner-1-lifecycle-perf
Open

IlyasShabi wants to merge 1 commit into
mainfrom
ishabi/heap-pruner-1-lifecycle-perf

Conversation

@IlyasShabi

@IlyasShabi IlyasShabi commented Dec 2, 2026 •

Copy link
Copy Markdown

Stack

# PR Base Summary
1 #459 ← this PR main Lifecycle hardening, translation fast paths, and OOM callback correctness
2 #460 ishabi/heap-pruner-1-lifecycle-perf Watermarked BuildAllocationStatsByNodeId and live-only near-OOM filtering
3 #461 ishabi/heap-pruner-2-watermark-oom Self-contained SamplingHeapPruner implementation + design doc
4 #462 ishabi/heap-pruner-3-sampling-pruner Wire SamplingHeapPruner, remove restart loop, full integration & worker tests

Motivation

Prepares the heap profiler codebase for continuous in-place allocation profiling (DataDog/dd-trace-js#11122) by fixing standalone lifecycle, correctness, and translation issues that are valuable independently of the pruner.

Changes

  • Lifecycle & safety (bindings/profilers/heap.cc, bindings/profilers/near-oom.hh):
    • Removed the redundant HeapProfilerCleanupHook + global mutex/set (relying on PerIsolateData's existing environment cleanup hook to destroy HeapProfilerState).
    • Added stopped guard in HeapProfilerState so a stale ~HeapProfilerState kept alive by an in-flight OOM/interrupt callback cannot stop a newly restarted session.
    • Rejected sample_interval == 0 with RangeError without wedging state.
    • Captured state std::shared_ptr by value in GetAllocationProfile() and scoped allocation_stats.
  • Translation hardening & perf (bindings/profile-translator.hh, bindings/allocation-profile.{hh,cc}, bindings/translate-heap-profile.cc):
    • Switched property assignment to CreateDataProperty so Object.prototype setters cannot run or throw during translation.
    • Hoisted AllocationStatKeys (kInternalized literals), added single-bucket fast path, deterministic SizeEntry sort, inner HandleScope / EscapableHandleScope, single-pass branchless BuildAllocationStatsByNodeId, and 64-bit byte accumulation.
  • TypeScript OOM & (external) fixes (ts/src/heap-profiler.ts):
    • Fixed monitorOutOfMemory() callbacks to always convert near-OOM profiles in live-only mode (allocations = false).
    • Set allocObjects: 0, allocSpaceBytes: 0 on the synthetic (external) live gauge node in allocation mode.
  • Tests (bindings/test/binding.cc, ts/test/test-heap-profiler.ts, ts/test/oom-heap-limit-extension.ts):
    • Added C++ unit tests for TranslateAllocationStats and 64-bit overflow protection.
    • Added JS tests for intervalBytes === 0, Object.prototype setter immunity, and OOM Async/Interrupt/restart-in-callback flows.

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

Overall package size

Self size: 2.8 MB
Deduped: 3.92 MB
No deduping: 3.92 MB

Dependency sizes | name | version | self size | total size | |------|---------|-----------|------------| | pprof-format | 2.4.1 | 924.37 kB | 924.37 kB | | source-map | 0.8.0 | 185.66 kB | 185.66 kB | | node-gyp-build | 4.8.4 | 13.86 kB | 13.86 kB |

🤖 This report was automatically generated by heaviest-objects-in-the-universe

Comment on lines -165 to +129
auto& state = PerIsolateData::For(isolate)->GetHeapProfilerState();
auto state = PerIsolateData::For(isolate)->GetHeapProfilerState();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's always a tiny alarm bell for me when you go from by-ref to by-value for a return value, but I understand why this is and it's actually safer this way. Maybe a one-line note saying the copy is deliberate to pin the object's lifetime, so nobody "fixes" it back to auto& later?

Comment thread ts/src/heap-profiler.ts
if (typeof callback !== 'undefined') {
newCallback = (profile: AllocationProfileNode) => {
callback(convertProfile(profile));
// Near-OOM capture always translates live-only AllocationProfileNode

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

they aren't really "live-only" but since you're fixing this in #460 it should be fine. If I want to be pedantic, you might remove that wording until then from here.

static std::mutex g_heap_profiler_mutex;

// Cleanup hook to stop heap profiler before isolate is destroyed
static void HeapProfilerCleanupHook(void* data) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because you removed the hook, StopSamplingHeapProfiler now runs inside ~HeapProfilerState, while the PerIsolateData cleanup lambda holds a mutex. If a worker thread exits while still profiling, other isolates calling PerIsolateData::For will block until teardown finishes. Any re-entry into For() from that path would deadlock, although I'm not sure if there are any such reentries.

Fix ideas (suggested by Claude, so take with grain of salt) are to take the state out of the map, or stop sampling, then destroy it after the lock_guard is released.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looked into this more, and I couldn't find anything on that path that re-enters PerIsolateData::For, so I don't think it deadlocks. But in allocation mode, stopping frees every retained sample, and every other isolate's For() (profile(), NearHeapLimit, the wall profiler) blocks meanwhile, and it might take some time. Later in #462 you added a test with 4 workers exiting this way.

Could we move the state out under the lock and destroy it after releasing it? Something like:

std::shared_ptr<HeapProfilerState> doomed;
{
  const std::lock_guard<std::mutex> lock(mutex);
  auto it = per_isolate_data_.find(isolate);
  if (it != per_isolate_data_.end()) {
    doomed = std::move(it->second.GetHeapProfilerState());
    per_isolate_data_.erase(it);
  }
}
// doomed (and the V8 sampler stop) released here, outside the lock

static std::mutex g_heap_profiler_mutex;

// Cleanup hook to stop heap profiler before isolate is destroyed
static void HeapProfilerCleanupHook(void* data) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You have a comment in bindings/profilers/near-oom.cc:347 that still references this method name.

heapProfiler.start(64 * 1024, 64, false);
const p = heapProfiler.profile();
assert.ok(p.sampleType.length === 2);
heapProfiler.stop();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be in a finally block of a try/finally or an assertion failure will cause other tests to fail with "profiler already started"

assert.ok(retained.length === 16);
const root = heapProfiler.v8Profile();
assert.ok(Array.isArray(root.children));
heapProfiler.stop();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be in the finally block below or an assertion failure will cause other tests to fail with "profiler already started"


uint64_t sample_interval = info[0].As<v8::Integer>()->Value();
if (sample_interval == 0) {
return Nan::ThrowRangeError("Sample interval must be greater than 0.");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very correct to add here, but it can have an… interesting side effect, namely:
start() sets startedWithAllocations, heapIntervalBytes and heapStackDepth before it calls here and it can now throw RangeError when intervalBytes is 0, and the values start() set stay set. A later call to the exported convertProfile() then runs in the wrong mode.

This isn't a new problem, just your new RangeError path makes it easier to hit.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see you fixed this in #462 so probably nothing to do here.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

semver-minor Usually minor non-breaking improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants