Repository navigation
fix(ext/node): don't leave 0-byte .heapsnapshot files near the heap limit - #36113
Conversation
…imit `v8.setHeapSnapshotNearHeapLimit()` could leave behind empty `.heapsnapshot` files while the process never actually OOM-aborted (denoland#36034). Two bugs, one visible symptom each: 1. The destination file was created with `File::create` *before* the snapshot was generated, so any failure to complete generation left the file behind at 0 bytes. Nothing treated "V8 emitted no chunks" as a failure either, so it was reported as success. The snapshot is now streamed into a `.heapsnapshot.tmp` sibling, and is only renamed into place once V8 has actually produced bytes (flushed + `sync_all`'d + closed first, which Windows needs before a rename). Zero chunks or a write error removes the temp file and reports the failure, so the destination path never exists at 0 bytes. 2. The reentrancy guard returned `current_heap_limit + headroom` on every nested invocation. Generating a snapshot itself runs a full GC (`HeapSnapshotGenerator::GenerateSnapshot` calls `CollectAllAvailableGarbage`), which re-enters the callback, and V8 passes the *already raised* limit back in as `current_heap_limit` (`Heap::InvokeNearHeapLimitCallback`). The limit therefore ratcheted up without bound and the process grew until it ate the machine instead of OOMing. The headroom is now computed once per snapshot and stashed in `granted_limit`; reentrant invocations return that same fixed ceiling. V8 only raises the limit when the returned value exceeds the current one, so the limit is raised exactly once and the process still OOMs once that budget is spent. Node avoids the same ratchet by computing `new_limit` once (src/env.cc `Environment::NearHeapLimitCallback`) and undoing the raise via `AutomaticallyRestoreInitialHeapLimit`, which rusty_v8 does not bind. Also print the diagnostic with `eprintln!` instead of `log::info!` so it matches Node and survives `--quiet`, and correct the comment on `remove_near_heap_limit_callback(cb, 0)`: a 0 limit means "leave the heap limit alone", it does not restore a minimal one (`Heap::RemoveNearHeapLimitCallback` only calls `RestoreHeapLimit` for a non-zero value). The spec test now asserts the snapshot is non-empty, that no `.tmp` file is left behind, and adds a `write_fail.ts` step covering the write-failure path (read-only cwd): the error is reported and no file is left behind.
bartlomieju
left a comment
There was a problem hiding this comment.
LGTM. The bounded ratchet is correct — granted_limit is set exactly once per snapshot with no intervening V8 call, so every reentry returns the same fixed ceiling (>= current, but bounded so OOM eventually happens), and byte-counting gates Ok on a successful flush+sync so a partial/corrupt snapshot can't be renamed into place. tmp cleanup and close-before-rename ordering are right. Nice fix.
A couple of non-blocking notes:
- On a mid-generation OOM (if the once-computed headroom is ever insufficient for V8 to finish serializing), the process dies before the cleanup/rename runs, leaving a
.heapsnapshot.tmpbehind.check.tscurrently hard-fails on any leftover.tmp, which couples green CI to "4MB headroom is always enough for this heap." Consider tolerating a stray.tmpwhile still failing on the actual regression (a.heapsnapshotexisting at 0 bytes), or documenting the mid-abort leftover as expected. - Minor: the extra
Wrote heap snapshot to ...success line isn't something Node emits (Node only prints "Writing heap snapshot to ..." up front). The PR says it mirrors Node, so strictly it over-mirrors. Harmless, optional to drop. - Pre-existing, not introduced here: the
&mut *(data)state borrow is aliased across the synchronous reentrant callback, which is UB under Rust's aliasing model. Not worsened by this PR (reentry only reads and returns before touching outer locals), but worth a follow-up.
… test Addresses review feedback: - Node only prints "Writing heap snapshot to ..." up front and nothing on success, so the extra "Wrote heap snapshot to ..." line over-mirrored it. - check.ts hard-failed on a leftover .heapsnapshot.tmp, which couples green CI to "the once-granted headroom is always enough for this heap": a mid-generation OOM kills the process before cleanup runs and leaves the temp file behind. The actual regression under test is a 0-byte .heapsnapshot at the destination path, which is still asserted.
|
Thanks — took both non-blocking notes in 4857c4a.
Left the aliased |
bartlomieju
left a comment
There was a problem hiding this comment.
LGTM. Both bugs correctly diagnosed and fixed:
- Unbounded ratchet: stashing a single
granted_limiton entry and returning it on reentry is the right fix. Verified theprocessingguard sits before thetaken >= limitcheck, so every in-generation reentry returns the fixed ceiling and the limit is raised exactly once. - 0-byte file: streaming into
.heapsnapshot.tmpand renaming only after a non-empty, flushed +sync_all'd write means the destination path never exists at 0 bytes. flush + sync_all + close before rename for Windows is correct.
check.ts correctly tolerates a leftover .tmp (excluded by the .endsWith(".heapsnapshot") filter) while forbidding a 0-byte destination, and write_fail.ts stays deterministic by self-reporting on Windows/root where chmod doesn't bite. Thorough verification notes too.
…36114) Two independent findings, split out of the investigation into #36034 (fixed separately in #36113) to keep that PR focused. Neither is needed for that issue. ### fix(runtime): give worker isolate threads the stack size we report `resourceLimits.stackSizeMb` reports `DEFAULT_STACK_SIZE_MB` (4, matching Node) for a `node:worker_threads` worker created without explicit limits — but `op_create_worker` only called `Builder::stack_size()` when `stackSizeMb` was explicitly passed. So the thread the worker's isolate actually ran on got Rust's 2MB default while we told the user it was 4MB. Beyond the reported value being wrong, 2MB leaves almost no native headroom above V8's own JS stack limit (`--stack-size`, ~1MB by default): with `--stack-size` raised above 2MB, recursing JS in a default worker overflows the OS stack and **aborts the process** instead of raising `RangeError`. `DEFAULT_WORKER_STACK_SIZE_MB = 4` now applies to every worker isolate thread; an explicit `stackSizeMb` still overrides. New spec test `node::worker_threads_resource_limits::resource_limits_default_stack_size`. It was validated with a negative control — forcing the default back to 2MB makes it fail exactly as designed: ``` <thread 'worker-1' has overflowed its stack <fatal runtime error: stack overflow, aborting >caught RangeError: true ``` With the fix, all 4 tests in that spec pass. ### chore: drop dead Windows cargo config and fix a stack-size comment Cargo evaluates `target.'cfg(...)'` specs against `rustc --print cfg --target <triple>`, whose output **always contains `debug_assertions`** regardless of the profile being built. Two consequences in `.cargo/config.toml`, neither of which produced a warning: - `cfg(all(windows, debug_assertions))` has always matched **every** Windows build, so `/STACK:4194304` has been applied to release all along — despite its comment saying "in debug". Respelled `cfg(windows)`, which states the existing effective behavior honestly. - `cfg(all(windows, not(debug_assertions)))` matched **nothing**, so its `link-arg=/OPT:ICF` was dead config that never applied to any build. Removed; it was redundant anyway, since rustc already passes `/OPT:REF,ICF` when optimizing. **This is a no-op**, verified by diffing the flags Cargo actually emits for `x86_64-pc-windows-msvc` in both profiles, using the exact config text from before and after. Identical in both. The check also directly confirms both claims above: `/STACK:4194304` *is* emitted in release before the change, and `/OPT:ICF` is emitted in neither profile before the change. A method caveat worth stating: `cargo build -v --target x86_64-pc-windows-msvc` against the full repo timed out resolving the dep graph before it printed any link args, so the comparison was run on a throwaway crate using byte-identical config text — that's what determines the flags. (Gotcha for anyone reproducing: Cargo quotes it as `-C 'link-arg=/STACK:4194304'`, so a `-C link-arg=[^ ]*` grep matches nothing.) Comments in `.cargo/config.toml` now document the Cargo `cfg` behavior so the profile-gating intent isn't re-attempted — there is no stable way to gate rustflags on the profile. `runtime/tokio_util.rs` gets a comment-only correction: `thread_stack_size` sizes the blocking pool only. This is a `current_thread` runtime, so V8 runs on the thread that calls `block_on`, not a pool thread — the old comment's claim that 2MB "matches the main thread size" was wrong (Unix main is ~8MB; Windows main is the PE reserve). --------- Co-authored-by: Nathan Whitaker <nathan@deno.com>
…36114) Two independent findings, split out of the investigation into #36034 (fixed separately in #36113) to keep that PR focused. Neither is needed for that issue. ### fix(runtime): give worker isolate threads the stack size we report `resourceLimits.stackSizeMb` reports `DEFAULT_STACK_SIZE_MB` (4, matching Node) for a `node:worker_threads` worker created without explicit limits — but `op_create_worker` only called `Builder::stack_size()` when `stackSizeMb` was explicitly passed. So the thread the worker's isolate actually ran on got Rust's 2MB default while we told the user it was 4MB. Beyond the reported value being wrong, 2MB leaves almost no native headroom above V8's own JS stack limit (`--stack-size`, ~1MB by default): with `--stack-size` raised above 2MB, recursing JS in a default worker overflows the OS stack and **aborts the process** instead of raising `RangeError`. `DEFAULT_WORKER_STACK_SIZE_MB = 4` now applies to every worker isolate thread; an explicit `stackSizeMb` still overrides. New spec test `node::worker_threads_resource_limits::resource_limits_default_stack_size`. It was validated with a negative control — forcing the default back to 2MB makes it fail exactly as designed: ``` <thread 'worker-1' has overflowed its stack <fatal runtime error: stack overflow, aborting >caught RangeError: true ``` With the fix, all 4 tests in that spec pass. ### chore: drop dead Windows cargo config and fix a stack-size comment Cargo evaluates `target.'cfg(...)'` specs against `rustc --print cfg --target <triple>`, whose output **always contains `debug_assertions`** regardless of the profile being built. Two consequences in `.cargo/config.toml`, neither of which produced a warning: - `cfg(all(windows, debug_assertions))` has always matched **every** Windows build, so `/STACK:4194304` has been applied to release all along — despite its comment saying "in debug". Respelled `cfg(windows)`, which states the existing effective behavior honestly. - `cfg(all(windows, not(debug_assertions)))` matched **nothing**, so its `link-arg=/OPT:ICF` was dead config that never applied to any build. Removed; it was redundant anyway, since rustc already passes `/OPT:REF,ICF` when optimizing. **This is a no-op**, verified by diffing the flags Cargo actually emits for `x86_64-pc-windows-msvc` in both profiles, using the exact config text from before and after. Identical in both. The check also directly confirms both claims above: `/STACK:4194304` *is* emitted in release before the change, and `/OPT:ICF` is emitted in neither profile before the change. A method caveat worth stating: `cargo build -v --target x86_64-pc-windows-msvc` against the full repo timed out resolving the dep graph before it printed any link args, so the comparison was run on a throwaway crate using byte-identical config text — that's what determines the flags. (Gotcha for anyone reproducing: Cargo quotes it as `-C 'link-arg=/STACK:4194304'`, so a `-C link-arg=[^ ]*` grep matches nothing.) Comments in `.cargo/config.toml` now document the Cargo `cfg` behavior so the profile-gating intent isn't re-attempted — there is no stable way to gate rustflags on the profile. `runtime/tokio_util.rs` gets a comment-only correction: `thread_stack_size` sizes the blocking pool only. This is a `current_thread` runtime, so V8 runs on the thread that calls `block_on`, not a pool thread — the old comment's claim that 2MB "matches the main thread size" was wrong (Unix main is ~8MB; Windows main is the PE reserve). --------- Co-authored-by: Nathan Whitaker <nathan@deno.com>
…imit (#36113) Fixes #36034. `v8.setHeapSnapshotNearHeapLimit()` could leave 0-byte `.heapsnapshot` files behind, and the process would keep growing instead of OOMing — in the reporter's case until the machine itself ran out of memory and rebooted. Both symptoms come from `near_heap_limit_snapshot_callback` in `ext/node/ops/v8.rs`. ### Root cause **The heap limit ratcheted up without bound.** Generating a snapshot itself runs a full GC (`HeapSnapshotGenerator::GenerateSnapshot` → `CollectAllAvailableGarbage`), which re-enters the near-heap-limit callback while we're still writing. The old `processing` guard returned a freshly computed `current_heap_limit + headroom` on *every* reentry — and `Heap::InvokeNearHeapLimitCallback` passes the **already-raised** limit as `current_heap_limit`, then raises again whenever the returned value exceeds it. So each reentry lifted the ceiling another notch, forever. The process never OOMed; it just consumed memory until something else gave out. For comparison, Node computes `new_limit = current_heap_limit + max_young_gen_size` **once** and its nested branch returns *that* fixed value, then undoes the raise via `AutomaticallyRestoreInitialHeapLimit(0.95)`. That API isn't bound in rusty_v8, so this PR bounds the raise by construction instead. **The destination file was created up front.** `File::create` ran before generation, so the `.heapsnapshot` existed at 0 bytes from the outset. Any failure to complete generation — including being stuck in the ratchet above, or the process finally dying — left that empty file behind, and nothing treated "V8 emitted zero chunks" as a failure. (Node's `heap::WriteSnapshot` opens its destination `O_CREAT|O_TRUNC` up front too and has the same exposure; its guards are what keep it from getting there.) ### Changes - **Bounded ratchet**: headroom is computed once per snapshot and stored in `granted_limit`; reentrant invocations return that same fixed ceiling. The limit rises exactly once, and once the snapshot spends that budget V8 OOMs normally. - **Never a 0-byte file**: the snapshot streams into a `.heapsnapshot.tmp`, counting bytes, and is `rename`d into place only after a successful non-empty write (with `flush` + `sync_all` + close first, which Windows needs before the rename). An empty result or a write error removes the temp file and reports the failure, so the destination path never exists at 0 bytes. - **Diagnostic**: "Writing heap snapshot to …" moves from `log::info!` to `eprintln!` so it survives `--quiet`, matching Node. Adds `Wrote heap snapshot to …` / `Failed to write heap snapshot to …: <reason>`. - Corrects a comment: `remove_near_heap_limit_callback(cb, 0)` doesn't restore a minimal limit — `Heap::RemoveNearHeapLimitCallback` only calls `RestoreHeapLimit` for a non-zero value. Passing 0 leaves the limit alone, which is what we want so the pending OOM actually happens. ### Tests `tests/specs/node/v8_set_heap_snapshot_near_heap_limit/` now asserts the snapshot is non-empty and structurally valid (`nodes`/`edges`/`strings` populated) and that no `.tmp` file is left behind. A new `write_fail.ts` step makes the child's cwd read-only at the OS level so the write fails *inside* the callback, and asserts the failure is reported and **no** file is left behind (skipped on Windows and as root, where `chmod` doesn't bite). Verified against an OOM repro: a ~5.8 MB valid snapshot is written and renamed into place with no leftovers, and the process still OOM-aborts (exit 133, "Fatal JavaScript out of memory: Reached heap limit"). The read-only repro reports the failure and leaves nothing behind. ### A note on the Windows angle The report is from Windows, and a plausible theory was that V8's snapshot generator blew Windows' smaller native stack. That was investigated and **disproved**, so no stack change is included here: - Release Windows builds already link with `/STACK:4194304`. Cargo evaluates `target.'cfg(...)'` specs against `rustc --print cfg`, whose output always contains `debug_assertions` regardless of profile — so the existing `cfg(all(windows, debug_assertions))` block has always applied to release too. - An apparent "stack cliff" at 1MB turned out to be a debug-build artifact with no control: the same allocate-until-OOM script with `setHeapSnapshotNearHeapLimit` removed *also* overflows at `ulimit -s 1024` on a debug build. On a release build, every stack size tested down to **512k** wrote a full ~6.2MB snapshot and then OOM-aborted as intended. V8 walks the object graph with worklists, not recursion. The unbounded ratchet is platform-independent, and the atomic rename makes a 0-byte artifact impossible regardless of why generation fails. --------- Co-authored-by: Nathan Whitaker <nathan@deno.com>
Fixes #36034.
v8.setHeapSnapshotNearHeapLimit()could leave 0-byte.heapsnapshotfiles behind, and the process would keep growing instead of OOMing — in the reporter's case until the machine itself ran out of memory and rebooted. Both symptoms come fromnear_heap_limit_snapshot_callbackinext/node/ops/v8.rs.Root cause
The heap limit ratcheted up without bound. Generating a snapshot itself runs a full GC (
HeapSnapshotGenerator::GenerateSnapshot→CollectAllAvailableGarbage), which re-enters the near-heap-limit callback while we're still writing. The oldprocessingguard returned a freshly computedcurrent_heap_limit + headroomon every reentry — andHeap::InvokeNearHeapLimitCallbackpasses the already-raised limit ascurrent_heap_limit, then raises again whenever the returned value exceeds it. So each reentry lifted the ceiling another notch, forever. The process never OOMed; it just consumed memory until something else gave out.For comparison, Node computes
new_limit = current_heap_limit + max_young_gen_sizeonce and its nested branch returns that fixed value, then undoes the raise viaAutomaticallyRestoreInitialHeapLimit(0.95). That API isn't bound in rusty_v8, so this PR bounds the raise by construction instead.The destination file was created up front.
File::createran before generation, so the.heapsnapshotexisted at 0 bytes from the outset. Any failure to complete generation — including being stuck in the ratchet above, or the process finally dying — left that empty file behind, and nothing treated "V8 emitted zero chunks" as a failure. (Node'sheap::WriteSnapshotopens its destinationO_CREAT|O_TRUNCup front too and has the same exposure; its guards are what keep it from getting there.)Changes
granted_limit; reentrant invocations return that same fixed ceiling. The limit rises exactly once, and once the snapshot spends that budget V8 OOMs normally..heapsnapshot.tmp, counting bytes, and isrenamed into place only after a successful non-empty write (withflush+sync_all+ close first, which Windows needs before the rename). An empty result or a write error removes the temp file and reports the failure, so the destination path never exists at 0 bytes.log::info!toeprintln!so it survives--quiet, matching Node. AddsWrote heap snapshot to …/Failed to write heap snapshot to …: <reason>.remove_near_heap_limit_callback(cb, 0)doesn't restore a minimal limit —Heap::RemoveNearHeapLimitCallbackonly callsRestoreHeapLimitfor a non-zero value. Passing 0 leaves the limit alone, which is what we want so the pending OOM actually happens.Tests
tests/specs/node/v8_set_heap_snapshot_near_heap_limit/now asserts the snapshot is non-empty and structurally valid (nodes/edges/stringspopulated) and that no.tmpfile is left behind. A newwrite_fail.tsstep makes the child's cwd read-only at the OS level so the write fails inside the callback, and asserts the failure is reported and no file is left behind (skipped on Windows and as root, wherechmoddoesn't bite).Verified against an OOM repro: a ~5.8 MB valid snapshot is written and renamed into place with no leftovers, and the process still OOM-aborts (exit 133, "Fatal JavaScript out of memory: Reached heap limit"). The read-only repro reports the failure and leaves nothing behind.
A note on the Windows angle
The report is from Windows, and a plausible theory was that V8's snapshot generator blew Windows' smaller native stack. That was investigated and disproved, so no stack change is included here:
/STACK:4194304. Cargo evaluatestarget.'cfg(...)'specs againstrustc --print cfg, whose output always containsdebug_assertionsregardless of profile — so the existingcfg(all(windows, debug_assertions))block has always applied to release too.setHeapSnapshotNearHeapLimitremoved also overflows atulimit -s 1024on a debug build. On a release build, every stack size tested down to 512k wrote a full ~6.2MB snapshot and then OOM-aborted as intended. V8 walks the object graph with worklists, not recursion.The unbounded ratchet is platform-independent, and the atomic rename makes a 0-byte artifact impossible regardless of why generation fails.