diff --git a/bindings/profilers/heap.cc b/bindings/profilers/heap.cc index 1c467445..f7872675 100644 --- a/bindings/profilers/heap.cc +++ b/bindings/profilers/heap.cc @@ -49,7 +49,8 @@ static void HeapProfilerCleanupHook(void* data) { } } -NAN_METHOD(HeapProfiler::StartSamplingHeapProfiler) { +static void StartSampling(const Nan::FunctionCallbackInfo& info, + bool restart) { auto isolate = info.GetIsolate(); // Register cleanup hook if not already registered for this isolate @@ -94,9 +95,14 @@ NAN_METHOD(HeapProfiler::StartSamplingHeapProfiler) { } #endif + // Collection resets only V8 sampling. Keep the OOM callback, configuration, + // extension counters, and cleanup hook attached to the existing state. + if (restart) { + isolate->GetHeapProfiler()->StopSamplingHeapProfiler(); + } isolate->GetHeapProfiler()->StartSamplingHeapProfiler( sample_interval, stack_depth, flags); - } else if (info.Length() == 0) { + } else if (info.Length() == 0 && !restart) { isolate->GetHeapProfiler()->StartSamplingHeapProfiler(); } else { return Nan::ThrowTypeError( @@ -110,6 +116,18 @@ NAN_METHOD(HeapProfiler::StartSamplingHeapProfiler) { state->allocations = allocations; } +NAN_METHOD(HeapProfiler::StartSamplingHeapProfiler) { + StartSampling(info, false); +} + +NAN_METHOD(HeapProfiler::RestartSamplingHeapProfiler) { + auto& state = PerIsolateData::For(info.GetIsolate())->GetHeapProfilerState(); + if (!state) { + return Nan::ThrowError("Heap profiler is not enabled."); + } + StartSampling(info, true); +} + // Signature: // stopSamplingHeapProfiler() NAN_METHOD(HeapProfiler::StopSamplingHeapProfiler) { @@ -211,6 +229,8 @@ NAN_MODULE_INIT(HeapProfiler::Init) { v8::Local heapProfiler = Nan::New(); Nan::SetMethod( heapProfiler, "startSamplingHeapProfiler", StartSamplingHeapProfiler); + Nan::SetMethod( + heapProfiler, "restartSamplingHeapProfiler", RestartSamplingHeapProfiler); Nan::SetMethod( heapProfiler, "stopSamplingHeapProfiler", StopSamplingHeapProfiler); Nan::SetMethod(heapProfiler, "getAllocationProfile", GetAllocationProfile); diff --git a/bindings/profilers/heap.hh b/bindings/profilers/heap.hh index aef0ef7e..431a418a 100644 --- a/bindings/profilers/heap.hh +++ b/bindings/profilers/heap.hh @@ -30,6 +30,9 @@ class HeapProfiler { // stopSamplingHeapProfiler() static NAN_METHOD(StopSamplingHeapProfiler); + // Restart V8 sampling while preserving OOM monitoring. + static NAN_METHOD(RestartSamplingHeapProfiler); + // Signature: // getAllocationProfile(): AllocationProfileNode static NAN_METHOD(GetAllocationProfile); diff --git a/ts/src/heap-profiler-bindings.ts b/ts/src/heap-profiler-bindings.ts index cc5d0d4e..2ac52239 100644 --- a/ts/src/heap-profiler-bindings.ts +++ b/ts/src/heap-profiler-bindings.ts @@ -38,6 +38,18 @@ export function startSamplingHeapProfiler( ); } +export function restartSamplingHeapProfiler( + heapIntervalBytes: number, + heapStackDepth: number, + allocations: boolean, +) { + profiler.heapProfiler.restartSamplingHeapProfiler( + heapIntervalBytes, + heapStackDepth, + allocations, + ); +} + export function stopSamplingHeapProfiler() { profiler.heapProfiler.stopSamplingHeapProfiler(); } diff --git a/ts/src/heap-profiler.ts b/ts/src/heap-profiler.ts index 9e265b10..4c4b4286 100644 --- a/ts/src/heap-profiler.ts +++ b/ts/src/heap-profiler.ts @@ -20,6 +20,7 @@ import { getAllocationProfile, mapAllocationProfile, startSamplingHeapProfiler, + restartSamplingHeapProfiler, stopSamplingHeapProfiler, monitorOutOfMemory as monitorOutOfMemoryImported, } from './heap-profiler-bindings'; @@ -113,15 +114,15 @@ function collectProfile( return processProfile(root); } finally { // In allocation mode V8 keeps every sampled object (live + collected-by-GC) - // in an append-only buffer that's only freed by stopSamplingHeapProfiler. + // in an append-only buffer that's only freed by stopping V8 sampling. // Without this reset, each call to getAllocationProfile re-reads the entire // history, so alloc_* totals grow linearly with wall-clock time and V8's // internal sample buffer leaks for the lifetime of the process. Reset even // if processing throws: the collected window is consumed either way, so it - // isn't counted again by the next collection. + // isn't counted again by the next collection. Preserve OOM monitoring + // when starting the next sampling interval. if (startedWithAllocations) { - stopSamplingHeapProfiler(); - startSamplingHeapProfiler(heapIntervalBytes, heapStackDepth, true); + restartSamplingHeapProfiler(heapIntervalBytes, heapStackDepth, true); } } } diff --git a/ts/test/oom-heap-limit-extension.ts b/ts/test/oom-heap-limit-extension.ts index 0e5320a9..740af460 100644 --- a/ts/test/oom-heap-limit-extension.ts +++ b/ts/test/oom-heap-limit-extension.ts @@ -23,6 +23,7 @@ import {heap, HeapLimitExtensionSize} from '../src/index'; const MB = 1024 * 1024; const CHUNK_SIZE = 4 * MB; const MAX_CHUNKS = 64; +const allocations = process.argv[3] === 'allocations'; const heapLimitExtensionSize: HeapLimitExtensionSize = process.argv[2] === 'auto' ? 'auto' : Number(process.argv[2] || 0); @@ -30,8 +31,9 @@ function heapLimit() { return v8.getHeapStatistics().heap_size_limit; } -heap.start(MB, 64); -heap.monitorOutOfMemory(heapLimitExtensionSize, 1, false); +heap.start(MB, 64, allocations); +heap.monitorOutOfMemory(heapLimitExtensionSize, 1, allocations); +if (allocations) heap.profile(); const initialLimit = heapLimit(); const retained: number[][] = []; diff --git a/ts/test/test-heap-profiler.ts b/ts/test/test-heap-profiler.ts index db48c24e..1e356324 100644 --- a/ts/test/test-heap-profiler.ts +++ b/ts/test/test-heap-profiler.ts @@ -83,6 +83,7 @@ const v8AllocationProfile: AllocationProfileNodeWithStats = { describe('HeapProfiler', () => { let startStub: sinon.SinonStub<[number, number, boolean?], void>; + let restartStub: sinon.SinonStub; let stopStub: sinon.SinonStub<[], void>; let profileStub: sinon.SinonStub< [], @@ -92,6 +93,7 @@ describe('HeapProfiler', () => { let memoryUsageStub: sinon.SinonStub<[], NodeJS.MemoryUsage>; beforeEach(() => { startStub = sinon.stub(v8HeapProfiler, 'startSamplingHeapProfiler'); + restartStub = sinon.stub(v8HeapProfiler, 'restartSamplingHeapProfiler'); stopStub = sinon.stub(v8HeapProfiler, 'stopSamplingHeapProfiler'); dateStub = sinon.stub(Date, 'now').returns(0); }); @@ -100,6 +102,7 @@ describe('HeapProfiler', () => { heapProfiler.stop(); startStub.restore(); stopStub.restore(); + restartStub.restore(); profileStub?.restore(); dateStub.restore(); memoryUsageStub?.restore(); @@ -200,8 +203,9 @@ describe('HeapProfiler', () => { }), /boom/, ); - sinon.assert.calledOnce(stopStub); - sinon.assert.calledOnceWithExactly(startStub, 1024 * 512, 32, true); + sinon.assert.notCalled(stopStub); + sinon.assert.notCalled(startStub); + sinon.assert.calledOnceWithExactly(restartStub, 1024 * 512, 32, true); }); it('should use allocation profile mode when allocations is passed', async () => { @@ -426,11 +430,32 @@ describe('foreign heap sampler', () => { }); describe('OOMMonitoring', () => { - async function runOomFixture(script: string, heapLimitExtensionSize: string) { - const proc = fork(path.join(__dirname, script), [heapLimitExtensionSize], { - execArgv: ['--expose-gc', '--max-old-space-size=64'], - silent: true, - }); + it('should dump an OOM profile after an allocation collection', async function () { + if (Number(process.versions.node.split('.')[0]) < 26) this.skip(); + this.timeout(30000); + const {output} = await runOomFixture( + 'oom-heap-limit-extension.js', + '0', + 'allocations', + ); + assert.ok(output.includes('FATAL ERROR:'), output); + assert.ok(output.includes('NearHeapLimit(count=1)'), output); + assert.ok(output.includes(':leak:'), output); + }); + + async function runOomFixture( + script: string, + heapLimitExtensionSize: string, + mode = '', + ) { + const proc = fork( + path.join(__dirname, script), + [heapLimitExtensionSize, mode], + { + execArgv: ['--expose-gc', '--max-old-space-size=64'], + silent: true, + }, + ); let output = ''; proc.stdout?.on('data', chunk => {