diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 30a51876..3a050113 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -64,19 +64,7 @@ jobs: - name: Release notes env: GH_TOKEN: ${{ steps.octo-sts.outputs.token }} - VERSION: ${{ fromJson(steps.pkg.outputs.json).version }} - run: | - # The release notes are the body of the proposal PR, looked up by its - # head branch. This resolves even after the branch is deleted on merge. - notes="$RUNNER_TEMP/v$VERSION.md" - gh pr view "v$VERSION-proposal" --json body --jq .body > "$notes" - # v5.x is currently the only release line. Once a second one ships, - # --latest has to be decided per branch rather than hardcoded. - if gh release view "v$VERSION" > /dev/null 2>&1; then - gh release edit "v$VERSION" --title "$VERSION" -F "$notes" --latest - else - gh release create "v$VERSION" --target "${{ github.ref_name }}" --title "$VERSION" -F "$notes" --latest - fi + run: node scripts/release-notes.js publish_dev: needs: build diff --git a/bindings/profilers/heap.cc b/bindings/profilers/heap.cc index 3b87fad1..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 @@ -89,15 +90,19 @@ NAN_METHOD(HeapProfiler::StartSamplingHeapProfiler) { #if NODE_MAJOR_VERSION >= 26 if (allocations) { flags = static_cast( - v8::HeapProfiler::kSamplingForceGC | v8::HeapProfiler::kSamplingIncludeObjectsCollectedByMajorGC | v8::HeapProfiler::kSamplingIncludeObjectsCollectedByMinorGC); } #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( @@ -111,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) { @@ -212,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/package-lock.json b/package-lock.json index 2a6d4ec5..63c70b7b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@datadog/pprof", - "version": "5.20.0", + "version": "5.20.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@datadog/pprof", - "version": "5.20.0", + "version": "5.20.1", "license": "Apache-2.0", "dependencies": { "node-gyp-build": "^4.8.4", @@ -15,20 +15,20 @@ }, "devDependencies": { "@types/mocha": "^10.0.1", - "@types/node": "26.6.3", + "@types/node": "26.6.6", "@types/semver": "^7.8.0", - "@types/sinon": "^22.0.0", + "@types/sinon": "^22.0.2", "@types/tmp": "^0.2.3", "clang-format": "^1.8.0", "codecov": "^3.8.3", "deep-copy": "^1.4.2", - "eslint-plugin-n": "^18.4.0", + "eslint-plugin-n": "^18.5.0", "gts": "^7.0.0", "js-green-licenses": "^4.0.0", "mocha": "^11.8.0", - "nan": "^2.29.0", + "nan": "^2.30.0", "nyc": "^18.0.0", - "semver": "^7.8.5", + "semver": "^7.8.6", "sinon": "^22.1.0", "source-map-support": "^0.5.21", "tmp": "0.2.7", @@ -962,9 +962,9 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "26.6.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.3.tgz", - "integrity": "sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg==", + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", "dev": true, "license": "MIT", "dependencies": { @@ -996,22 +996,15 @@ "license": "MIT" }, "node_modules/@types/sinon": { - "version": "22.0.0", - "resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-22.0.0.tgz", - "integrity": "sha512-TDbVpbccc2HfiqHR09Argj3mHV1KMW7sCCKj52fsl8lbRLkEn7fB1966EWhOKWUBcqfBueZuPoA7/OK1CKiy3g==", + "version": "22.0.2", + "resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-22.0.2.tgz", + "integrity": "sha512-2qLRFlluKkn6mci189eKhlOsHcdFpsn/9+29S4VmwKCpfb+vseKrZSSOSy5259yzIpP/y4gLfqQfIIR/lZn4Ng==", "dev": true, "license": "MIT", "dependencies": { - "@types/sinonjs__fake-timers": "*" + "@sinonjs/fake-timers": "^15.4.0" } }, - "node_modules/@types/sinonjs__fake-timers": { - "version": "8.1.5", - "resolved": "https://registry.npmjs.org/@types/sinonjs__fake-timers/-/sinonjs__fake-timers-8.1.5.tgz", - "integrity": "sha512-mQkU2jY8jJEF7YHjHvsQO8+3ughTL1mcnn96igfhONmR+fUPSKIkefQYpSe8bsly2Ep7oQbn/6VG5/9/0qcArQ==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/tmp": { "version": "0.2.6", "resolved": "https://registry.npmjs.org/@types/tmp/-/tmp-0.2.6.tgz", @@ -2245,9 +2238,9 @@ } }, "node_modules/eslint-plugin-n": { - "version": "18.4.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-n/-/eslint-plugin-n-18.4.0.tgz", - "integrity": "sha512-TEm6Nqn9+l7EWfJXOL6pmrEdpiM2ZTgo4fNMRDvBTM70jeQ7x3X3Akcx+sRCIRfpcSVwMypH3ZAA33PLyNKmYw==", + "version": "18.5.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-n/-/eslint-plugin-n-18.5.0.tgz", + "integrity": "sha512-M7uF6MTN/An+AXqvyIbXq7npJIZOkd5eKo8iMMvWrcDVNyZVdA6TF2lw01aKQfCEidRfpnR78GhAjZorlXNHiw==", "dev": true, "license": "MIT", "dependencies": { @@ -4321,9 +4314,9 @@ "license": "ISC" }, "node_modules/nan": { - "version": "2.29.0", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.29.0.tgz", - "integrity": "sha512-GlGk3HIvitbvs+LT3g6XUP1kpirKNvmDFwF/bmo6XNWSb/eYEs/O4bfgIEIXCZ+lIOTS5xNwDvSGMw6FJdAhtA==", + "version": "2.30.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.30.0.tgz", + "integrity": "sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==", "dev": true, "license": "MIT" }, @@ -5672,9 +5665,9 @@ "license": "MIT" }, "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { diff --git a/package.json b/package.json index 5578f6c8..0aef24b2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@datadog/pprof", - "version": "5.20.0", + "version": "5.20.1", "description": "pprof support for Node.js", "repository": { "type": "git", @@ -43,20 +43,20 @@ }, "devDependencies": { "@types/mocha": "^10.0.1", - "@types/node": "26.6.3", + "@types/node": "26.6.6", "@types/semver": "^7.8.0", - "@types/sinon": "^22.0.0", + "@types/sinon": "^22.0.2", "@types/tmp": "^0.2.3", "clang-format": "^1.8.0", "codecov": "^3.8.3", "deep-copy": "^1.4.2", - "eslint-plugin-n": "^18.4.0", + "eslint-plugin-n": "^18.5.0", "gts": "^7.0.0", "js-green-licenses": "^4.0.0", "mocha": "^11.8.0", - "nan": "^2.29.0", + "nan": "^2.30.0", "nyc": "^18.0.0", - "semver": "^7.8.5", + "semver": "^7.8.6", "sinon": "^22.1.0", "source-map-support": "^0.5.21", "tmp": "0.2.7", diff --git a/scripts/release-notes.js b/scripts/release-notes.js new file mode 100644 index 00000000..174fc2ac --- /dev/null +++ b/scripts/release-notes.js @@ -0,0 +1,99 @@ +'use strict' + +// Usage: node scripts/release-notes.js [version] [--dry-run] +// +// Publishes the release proposal PR's body as the GitHub release notes for +// that version, expanding bare pull request references into their titles. +// +// The proposal PR is resolved by its head branch, which keeps working after +// the branch is deleted on merge. `--latest` is hardcoded because v5.x is the +// only release line; once a second one ships it has to be decided per branch. + +const { execFileSync } = require('child_process') +const { writeFileSync } = require('fs') +const { join } = require('path') +const { tmpdir } = require('os') + +const owner = 'DataDog' +const name = 'pprof-nodejs' +const repo = `${owner}/${name}` + +const args = process.argv.slice(2) +const dryRun = args.includes('--dry-run') +const version = args.find(arg => !arg.startsWith('--')) || require('../package.json').version +const tag = `v${version}` + +function gh (params) { + return execFileSync('gh', params, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }).trim() +} + +function ghSucceeds (params) { + try { + gh(params) + return true + } catch { + return false + } +} + +function readTitles (numbers) { + const titles = new Map() + if (numbers.length === 0) return titles + + const fields = numbers + .map(number => `pr${number}: pullRequest(number: ${number}) { number title }`) + .join(' ') + const response = JSON.parse(gh([ + 'api', 'graphql', '-f', + `query=query { repository(owner: "${owner}", name: "${name}") { ${fields} } }` + ])) + + if (response.errors && response.errors.length > 0) { + throw new Error(`Pull request title lookup failed: ${response.errors[0].message}`) + } + + for (const pullRequest of Object.values(response.data.repository)) { + if (pullRequest) titles.set(String(pullRequest.number), pullRequest.title) + } + + return titles +} + +// Only a list item that is nothing but a reference is expanded, so bodies that +// already spell out their titles are left exactly as the author wrote them. +const bareReference = /^([ \t]*[-*][ \t]+)#(\d+)[ \t]*$/gm + +const body = gh(['pr', 'view', `${tag}-proposal`, '--repo', repo, '--json', 'body', '--jq', '.body']) + .replace(/\r\n/g, '\n') +const numbers = [...new Set([...body.matchAll(bareReference)].map(match => match[2]))] +const titles = readTitles(numbers) +const notes = body.replace(bareReference, (line, bullet, number) => { + const title = titles.get(number) + return title ? `${bullet}${title} (#${number})` : line +}) + +if (dryRun) { + console.log(notes) + process.exit(0) +} + +const file = join(process.env.RUNNER_TEMP || tmpdir(), `${tag}.md`) +writeFileSync(file, notes) + +const exists = ghSucceeds(['release', 'view', tag, '--repo', repo, '--json', 'tagName']) +const prerelease = version.includes('-') + +// --verify-tag keeps a lagging tag push from silently creating the tag on the +// default branch instead of on the release commit. +const params = [ + 'release', exists ? 'edit' : 'create', tag, + '--repo', repo, + '--verify-tag', + '--title', version, + '--notes-file', file, + prerelease ? '--latest=false' : '--latest' +] + +if (prerelease) params.push('--prerelease') + +console.log(gh(params)) 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 e520d45e..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'; @@ -92,23 +93,38 @@ export function profile( generateLabels?: GenerateAllocationLabelsFunction, columnNumbers: ColumnNumbers = DEFAULT_COLUMN_NUMBERS, ): Profile { - const result = convertProfile( - v8Profile(), - ignoreSamplePath, - sourceMapper, - generateLabels, - columnNumbers, + return collectProfile(root => + convertProfile( + root, + ignoreSamplePath, + sourceMapper, + generateLabels, + columnNumbers, + ), ); - // In allocation mode V8 keeps every sampled object (live + collected-by-GC) - // in an append-only buffer that's only freed by stopSamplingHeapProfiler. - // 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. - if (startedWithAllocations) { - stopSamplingHeapProfiler(); - startSamplingHeapProfiler(heapIntervalBytes, heapStackDepth, true); +} + +function collectProfile( + processProfile: ( + root: AllocationProfileNode | AllocationProfileNodeWithStats, + ) => T, +): T { + const root = v8Profile(); + try { + 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 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. Preserve OOM monitoring + // when starting the next sampling interval. + if (startedWithAllocations) { + restartSamplingHeapProfiler(heapIntervalBytes, heapStackDepth, true); + } } - return result; } export function convertProfile( @@ -204,9 +220,8 @@ export function profileV2( * @param intervalBytes - average number of bytes between samples. * @param stackDepth - maximum stack depth for samples collected. * @param allocations - include total allocation samples in the profile. - * When true, each call to `profile()` forces a full GC (via - * v8::HeapProfiler::kSamplingForceGC) to classify sampled objects as - * live/dead, which adds a measurable pause. Requires Node.js >= 26. + * Retains samples of objects collected by GC. Liveness reflects the most + * recent GC; collecting a profile does not force one. Requires Node.js >= 26. */ export function start( intervalBytes: number, diff --git a/ts/src/profile-serializer.ts b/ts/src/profile-serializer.ts index 5d5ebb36..0e5d349c 100644 --- a/ts/src/profile-serializer.ts +++ b/ts/src/profile-serializer.ts @@ -222,7 +222,11 @@ function serialize( } } } - const keyStr = `${node.scriptId}:${profLoc.line}:${profLoc.column}:${profLoc.name}`; + // The resolved file is part of a location's identity: after source + // mapping, one script can map to several original files. The file's + // length makes the key unambiguous. + const file = profLoc.file || ''; + const keyStr = `${node.scriptId}:${profLoc.line}:${profLoc.column}:${profLoc.missingMapFile ? 1 : 0}:${file.length}:${file}:${profLoc.name}`; let id = locationIdMap.get(keyStr); if (id !== undefined) { // id is index+1, since 0 is not valid id. @@ -259,9 +263,14 @@ function serialize( function getFunction(loc: SourceLocation, scriptId?: number): Function { let name = loc.name; + // A function is identified by script, file and name, or by script, file + // and position for anonymous functions; the prefixes keep the two kinds + // apart. The file matters because after source mapping, one script can + // map to several original files. + const file = loc.file || ''; const keyStr = name - ? `${scriptId}:${name}` - : `${scriptId}:${loc.line}:${loc.column}`; + ? `n:${scriptId}:${file.length}:${file}:${name}` + : `a:${scriptId}:${loc.line}:${loc.column}:${file}`; let id = functionIdMap.get(keyStr); if (id !== undefined) { // id is index+1, since 0 is not valid id. diff --git a/ts/src/time-profiler.ts b/ts/src/time-profiler.ts index d57b94fb..294b5835 100644 --- a/ts/src/time-profiler.ts +++ b/ts/src/time-profiler.ts @@ -178,6 +178,23 @@ export function stop( generateLabels?: GenerateTimeLabelsFunction, lowCardinalityLabels?: string[], ): Profile { + return stopAndProcess(restart, profile => + serializeTimeProfile( + profile, + gIntervalMicros, + gSourceMapper, + true, + generateLabels, + lowCardinalityLabels, + gColumnNumbers, + ), + ); +} + +function stopAndProcess( + restart: boolean, + processProfile: (profile: TimeProfile) => T, +): T { if (!gProfiler) { throw new Error('Wall profiler is not started'); } @@ -185,31 +202,55 @@ export function stop( const profile = gProfiler.stop(restart); if (restart) { - // Restart the profiler *before* serializing so the cost of serialization is + // Restart the profiler *before* processing so the cost of processing is // captured in the next profile. handleStopRestart() does not dispose of the // source mapper, so the source-map resolution below is unaffected. handleStopRestart(); + return processProfile(profile); } - const serializedProfile = serializeTimeProfile( - profile, - gIntervalMicros, - gSourceMapper, - true, - generateLabels, - lowCardinalityLabels, - gColumnNumbers, - ); - - if (!restart) { - // Tear down *after* serializing: handleStopNoRestart() clears gSourceMapper - // (and disposes gProfiler), so serializing afterwards would drop source-map + try { + return processProfile(profile); + } finally { + // Tear down *after* processing: handleStopNoRestart() clears gSourceMapper + // (and disposes gProfiler), so processing afterwards would drop source-map // resolution and leave transpiled frames pointing at the generated files - // instead of the original sources. + // instead of the original sources. Tear down even if processing throws, + // since the native profiler has already stopped. handleStopNoRestart(); } +} - return serializedProfile; +/** + * Stops the profiler through the lazy native path, which passes the profile + * to `processProfile` while the native profile is still alive. Updates the JS + * state for the stop or restart even if `processProfile` throws, because the + * native profiler has already stopped (and restarted) by then. If the native + * stop itself fails, the state is left as it was. + */ +function stopAndCollect( + restart: boolean, + processProfile: (profile: TimeProfile) => T, +): T { + if (!gProfiler) { + throw new Error('Wall profiler is not started'); + } + + let stopped = false; + try { + return gProfiler.stopAndCollect(restart, (profile: TimeProfile) => { + stopped = true; + return processProfile(profile); + }); + } finally { + if (stopped) { + if (restart) { + handleStopRestart(); + } else { + handleStopNoRestart(); + } + } + } } /** @@ -222,29 +263,17 @@ export function stopV2( generateLabels?: GenerateTimeLabelsFunction, lowCardinalityLabels?: string[], ) { - if (!gProfiler) { - throw new Error('Wall profiler is not started'); - } - - const serializedProfile = gProfiler.stopAndCollect( - restart, - (profile: TimeProfile) => - serializeTimeProfile( - profile, - gIntervalMicros, - gSourceMapper, - true, - generateLabels, - lowCardinalityLabels, - gColumnNumbers, - ), + return stopAndCollect(restart, (profile: TimeProfile) => + serializeTimeProfile( + profile, + gIntervalMicros, + gSourceMapper, + true, + generateLabels, + lowCardinalityLabels, + gColumnNumbers, + ), ); - if (restart) { - handleStopRestart(); - } else { - handleStopNoRestart(); - } - return serializedProfile; } export function getState() { diff --git a/ts/src/v8-types.ts b/ts/src/v8-types.ts index 9422d283..6221326f 100644 --- a/ts/src/v8-types.ts +++ b/ts/src/v8-types.ts @@ -17,10 +17,10 @@ // Type Definitions based on implementation in bindings/ export interface TimeProfile { - /** Time in nanoseconds at which profile was stopped. */ + /** V8 timer value, in microseconds, at which profile was stopped. */ endTime: number; topDownRoot: TimeProfileNode; - /** Time in nanoseconds at which profile was started. */ + /** V8 timer value, in microseconds, at which profile was started. */ startTime: number; hasCpuTime?: boolean; /** CPU time of non-JS threads, only reported for the main worker thread */ 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 26bcca70..1e356324 100644 --- a/ts/test/test-heap-profiler.ts +++ b/ts/test/test-heap-profiler.ts @@ -23,7 +23,7 @@ import { AllocationProfileNodeWithStats, LabelSet, } from '../src/v8-types'; -import {fork} from 'child_process'; +import {execFileSync, fork} from 'child_process'; import path from 'path'; import fs from 'fs'; @@ -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(); @@ -180,6 +183,31 @@ describe('HeapProfiler', () => { assert.deepEqual(heapProfileIncludePathWithLabels, profile); }); + it('should reset the allocation window even when processing throws', async () => { + profileStub = sinon + .stub(v8HeapProfiler, 'getAllocationProfile') + .returns(copy(v8AllocationProfile)); + memoryUsageStub = sinon.stub(process, 'memoryUsage').returns({ + external: 0, + rss: 2048, + heapTotal: 4096, + heapUsed: 2048, + arrayBuffers: 512, + }); + heapProfiler.start(1024 * 512, 32, true); + startStub.resetHistory(); + assert.throws( + () => + heapProfiler.profile(undefined, undefined, () => { + throw new Error('boom'); + }), + /boom/, + ); + 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 () => { profileStub = sinon .stub(v8HeapProfiler, 'getAllocationProfile') @@ -330,6 +358,31 @@ describe('HeapProfiler', () => { }); }); +it('should collect allocation profiles without forcing GC', function () { + this.timeout(30000); + if (Number(process.versions.node.split('.')[0]) < 26) this.skip(); + + const output = execFileSync( + process.execPath, + [ + '--trace-gc', + '-e', + ` + const heap = require(${JSON.stringify(require.resolve('../src/heap-profiler'))}); + heap.start(512 * 1024, 64, true); + global.retained = Array.from({length: 200000}, (_, i) => ({i})); + console.time('10 allocation profiles'); + for (let i = 0; i < 10; i++) heap.profile(); + console.timeEnd('10 allocation profiles'); + heap.stop(); + `, + ], + {encoding: 'utf8', timeout: 25000}, + ); + console.log(output.trim()); + assert.doesNotMatch(output, /sampling profiler/); +}); + describe('foreign heap sampler', () => { // Regression test: V8's sampling heap profiler can be enabled by something // other than pprof (inspector, DevTools, another agent). getAllocationProfile @@ -377,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 => { diff --git a/ts/test/test-profile-serializer.ts b/ts/test/test-profile-serializer.ts index 5ad6d488..7beed1f7 100644 --- a/ts/test/test-profile-serializer.ts +++ b/ts/test/test-profile-serializer.ts @@ -236,6 +236,75 @@ describe('profile-serializer', () => { }); }); + describe('frame identity', () => { + const makeProfile = (children: TimeProfileNode[]): TimeProfile => ({ + startTime: 0, + endTime: 10 * 1000 * 1000, + topDownRoot: { + name: '(root)', + scriptName: 'root', + scriptId: 0, + lineNumber: 0, + columnNumber: 0, + hitCount: 0, + children, + }, + }); + const leaf = (props: Partial): TimeProfileNode => ({ + name: 'foo', + scriptName: 'script.js', + scriptId: 1, + lineNumber: 1, + columnNumber: 1, + hitCount: 1, + children: [], + ...props, + }); + + it('should keep frames from different original files apart', () => { + // One generated script whose two positions map to different original + // files, with the same function name and position + const sourceMapper = { + mappingInfo: (loc: {line: number}) => ({ + file: loc.line === 1 ? '/app/a.ts' : '/app/b.ts', + line: 1, + column: 1, + name: 'render', + }), + } as unknown as SourceMapper; + const profile = serializeTimeProfile( + makeProfile([ + leaf({scriptId: 42, lineNumber: 1, columnNumber: 5}), + leaf({scriptId: 42, lineNumber: 2, columnNumber: 5}), + ]), + 1000, + sourceMapper, + ); + const strings = profile.stringTable.strings; + assert.deepStrictEqual( + profile.function.map(f => strings[Number(f.filename)]).sort(), + ['/app/a.ts', '/app/b.ts'], + ); + assert.strictEqual(profile.location.length, 2); + }); + + it('should keep named and anonymous functions apart', () => { + // A function named like an anonymous function's position + const profile = serializeTimeProfile( + makeProfile([ + leaf({name: '1:1', lineNumber: 5, columnNumber: 5}), + leaf({name: '', lineNumber: 1, columnNumber: 1}), + ]), + 1000, + ); + const strings = profile.stringTable.strings; + assert.deepStrictEqual( + profile.function.map(f => strings[Number(f.name)]).sort(), + ['(anonymous:L#1:C#1)', '1:1'], + ); + }); + }); + describe('label builder', () => { it('should accept strings, numbers, and bigints', () => { const profileOut = serializeTimeProfile(labelEncodingProfile, 1000); diff --git a/ts/test/test-time-profiler.ts b/ts/test/test-time-profiler.ts index 1738ee94..112a584e 100644 --- a/ts/test/test-time-profiler.ts +++ b/ts/test/test-time-profiler.ts @@ -498,6 +498,20 @@ describe('Time Profiler', () => { assert.deepEqual(timeProfile, profile); }); + it('should stay usable when processing the stopped profile throws', () => { + const boom = () => { + throw new Error('boom'); + }; + time.start({intervalMicros: PROFILE_OPTIONS.intervalMicros}); + assert.throws(() => time.stop(false, boom), /boom/); + assert.ok(!time.isStarted(), 'stopped despite the error'); + time.start({intervalMicros: PROFILE_OPTIONS.intervalMicros}); + assert.throws(() => time.stop(true, boom), /boom/); + assert.ok(time.isStarted(), 'still running after a restart'); + time.stop(); + assert.ok(!time.isStarted()); + }); + it('should be able to restart when stopping', async () => { time.start({intervalMicros: PROFILE_OPTIONS.intervalMicros}); timeProfilerStub.start.resetHistory(); @@ -683,6 +697,20 @@ describe('Time Profiler', () => { assert.deepEqual(timeProfile, profile); }); + it('should stay usable when processing the stopped profile throws', () => { + const boom = () => { + throw new Error('boom'); + }; + time.start({intervalMicros: PROFILE_OPTIONS.intervalMicros}); + assert.throws(() => stopV2(false, boom), /boom/); + assert.ok(!time.isStarted(), 'stopped despite the error'); + time.start({intervalMicros: PROFILE_OPTIONS.intervalMicros}); + assert.throws(() => stopV2(true, boom), /boom/); + assert.ok(time.isStarted(), 'still running after a restart'); + stopV2(); + assert.ok(!time.isStarted()); + }); + it('should be able to restart when stopping', async () => { time.start({intervalMicros: PROFILE_OPTIONS.intervalMicros}); timeProfilerStub.start.resetHistory();