Repository navigation
[3/4] feat(heap): add in-place SamplingHeapPruner implementation and design doc - #461
IlyasShabi wants to merge 3 commits into
Conversation
Overall package sizeSelf size: 2.88 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 |
szegedi
left a comment
There was a problem hiding this comment.
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.
| 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]); |
There was a problem hiding this comment.
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.
| if (!p || p->last_sample_id_ < watermark_ || | ||
| p->samples_.size() != samples.size()) { |
There was a problem hiding this comment.
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?
| 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; | ||
| } |
There was a problem hiding this comment.
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.
| 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); | ||
| } |
There was a problem hiding this comment.
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.
| // 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); |
There was a problem hiding this comment.
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.
Stack
mainishabi/heap-pruner-1-lifecycle-perfBuildAllocationStatsByNodeIdand live-only near-OOM filteringishabi/heap-pruner-2-watermark-oomSamplingHeapPrunerimplementation + design docishabi/heap-pruner-3-sampling-prunerSamplingHeapPruner, remove restart loop, full integration & worker testsMotivation
Introduces the self-contained
SamplingHeapPrunerclass and its full technical design document before wiring it intoHeapProfilerin #462 (DataDog/dd-trace-js#11122). Because nothing callsSamplingHeapPrunerin production yet, reviewers can audit the V8 layout mirrors, safety invariants, and downgrade behavior in complete isolation.Changes
bindings/profilers/sampling-heap-pruner.{hh,cc},binding.gyp):#if !defined(_WIN32) && NODE_MAJOR_VERSION == 26; unsupported platforms/versions compile a safe#elsefallback that starts V8 directly in live-only mode (kSamplingNoFlags).StartSamplingHeapProfiler) and ascending-offsetV8Profilerfield verification; downgrades immediately to live-only mode on any layout mismatch or leaves an existing foreign sampler untouched.BuildStats()verifies session continuity (slot_,last_sample_id_ >= watermark_,samples_.size() == samples.size()) and delegates to watermarkedBuildAllocationStatsByNodeId().Prune()resolves V8'sOnWeakCallbackfrom the first live sample'sGlobalHandles::Node, temporarily clears GC-retention flags withdefer, and invokes V8's ownOnWeakCallbackfor each dead sample withsample_id <= watermark_(or flushes dead-only initial windows once inline). Any invariant mismatch triggersDowngradeToLive().bindings/test/binding.cc):TestSamplingHeapPrunerDowngradeverifyinginterval == 0, synthetic sample-count mismatch -> pending downgrade ->Prune()downgrade to live-only, and foreign-sampler-already-running no-op.docs/in-place-sampling-heap-pruner-design.md):