Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions bindings/profilers/heap.cc
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ static void HeapProfilerCleanupHook(void* data) {
}
}

NAN_METHOD(HeapProfiler::StartSamplingHeapProfiler) {
static void StartSampling(const Nan::FunctionCallbackInfo<v8::Value>& info,
bool restart) {
auto isolate = info.GetIsolate();

// Register cleanup hook if not already registered for this isolate
Expand Down Expand Up @@ -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(
Expand All @@ -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) {
Expand Down Expand Up @@ -211,6 +229,8 @@ NAN_MODULE_INIT(HeapProfiler::Init) {
v8::Local<v8::Object> heapProfiler = Nan::New<v8::Object>();
Nan::SetMethod(
heapProfiler, "startSamplingHeapProfiler", StartSamplingHeapProfiler);
Nan::SetMethod(
heapProfiler, "restartSamplingHeapProfiler", RestartSamplingHeapProfiler);
Nan::SetMethod(
heapProfiler, "stopSamplingHeapProfiler", StopSamplingHeapProfiler);
Nan::SetMethod(heapProfiler, "getAllocationProfile", GetAllocationProfile);
Expand Down
3 changes: 3 additions & 0 deletions bindings/profilers/heap.hh
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
12 changes: 12 additions & 0 deletions ts/src/heap-profiler-bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
9 changes: 5 additions & 4 deletions ts/src/heap-profiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
getAllocationProfile,
mapAllocationProfile,
startSamplingHeapProfiler,
restartSamplingHeapProfiler,
stopSamplingHeapProfiler,
monitorOutOfMemory as monitorOutOfMemoryImported,
} from './heap-profiler-bindings';
Expand Down Expand Up @@ -113,15 +114,15 @@ function collectProfile<T>(
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);
}
}
}
Expand Down
6 changes: 4 additions & 2 deletions ts/test/oom-heap-limit-extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,17 @@ 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);

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[][] = [];
Expand Down
39 changes: 32 additions & 7 deletions ts/test/test-heap-profiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<
[],
Expand All @@ -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);
});
Expand All @@ -100,6 +102,7 @@ describe('HeapProfiler', () => {
heapProfiler.stop();
startStub.restore();
stopStub.restore();
restartStub.restore();
profileStub?.restore();
dateStub.restore();
memoryUsageStub?.restore();
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 => {
Expand Down
Loading