From e7796a0d6a9c7f0685c96917ebfec14d9a36ed05 Mon Sep 17 00:00:00 2001 From: Karl Seguin Date: Thu, 9 Jul 2026 16:51:32 +0800 Subject: [PATCH] mem, v8: Increase the extra room we give v8 @ nearHeapLimit Currently, we give v8 8MB more memory. This new commit increases that to 64MB up to a total of 256MB (at which point, no extra space is given). The commit also instructs v8 to eventually go back to its original heap limit (and not continuing using the higher limit it was given by nearHeapLimit). This is important since the isolate can be relatively long lived compared to a script that caused memory pressure. This feature is currently commented and depends on: https://github.com/lightpanda-io/zig-v8-fork/pull/187 --- src/browser/js/Env.zig | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/browser/js/Env.zig b/src/browser/js/Env.zig index 6edda76bd..ffab70284 100644 --- a/src/browser/js/Env.zig +++ b/src/browser/js/Env.zig @@ -553,13 +553,18 @@ pub fn terminate(self: *Env) void { // We need a stable pointer for *Env, so can't be setup in init. pub fn protectHeapLimit(self: *Env) void { v8.v8__Isolate__AddNearHeapLimitCallback(self.isolate.handle, nearHeapLimit, self); + // TODO: uncomment this when https://github.com/lightpanda-io/zig-v8-fork/pull/187 lands + // if our nearHeapLimit extends the memory, we want to restore the original + // value, since the isolate can be long lived (relative to the page/script + // that caused the memory spike). + // v8.v8__Isolate__AutomaticallyRestoreInitialHeapLimit(self.isolate.handle, 0.5); } // v8 is telling us it's about to run out of memory for this isolate. We'll // do two things: // 1 - Terminate the execution (attempting to prevent v8 from OOM'ing the process) -// 2 - Tell v8 that it can use 8MB more memory, hopefully giving it enough memory -// to properly shutdown +// 2 - Grant more headroom so execution can reach a stack-guard check, where +// the terminate lands // // The terminate must go through requestTerminate (RequestInterrupt), NOT a // direct TerminateExecution: we're mid-GC, which is an arbitrary point — @@ -575,7 +580,12 @@ fn nearHeapLimit(data: ?*anyopaque, current_limit: usize, initial_limit: usize) .current_limit = current_limit, }); self.requestTerminate(); - return current_limit + 8 * 1024 * 1024; + + const cap = initial_limit + 256 * 1024 * 1024; + if (current_limit >= cap) { + return current_limit; + } + return @min(cap, current_limit + 64 * 1024 * 1024); } // Called from the network thread, caused v8 to eventually call terminateInterrupt