Skip to content

feat: capture JS stack trace on renderer OOM - #50043

Merged
jkleinsc merged 16 commits into
electron:mainfrom
alexkozy:feat/oom-js-stack-trace
Apr 10, 2026
Merged

jkleinsc merged 16 commits into
electron:mainfrom
alexkozy:feat/oom-js-stack-trace

Conversation

@alexkozy

@alexkozy alexkozy commented Mar 3, 2026 •

Copy link
Copy Markdown
Contributor

Description of Change

When a renderer process approaches its V8 heap limit, capture the JavaScript stack trace and write it to both a Crashpad crash key ("js-oom-stack") and stderr.

The stack trace is captured via RequestInterrupt rather than directly inside the NearHeapLimitCallback because CurrentStackTrace is unsafe to call during OOM — V8 FATALs on optimized (TurboFan) frames that have had their deoptimization data garbage-collected. RequestInterrupt defers the capture to the next V8 safe point, where all frames are guaranteed to have deopt data available. This matches Node.js's approach of never capturing JS stacks inside the heap limit callback.

The callback is registered once per isolate via an atomic guard in RendererClientBase::DidCreateScriptContext, preventing the CHECK failure V8 raises on duplicate AddNearHeapLimitCallback registrations (which would otherwise occur on page navigations or multiple contexts).

Fixes #46078

Checklist

  • PR description included
  • I have built and tested this PR
  • npm test passes
  • tests are added

Release Notes

Notes: Added JS stack trace to crash reports on renderer OOM.

@electron-cation electron-cation Bot added the new-pr 🌱 PR opened recently label Mar 3, 2026
Comment thread shell/renderer/oom_stack_trace.cc Resolved
@codebytere codebytere added semver/minor backwards-compatible functionality api-review/requested 🗳 labels Mar 3, 2026
@alexkozy
alexkozy force-pushed the feat/oom-js-stack-trace branch from 4c344e3 to 52c5dbd Compare March 5, 2026 07:55

@codebytere codebytere left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API LGTM

nikwen
nikwen previously requested changes Mar 5, 2026

@nikwen nikwen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great PR! Thank you.

@deepak1556 It would be great if you could take a look as well. Especially to make sure that the pattern of bumping the heap limit to then make more allocations is safe in an OOM scenario.

Comment thread shell/renderer/oom_stack_trace.cc Resolved
Comment thread shell/renderer/oom_stack_trace.cc Resolved
Comment thread shell/renderer/oom_stack_trace.cc Resolved
Comment thread shell/renderer/oom_stack_trace.cc Resolved
@nikwen
nikwen requested a review from deepak1556 March 5, 2026 12:30
@nikwen

nikwen commented Mar 5, 2026

Copy link
Copy Markdown
Member

You will also need to sign your commits. Otherwise, we can't merge them.

@alexkozy
alexkozy force-pushed the feat/oom-js-stack-trace branch 2 times, most recently from 0b63075 to 312ff96 Compare March 5, 2026 14:16
@nikwen

nikwen commented Mar 5, 2026

Copy link
Copy Markdown
Member

Thanks for the changes and for signing your commits!

Looks like there is still a small linter error:

--- a/shell/renderer/oom_stack_trace.cc
+++ b/shell/renderer/oom_stack_trace.cc
@@ -95,10 +95,9 @@
 
   v8::HeapStatistics stats;
   isolate->GetHeapStatistics(&stats);
-  std::string heap_info =
-      absl::StrFormat("Heap: used=%.1fMB limit=%.1fMB",
-                      stats.used_heap_size() / 1048576.0,
-                      stats.heap_size_limit() / 1048576.0);
+  std::string heap_info = absl::StrFormat("Heap: used=%.1fMB limit=%.1fMB",
+                                          stats.used_heap_size() / 1048576.0,
+                                          stats.heap_size_limit() / 1048576.0);
   fprintf(stderr, "\n<--- Near heap limit --->\n%s\n", heap_info.c_str());
   fflush(stderr);

@nikwen
nikwen dismissed their stale review March 5, 2026 17:11

Requested changes have been made. Not approving yet because Deepak should take a look at this, too, in my opinion.

@electron-cation electron-cation Bot removed the new-pr 🌱 PR opened recently label Mar 10, 2026
@alexkozy

Copy link
Copy Markdown
Contributor Author

@deepak1556 this change will help us a lot on our side to investigate ooms. I would really appreciate review.

@deepak1556

Copy link
Copy Markdown
Member

Apologies for the delay, taking a look now.

Comment thread shell/renderer/oom_stack_trace.cc Resolved

@deepak1556 deepak1556 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like that we are waiting for the next possible execution point to capture the stack trace but I am unsure if the captured stack is useful for all the different cases (ineffective mark-compact, old space exhaustion) given the implementation only captures once at the heap limit, it wouldn't tell effectively what led to it. V8 seems to capture heap stats https://source.chromium.org/chromium/chromium/src/+/main:v8/src/heap/heap.cc;l=5337-5419; as crash keys but it gets missed today due to the OOM callback override in

void V8OOMErrorCallback(const char* location, const v8::OOMDetails& details) {
const char* message =
details.is_heap_oom ? "Allocation failed - JavaScript heap out of memory"
: "Allocation failed - process out of memory";
if (location) {
LOG(ERROR) << "OOM error in V8: " << location << " " << message;
} else {
LOG(ERROR) << "OOM error in V8: " << message;
}
if (details.detail) {
LOG(ERROR) << "OOM detail: " << details.detail;
}
#if !IS_MAS_BUILD()
electron::crash_keys::SetCrashKey("electron.v8-oom.is_heap_oom",
base::NumberToString(details.is_heap_oom));
if (location) {
electron::crash_keys::SetCrashKey("electron.v8-oom.location", location);
}
if (details.detail) {
electron::crash_keys::SetCrashKey("electron.v8-oom.detail", details.detail);
}
#endif
OOM_CRASH(0);
}
wonder if we can include that to get some more heuristics in the dump.

Comment thread shell/renderer/oom_stack_trace.cc Resolved
Comment thread shell/renderer/oom_stack_trace.cc Resolved
@jkleinsc

Copy link
Copy Markdown
Member

API LGTM

@erickzhao erickzhao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API LGTM

@alexkozy
alexkozy force-pushed the feat/oom-js-stack-trace branch from 9748e4f to dae25b2 Compare April 3, 2026 03:43
@github-actions

github-actions Bot commented Apr 3, 2026

Copy link
Copy Markdown
Contributor

⚠️ This PR contains unsigned commits. This repository enforces commit signatures
for all incoming PRs. To get your PR merged, please sign those commits
(git rebase --exec 'git commit -S --amend --no-edit -n' @{upstream}) and force push them to this branch
(git push --force-with-lease)

For more information on signing commits, see GitHub's documentation on Telling Git about your signing key.

@github-actions github-actions Bot added the needs-signed-commits Currently some or all of the commits in this PR are not signed label Apr 3, 2026
@alexkozy
alexkozy force-pushed the feat/oom-js-stack-trace branch 2 times, most recently from 23827b8 to fc3101e Compare April 4, 2026 01:15
@alexkozy

alexkozy commented Apr 4, 2026

Copy link
Copy Markdown
Contributor Author

I like that we are waiting for the next possible execution point to capture the stack trace but I am unsure if the captured stack is useful for all the different cases (ineffective mark-compact, old space exhaustion) given the implementation only captures once at the heap limit, it wouldn't tell effectively what led to it. V8 seems to capture heap stats https://source.chromium.org/chromium/chromium/src/+/main:v8/src/heap/heap.cc;l=5337-5419; as crash keys but it gets missed today due to the OOM callback override in

void V8OOMErrorCallback(const char* location, const v8::OOMDetails& details) {
const char* message =
details.is_heap_oom ? "Allocation failed - JavaScript heap out of memory"
: "Allocation failed - process out of memory";
if (location) {
LOG(ERROR) << "OOM error in V8: " << location << " " << message;
} else {
LOG(ERROR) << "OOM error in V8: " << message;
}
if (details.detail) {
LOG(ERROR) << "OOM detail: " << details.detail;
}
#if !IS_MAS_BUILD()
electron::crash_keys::SetCrashKey("electron.v8-oom.is_heap_oom",
base::NumberToString(details.is_heap_oom));
if (location) {
electron::crash_keys::SetCrashKey("electron.v8-oom.location", location);
}
if (details.detail) {
electron::crash_keys::SetCrashKey("electron.v8-oom.detail", details.detail);
}
#endif
OOM_CRASH(0);
}

wonder if we can include that to get some more heuristics in the dump.

Added a bunch of statistics.

@deepak1556, sorry for the delay in addressing comments. Please take another look. I will address concerns promptly.

@jkleinsc
jkleinsc merged commit 8d8847d into electron:main Apr 10, 2026
119 of 120 checks passed
@release-clerk

release-clerk Bot commented Apr 10, 2026

Copy link
Copy Markdown

Release Notes Persisted

Added JS stack trace to crash reports on renderer OOM.

@trop

trop Bot commented Apr 10, 2026

Copy link
Copy Markdown
Contributor

I was unable to backport this PR to "41-x-y" cleanly;
you will need to perform this backport manually.

@trop trop Bot added needs-manual-bp/41-x-y and removed target/41-x-y PR should also be added to the "41-x-y" branch. labels Apr 10, 2026
@trop

trop Bot commented Apr 10, 2026

Copy link
Copy Markdown
Contributor

I have automatically backported this PR to "42-x-y", please check out #50911

@trop trop Bot added in-flight/42-x-y and removed target/42-x-y PR should also be added to the "42-x-y" branch. labels Apr 10, 2026
@trop

trop Bot commented Apr 10, 2026

Copy link
Copy Markdown
Contributor

@alexkozy has manually backported this PR to "41-x-y", please check out #50912

alexkozy added a commit to alexkozy/electron that referenced this pull request Apr 10, 2026
* feat: capture JS stack trace on renderer OOM

When a renderer process approaches its V8 heap limit, capture the
JavaScript stack trace and write it to both a Crashpad crash key
("js-oom-stack") and stderr.

The stack trace is captured via RequestInterrupt rather than directly
inside the NearHeapLimitCallback because CurrentStackTrace is unsafe
to call during OOM — V8 FATALs on optimized (TurboFan) frames that
have had their deoptimization data garbage-collected. RequestInterrupt
defers the capture to the next V8 safe point, where all frames are
guaranteed to have deopt data available. This matches Node.js's
approach of never capturing JS stacks inside the heap limit callback.

The callback is registered once per isolate via an atomic guard in
RendererClientBase::DidCreateScriptContext, preventing the CHECK
failure V8 raises on duplicate AddNearHeapLimitCallback registrations
(which would otherwise occur on page navigations or multiple contexts).

Refs: electron#46078
Made-with: Cursor

* Update shell/renderer/oom_stack_trace.cc

Co-authored-by: Niklas Wenzel <[email protected]>

* Update shell/renderer/oom_stack_trace.cc

Co-authored-by: Niklas Wenzel <[email protected]>

* test: add crash reporter test for OOM JS stack trace

Add a test that verifies the `electron.v8-oom.stack` crash key contains
the JS stack trace (including function names) when a renderer process
runs out of memory. Also deduplicate the heap info formatting in
oom_stack_trace.cc.

Refs: electron#46078
Made-with: Cursor

* fix: lint formatting in oom_stack_trace.cc

Made-with: Cursor

* fix: use proper logger API instead of cstdio

* fix: check heap headroom before capturing OOM stack trace

deepak1556: "Should there be check for available heap size [for]
CurrentStackTrace and formatting"

CurrentStackTrace allocates StackTraceInfo + StackFrameInfo on the V8
heap. If the 20 MB bump is partially consumed by the time the interrupt
fires, these allocations trigger a secondary OOM. Guard with a 2 MB
headroom check.

Made-with: Cursor

* fix: handle V8 cage limit when bumping heap for OOM stack capture

deepak1556: "Does this bumping work when we are at the cage limit of
4GB"

V8's pointer compression cage caps the heap at ~4 GB. When
current_heap_limit is already near the ceiling, our 20 MB bump gets
clamped to zero and the interrupt never fires. Detect this and record
heap info as the final crash key instead of waiting for a stack trace
that won't arrive.

Made-with: Cursor

* feat: add V8 heap statistics as OOM crash keys

deepak1556: "V8 seems to capture heap stats as crash keys but it gets
missed today due to the OOM callback override... wonder if we can
include that to get some more heuristics in the dump."

Record heap used/total/limit/available, per-space stats for old_space
and large_object_space, native/detached context counts, and utilization
percentage as crash keys. Also add heap stats in the V8OOMErrorCallback
in node_bindings.cc for the final OOM crash report.

Made-with: Cursor

* feat: support worker thread isolates for OOM stack trace

deepak1556: "You need a separate registration for worker threads via
WorkerScriptReadyForEvaluationOnWorkerThread but that also means the
process global g_registered_isolate would break."

Chromium has one V8 isolate per thread (main + one per web worker), so
thread_local is equivalent to per-isolate storage. Replace the global
atomic + mutex/set with a constinit thread_local OomState* that holds
the isolate pointer and per-isolate is_in_oom flag. The void* data
parameter on AddNearHeapLimitCallback delivers OomState* directly into
callbacks, so the hot path needs no TLS lookup.

Add WorkerScriptReadyForEvaluationOnWorkerThread and
WillDestroyWorkerContextOnWorkerThread overrides to RendererClientBase
so both ElectronRendererClient and ElectronSandboxedRendererClient get
worker OOM registration. Update ElectronRendererClient to call the base
class in both worker lifecycle methods.

Add a web worker OOM test that spawns a dedicated Worker with a memory
leak and verifies the stack trace captures the worker function name.

Made-with: Cursor

* fix: register OOM callback for all script contexts

When context isolation is enabled, ShouldNotifyClient skips
DidCreateScriptContext for the main world, but user JS still runs there
and can OOM. Register in DidInstallConditionalFeatures which fires for
every script context. The TLS dedup guard prevents double-registration
on the same isolate.

Made-with: Cursor

* fix: guard against division by zero and cage size changes in OOM handler

Add a zero-guard on heap_size_limit before computing utilization
percentage — maximizes robustness in an OOM code path.

Add static_assert on kPtrComprCageReservationSize to catch any
upstream V8 change to the cage size at compile time.

Made-with: Cursor

* fix: address review feedback on OOM stack trace PR

- Remove redundant RegisterOomStackTraceCallback from
  electron_render_frame_observer.cc; DidCreateScriptContext is sufficient
  since main world and isolated world share the same isolate
- Replace thread_local OomState* with base::ThreadLocalOwnedPointer
  wrapped in base::NoDestructor per Chromium style for non-trivially
  destructible types
- Change heap-headroom and cage-limit logs from ERROR to INFO since
  users cannot act on these diagnostics
- Add comment explaining why base class is called last in
  WillDestroyWorkerContextOnWorkerThread (OOM deregistration ordering)

Made-with: Cursor

* fix: skip OOM stack trace registration for worklet contexts

Worklets can share a thread and isolate via WorkletThreadHolder's
per-process singleton pattern. With per-thread OOM state, the first
worklet to be destroyed would prematurely remove the callback for
any remaining worklets on the same thread. Skip worklets entirely
to avoid this; can be revisited with ref-counting if needed.

Made-with: Cursor

* fix: prevent dangling raw_ptr<v8::Isolate> in OOM state

The OomState held a raw_ptr<v8::Isolate> that outlived the isolate on
the main thread: gin::IsolateHolder destroyed the isolate during
shutdown, but the OomState (stored in thread-local storage) was only
released later in JavascriptEnvironment::~JavascriptEnvironment. This
triggers a dangling pointer check when building with
enable_dangling_raw_ptr_checks.

Register OomState as a gin::PerIsolateData::DisposeObserver so it
clears the raw_ptr and removes the NearHeapLimitCallback before the
isolate is destroyed, regardless of destructor ordering.

Suggested-by: Deepak Mohan
Made-with: Cursor

* test: verify OOM crash keys end-to-end via crash reporter

Replace stderr-based OOM tests with end-to-end crash dump validation.
Instead of parsing log output, start a crash reporter server, trigger
renderer OOM, and verify the uploaded crash dump contains the expected
`electron.v8-oom.*` annotations — the same code path production crash
reports take.

Consolidate all OOM test scenarios (basic heap leak, JSON.stringify,
web worker) into a single `describe('OOM crash keys')` block inside
api-crash-reporter-spec using the existing crash fixture app with new
renderer-oom-json and renderer-oom-worker crash types.

The web worker test verifies that OOM crash keys are present but does
not assert on the JS function name: the 20 MB heap bump may be
exhausted before V8 reaches a safe point to fire the stack-capture
interrupt, leaving the crash key at "(stack pending)". Increasing the
bump or switching to a synchronous capture strategy would fix this but
is left for a follow-up.

Remove the standalone oom-stack-trace-spec.ts and its fixture app.

Made-with: Cursor

---------

Co-authored-by: Niklas Wenzel <[email protected]>
@alexkozy

Copy link
Copy Markdown
Contributor Author

sorry for noise, will backport properly soon

alexkozy added a commit to alexkozy/electron that referenced this pull request Apr 10, 2026
* feat: capture JS stack trace on renderer OOM

When a renderer process approaches its V8 heap limit, capture the
JavaScript stack trace and write it to both a Crashpad crash key
("js-oom-stack") and stderr.

The stack trace is captured via RequestInterrupt rather than directly
inside the NearHeapLimitCallback because CurrentStackTrace is unsafe
to call during OOM — V8 FATALs on optimized (TurboFan) frames that
have had their deoptimization data garbage-collected. RequestInterrupt
defers the capture to the next V8 safe point, where all frames are
guaranteed to have deopt data available. This matches Node.js's
approach of never capturing JS stacks inside the heap limit callback.

The callback is registered once per isolate via an atomic guard in
RendererClientBase::DidCreateScriptContext, preventing the CHECK
failure V8 raises on duplicate AddNearHeapLimitCallback registrations
(which would otherwise occur on page navigations or multiple contexts).

Refs: electron#46078
Made-with: Cursor

* Update shell/renderer/oom_stack_trace.cc

Co-authored-by: Niklas Wenzel <[email protected]>

* Update shell/renderer/oom_stack_trace.cc

Co-authored-by: Niklas Wenzel <[email protected]>

* test: add crash reporter test for OOM JS stack trace

Add a test that verifies the `electron.v8-oom.stack` crash key contains
the JS stack trace (including function names) when a renderer process
runs out of memory. Also deduplicate the heap info formatting in
oom_stack_trace.cc.

Refs: electron#46078
Made-with: Cursor

* fix: lint formatting in oom_stack_trace.cc

Made-with: Cursor

* fix: use proper logger API instead of cstdio

* fix: check heap headroom before capturing OOM stack trace

deepak1556: "Should there be check for available heap size [for]
CurrentStackTrace and formatting"

CurrentStackTrace allocates StackTraceInfo + StackFrameInfo on the V8
heap. If the 20 MB bump is partially consumed by the time the interrupt
fires, these allocations trigger a secondary OOM. Guard with a 2 MB
headroom check.

Made-with: Cursor

* fix: handle V8 cage limit when bumping heap for OOM stack capture

deepak1556: "Does this bumping work when we are at the cage limit of
4GB"

V8's pointer compression cage caps the heap at ~4 GB. When
current_heap_limit is already near the ceiling, our 20 MB bump gets
clamped to zero and the interrupt never fires. Detect this and record
heap info as the final crash key instead of waiting for a stack trace
that won't arrive.

Made-with: Cursor

* feat: add V8 heap statistics as OOM crash keys

deepak1556: "V8 seems to capture heap stats as crash keys but it gets
missed today due to the OOM callback override... wonder if we can
include that to get some more heuristics in the dump."

Record heap used/total/limit/available, per-space stats for old_space
and large_object_space, native/detached context counts, and utilization
percentage as crash keys. Also add heap stats in the V8OOMErrorCallback
in node_bindings.cc for the final OOM crash report.

Made-with: Cursor

* feat: support worker thread isolates for OOM stack trace

deepak1556: "You need a separate registration for worker threads via
WorkerScriptReadyForEvaluationOnWorkerThread but that also means the
process global g_registered_isolate would break."

Chromium has one V8 isolate per thread (main + one per web worker), so
thread_local is equivalent to per-isolate storage. Replace the global
atomic + mutex/set with a constinit thread_local OomState* that holds
the isolate pointer and per-isolate is_in_oom flag. The void* data
parameter on AddNearHeapLimitCallback delivers OomState* directly into
callbacks, so the hot path needs no TLS lookup.

Add WorkerScriptReadyForEvaluationOnWorkerThread and
WillDestroyWorkerContextOnWorkerThread overrides to RendererClientBase
so both ElectronRendererClient and ElectronSandboxedRendererClient get
worker OOM registration. Update ElectronRendererClient to call the base
class in both worker lifecycle methods.

Add a web worker OOM test that spawns a dedicated Worker with a memory
leak and verifies the stack trace captures the worker function name.

Made-with: Cursor

* fix: register OOM callback for all script contexts

When context isolation is enabled, ShouldNotifyClient skips
DidCreateScriptContext for the main world, but user JS still runs there
and can OOM. Register in DidInstallConditionalFeatures which fires for
every script context. The TLS dedup guard prevents double-registration
on the same isolate.

Made-with: Cursor

* fix: guard against division by zero and cage size changes in OOM handler

Add a zero-guard on heap_size_limit before computing utilization
percentage — maximizes robustness in an OOM code path.

Add static_assert on kPtrComprCageReservationSize to catch any
upstream V8 change to the cage size at compile time.

Made-with: Cursor

* fix: address review feedback on OOM stack trace PR

- Remove redundant RegisterOomStackTraceCallback from
  electron_render_frame_observer.cc; DidCreateScriptContext is sufficient
  since main world and isolated world share the same isolate
- Replace thread_local OomState* with base::ThreadLocalOwnedPointer
  wrapped in base::NoDestructor per Chromium style for non-trivially
  destructible types
- Change heap-headroom and cage-limit logs from ERROR to INFO since
  users cannot act on these diagnostics
- Add comment explaining why base class is called last in
  WillDestroyWorkerContextOnWorkerThread (OOM deregistration ordering)

Made-with: Cursor

* fix: skip OOM stack trace registration for worklet contexts

Worklets can share a thread and isolate via WorkletThreadHolder's
per-process singleton pattern. With per-thread OOM state, the first
worklet to be destroyed would prematurely remove the callback for
any remaining worklets on the same thread. Skip worklets entirely
to avoid this; can be revisited with ref-counting if needed.

Made-with: Cursor

* fix: prevent dangling raw_ptr<v8::Isolate> in OOM state

The OomState held a raw_ptr<v8::Isolate> that outlived the isolate on
the main thread: gin::IsolateHolder destroyed the isolate during
shutdown, but the OomState (stored in thread-local storage) was only
released later in JavascriptEnvironment::~JavascriptEnvironment. This
triggers a dangling pointer check when building with
enable_dangling_raw_ptr_checks.

Register OomState as a gin::PerIsolateData::DisposeObserver so it
clears the raw_ptr and removes the NearHeapLimitCallback before the
isolate is destroyed, regardless of destructor ordering.

Suggested-by: Deepak Mohan
Made-with: Cursor

* test: verify OOM crash keys end-to-end via crash reporter

Replace stderr-based OOM tests with end-to-end crash dump validation.
Instead of parsing log output, start a crash reporter server, trigger
renderer OOM, and verify the uploaded crash dump contains the expected
`electron.v8-oom.*` annotations — the same code path production crash
reports take.

Consolidate all OOM test scenarios (basic heap leak, JSON.stringify,
web worker) into a single `describe('OOM crash keys')` block inside
api-crash-reporter-spec using the existing crash fixture app with new
renderer-oom-json and renderer-oom-worker crash types.

The web worker test verifies that OOM crash keys are present but does
not assert on the JS function name: the 20 MB heap bump may be
exhausted before V8 reaches a safe point to fire the stack-capture
interrupt, leaving the crash key at "(stack pending)". Increasing the
bump or switching to a synchronous capture strategy would fix this but
is left for a follow-up.

Remove the standalone oom-stack-trace-spec.ts and its fixture app.

Made-with: Cursor

---------

Co-authored-by: Niklas Wenzel <[email protected]>
Made-with: Cursor
@trop

trop Bot commented Apr 10, 2026

Copy link
Copy Markdown
Contributor

@alexkozy has manually backported this PR to "41-x-y", please check out #50913

@trop trop Bot added merged/42-x-y PR was merged to the "42-x-y" branch. and removed in-flight/42-x-y labels Apr 27, 2026
alexkozy added a commit to alexkozy/electron that referenced this pull request Jun 5, 2026
* feat: capture JS stack trace on renderer OOM

When a renderer process approaches its V8 heap limit, capture the
JavaScript stack trace and write it to both a Crashpad crash key
("js-oom-stack") and stderr.

The stack trace is captured via RequestInterrupt rather than directly
inside the NearHeapLimitCallback because CurrentStackTrace is unsafe
to call during OOM — V8 FATALs on optimized (TurboFan) frames that
have had their deoptimization data garbage-collected. RequestInterrupt
defers the capture to the next V8 safe point, where all frames are
guaranteed to have deopt data available. This matches Node.js's
approach of never capturing JS stacks inside the heap limit callback.

The callback is registered once per isolate via an atomic guard in
RendererClientBase::DidCreateScriptContext, preventing the CHECK
failure V8 raises on duplicate AddNearHeapLimitCallback registrations
(which would otherwise occur on page navigations or multiple contexts).

Refs: electron#46078
Made-with: Cursor

* Update shell/renderer/oom_stack_trace.cc

Co-authored-by: Niklas Wenzel <[email protected]>

* Update shell/renderer/oom_stack_trace.cc

Co-authored-by: Niklas Wenzel <[email protected]>

* test: add crash reporter test for OOM JS stack trace

Add a test that verifies the `electron.v8-oom.stack` crash key contains
the JS stack trace (including function names) when a renderer process
runs out of memory. Also deduplicate the heap info formatting in
oom_stack_trace.cc.

Refs: electron#46078
Made-with: Cursor

* fix: lint formatting in oom_stack_trace.cc

Made-with: Cursor

* fix: use proper logger API instead of cstdio

* fix: check heap headroom before capturing OOM stack trace

deepak1556: "Should there be check for available heap size [for]
CurrentStackTrace and formatting"

CurrentStackTrace allocates StackTraceInfo + StackFrameInfo on the V8
heap. If the 20 MB bump is partially consumed by the time the interrupt
fires, these allocations trigger a secondary OOM. Guard with a 2 MB
headroom check.

Made-with: Cursor

* fix: handle V8 cage limit when bumping heap for OOM stack capture

deepak1556: "Does this bumping work when we are at the cage limit of
4GB"

V8's pointer compression cage caps the heap at ~4 GB. When
current_heap_limit is already near the ceiling, our 20 MB bump gets
clamped to zero and the interrupt never fires. Detect this and record
heap info as the final crash key instead of waiting for a stack trace
that won't arrive.

Made-with: Cursor

* feat: add V8 heap statistics as OOM crash keys

deepak1556: "V8 seems to capture heap stats as crash keys but it gets
missed today due to the OOM callback override... wonder if we can
include that to get some more heuristics in the dump."

Record heap used/total/limit/available, per-space stats for old_space
and large_object_space, native/detached context counts, and utilization
percentage as crash keys. Also add heap stats in the V8OOMErrorCallback
in node_bindings.cc for the final OOM crash report.

Made-with: Cursor

* feat: support worker thread isolates for OOM stack trace

deepak1556: "You need a separate registration for worker threads via
WorkerScriptReadyForEvaluationOnWorkerThread but that also means the
process global g_registered_isolate would break."

Chromium has one V8 isolate per thread (main + one per web worker), so
thread_local is equivalent to per-isolate storage. Replace the global
atomic + mutex/set with a constinit thread_local OomState* that holds
the isolate pointer and per-isolate is_in_oom flag. The void* data
parameter on AddNearHeapLimitCallback delivers OomState* directly into
callbacks, so the hot path needs no TLS lookup.

Add WorkerScriptReadyForEvaluationOnWorkerThread and
WillDestroyWorkerContextOnWorkerThread overrides to RendererClientBase
so both ElectronRendererClient and ElectronSandboxedRendererClient get
worker OOM registration. Update ElectronRendererClient to call the base
class in both worker lifecycle methods.

Add a web worker OOM test that spawns a dedicated Worker with a memory
leak and verifies the stack trace captures the worker function name.

Made-with: Cursor

* fix: register OOM callback for all script contexts

When context isolation is enabled, ShouldNotifyClient skips
DidCreateScriptContext for the main world, but user JS still runs there
and can OOM. Register in DidInstallConditionalFeatures which fires for
every script context. The TLS dedup guard prevents double-registration
on the same isolate.

Made-with: Cursor

* fix: guard against division by zero and cage size changes in OOM handler

Add a zero-guard on heap_size_limit before computing utilization
percentage — maximizes robustness in an OOM code path.

Add static_assert on kPtrComprCageReservationSize to catch any
upstream V8 change to the cage size at compile time.

Made-with: Cursor

* fix: address review feedback on OOM stack trace PR

- Remove redundant RegisterOomStackTraceCallback from
  electron_render_frame_observer.cc; DidCreateScriptContext is sufficient
  since main world and isolated world share the same isolate
- Replace thread_local OomState* with base::ThreadLocalOwnedPointer
  wrapped in base::NoDestructor per Chromium style for non-trivially
  destructible types
- Change heap-headroom and cage-limit logs from ERROR to INFO since
  users cannot act on these diagnostics
- Add comment explaining why base class is called last in
  WillDestroyWorkerContextOnWorkerThread (OOM deregistration ordering)

Made-with: Cursor

* fix: skip OOM stack trace registration for worklet contexts

Worklets can share a thread and isolate via WorkletThreadHolder's
per-process singleton pattern. With per-thread OOM state, the first
worklet to be destroyed would prematurely remove the callback for
any remaining worklets on the same thread. Skip worklets entirely
to avoid this; can be revisited with ref-counting if needed.

Made-with: Cursor

* fix: prevent dangling raw_ptr<v8::Isolate> in OOM state

The OomState held a raw_ptr<v8::Isolate> that outlived the isolate on
the main thread: gin::IsolateHolder destroyed the isolate during
shutdown, but the OomState (stored in thread-local storage) was only
released later in JavascriptEnvironment::~JavascriptEnvironment. This
triggers a dangling pointer check when building with
enable_dangling_raw_ptr_checks.

Register OomState as a gin::PerIsolateData::DisposeObserver so it
clears the raw_ptr and removes the NearHeapLimitCallback before the
isolate is destroyed, regardless of destructor ordering.

Suggested-by: Deepak Mohan
Made-with: Cursor

* test: verify OOM crash keys end-to-end via crash reporter

Replace stderr-based OOM tests with end-to-end crash dump validation.
Instead of parsing log output, start a crash reporter server, trigger
renderer OOM, and verify the uploaded crash dump contains the expected
`electron.v8-oom.*` annotations — the same code path production crash
reports take.

Consolidate all OOM test scenarios (basic heap leak, JSON.stringify,
web worker) into a single `describe('OOM crash keys')` block inside
api-crash-reporter-spec using the existing crash fixture app with new
renderer-oom-json and renderer-oom-worker crash types.

The web worker test verifies that OOM crash keys are present but does
not assert on the JS function name: the 20 MB heap bump may be
exhausted before V8 reaches a safe point to fire the stack-capture
interrupt, leaving the crash key at "(stack pending)". Increasing the
bump or switching to a synchronous capture strategy would fix this but
is left for a follow-up.

Remove the standalone oom-stack-trace-spec.ts and its fixture app.

Made-with: Cursor

---------

Co-authored-by: Niklas Wenzel <[email protected]>
Made-with: Cursor
@trop trop Bot removed the in-flight/41-x-y label Jul 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-review/approved ✅ merged/42-x-y PR was merged to the "42-x-y" branch. semver/minor backwards-compatible functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

minidump OOM crash reports should include javascript stacktrace

8 participants