Skip to content

[3/4] feat(heap): add in-place SamplingHeapPruner implementation and design doc - #461

Open
IlyasShabi wants to merge 3 commits into
ishabi/heap-pruner-2-watermark-oomfrom
ishabi/heap-pruner-3-sampling-pruner
Open

IlyasShabi wants to merge 3 commits into
ishabi/heap-pruner-2-watermark-oomfrom
ishabi/heap-pruner-3-sampling-pruner

Conversation

@IlyasShabi

@IlyasShabi IlyasShabi commented Dec 2, 2026 •

Copy link
Copy Markdown

Stack

# PR Base Summary
1 #459 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 ← this PR 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

Introduces the self-contained SamplingHeapPruner class and its full technical design document before wiring it into HeapProfiler in #462 (DataDog/dd-trace-js#11122). Because nothing calls SamplingHeapPruner in production yet, reviewers can audit the V8 layout mirrors, safety invariants, and downgrade behavior in complete isolation.

Changes

  • In-place pruner (bindings/profilers/sampling-heap-pruner.{hh,cc}, binding.gyp):
    • Compiled under #if !defined(_WIN32) && NODE_MAJOR_VERSION == 26; unsupported platforms/versions compile a safe #else fallback that starts V8 directly in live-only mode (kSamplingNoFlags).
    • Read-only slot discovery (12-slot diff around StartSamplingHeapProfiler) and ascending-offset V8Profiler field verification; downgrades immediately to live-only mode on any layout mismatch or leaves an existing foreign sampler untouched.
    • Per-collection BuildStats() verifies session continuity (slot_, last_sample_id_ >= watermark_, samples_.size() == samples.size()) and delegates to watermarked BuildAllocationStatsByNodeId().
    • Prune() resolves V8's OnWeakCallback from the first live sample's GlobalHandles::Node, temporarily clears GC-retention flags with defer, and invokes V8's own OnWeakCallback for each dead sample with sample_id <= watermark_ (or flushes dead-only initial windows once inline). Any invariant mismatch triggers DowngradeToLive().
  • C++ unit test (bindings/test/binding.cc):
    • Added TestSamplingHeapPrunerDowngrade verifying interval == 0, synthetic sample-count mismatch -> pending downgrade -> Prune() downgrade to live-only, and foreign-sampler-already-running no-op.
  • Design doc (docs/in-place-sampling-heap-pruner-design.md):
    • Documents problem statement, rejected public-API alternatives, V8 layout mirrors, lifecycle/state diagrams, safety invariants, known limitations, and benchmark results.

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

Overall package size

Self size: 2.88 MB
Deduped: 4.01 MB
No deduping: 4.01 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

@datadog-datadog-prod-us1-2

datadog-datadog-prod-us1-2 Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Pipelines

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: f054aec | Docs | Give us feedback!

@IlyasShabi
IlyasShabi marked this pull request as ready for review December 2, 2026 14:43

@szegedi szegedi left a comment

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'll approve this, as everything I have are hardening/robustness ideas and few nits. The CurrentProfiler thought about more detailed checks to detect reallocation at the same address is probably the one that I'd almost "request changes" for, though.

Comment on lines +139 to +145
if (before[i] == 0 && after[i] != 0 && (after[i] % sizeof(void*)) == 0) {
idx = i;
++changed;
}
}
if (changed == 1) {
auto* p = reinterpret_cast<V8Profiler*>(after[idx]);

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.

A hardening idea: If exactly one slot changes, its value is dereferenced (p->isolate_) before anything confirms it's a pointer. The existing checks protect against a real but smaller object, not against a non-pointer. If a future V8 moves sampling_heap_profiler_ past slot 11 and some other word flips 0 to aligned non-zero (e.g. a bool at byte offset 1 reads as 0x100), heap.start() will segfault instead of falling back.

Since the doc already says the slot is 9, could we require idx == kExpectedSlot (or a small allowlist per verified V8 versions) before dereferencing? Then any mismatch falls back through DowngradeToLive() without touching unknown memory.

Comment on lines +175 to +176
if (!p || p->last_sample_id_ < watermark_ ||
p->samples_.size() != samples.size()) {

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.

nit: On the samples_.size() != samples.size() path, the profiler is still ours and the session is unchanged, but the final build runs with no watermark, so every retained sample is re-reported as a new allocation in that window. Nothing runs between GetAllocationProfile() and BuildStats() that could change samples_, so this path really means "we're misreading the layout".

This is admittedly rare and happens once, but the watermark only depends on public sample_ids, so it stays valid. Could we zero it only on the !p || last_sample_id_ < watermark_ paths and use it for this last build?

Comment on lines +99 to +106
V8Profiler* CurrentProfiler(const void* slot, void* expected) {
if (!slot || !expected) return nullptr;
uintptr_t cur = 0;
std::memcpy(&cur, slot, sizeof(cur));
return cur == reinterpret_cast<uintptr_t>(expected)
? static_cast<V8Profiler*>(expected)
: nullptr;
}

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.

An idea for improving robustness:

Could we also compare p->interval_ / p->stack_depth_ / p->flags_ with what we attached with? Together with resetting on a null profile in #462 should cover all cases, I think.

Session identity is just pointer equality. If the inspector does stopSampling + startSampling and the new SamplingHeapProfiler gets allocated at the just-freed address (e.g. glibc tcache makes immediate same-size reuse fairly likely), the check will pass.

As an example of what I think can be a silent error: last_sample_id_ < watermark_ check only catches the new session having fewer samples than our watermark. Then BuildStats treats the new session's samples with sample_id <= watermark_ as already reported, and Prune will free dead samples the inspector asked to keep. There's no use-after-free error as the object is live, but the data gets mixed up.

Comment on lines +188 to +197
void SamplingHeapPruner::DowngradeToLive(v8::Isolate* isolate) {
const uint64_t interval = interval_;
const int depth = stack_depth_;
Reset();
if (interval == 0) return;
auto* hp = isolate->GetHeapProfiler();
hp->StopSamplingHeapProfiler();
hp->StartSamplingHeapProfiler(
interval, depth, v8::HeapProfiler::kSamplingNoFlags);
}

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.

Okay, a design question: when the slot holds a sampler we didn't start, Prune()/DowngradeToLive() call stops it and starts our own no-flags one. The new test in #462 ("should detect external sampler replacement") asserts this, so I know this is intentional, which is fine. It's also no worse than current main, which restarted on every collection. If "pprof reclaims the sampler" is the intended policy (it looks like it is), could we say so in a comment here and in the design doc? The design doc currently talks about isolating foreign samplers.

Comment on lines +37 to +40
// Starts V8 sampling in allocation mode and attaches if the internal layout
// matches. On unsupported platforms or layout mismatch, downgrades V8 to
// live-only mode (kSamplingNoFlags) leaving IsActive() == false.
void Start(v8::Isolate* isolate, uint64_t sample_interval, int stack_depth);

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.

nit: the comment says Start() downgrades to live-only on failure. That's true for a layout mismatch, but when V8 is already running a sampler it returns with IsActive() == false and leaves that sampler alone. The fact that Start() must not be called while our own session is running is enforced by the IsActive() check in heap.cc. Either a one-liner in the comments here documenting it, or an early if (IsActive()) return; would make the class safe on its own.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants