Skip to content

fix(ext/node): don't leave 0-byte .heapsnapshot files near the heap limit - #36113

Merged
nathanwhit merged 2 commits into
denoland:mainfrom
nathanwhitbot:orcha/impl-2c318d99
Jul 17, 2026
Merged

nathanwhit merged 2 commits into
denoland:mainfrom
nathanwhitbot:orcha/impl-2c318d99

Conversation

@nathanwhitbot

Copy link
Copy Markdown
Contributor

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 renamed 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.

…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 bartlomieju 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.

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.tmp behind. check.ts currently hard-fails on any leftover .tmp, which couples green CI to "4MB headroom is always enough for this heap." Consider tolerating a stray .tmp while still failing on the actual regression (a .heapsnapshot existing 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.
@nathanwhitbot

Copy link
Copy Markdown
Contributor Author

Thanks — took both non-blocking notes in 4857c4a.

  • Dropped the Wrote heap snapshot to ... success line. You're right that it over-mirrors: Node only prints Writing heap snapshot to ... up front and nothing on success. The failure lines stay, since a silent failure is what made heapsnapshot files sometimes 0 byte #36034 hard to spot.
  • check.ts no longer fails on a leftover .heapsnapshot.tmp, with a comment explaining why: a mid-generation OOM kills the process before cleanup runs, so the stray .tmp is the pre-existing "snapshot didn't fit" behaviour rather than the bug under test, and failing on it would tie green CI to the granted headroom always being enough. The regression assertion — no .heapsnapshot at the destination path at 0 bytes — is unchanged, and that's exactly what the temp-file dance guarantees: a half-written snapshot stays under .tmp.

Left the aliased &mut *(data) borrow alone as agreed — pre-existing and not worsened here, worth its own PR.

@bartlomieju bartlomieju 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.

LGTM. Both bugs correctly diagnosed and fixed:

  • Unbounded ratchet: stashing a single granted_limit on entry and returning it on reentry is the right fix. Verified the processing guard sits before the taken >= limit check, so every in-generation reentry returns the fixed ceiling and the limit is raised exactly once.
  • 0-byte file: streaming into .heapsnapshot.tmp and 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.

nathanwhit added a commit that referenced this pull request Jul 17, 2026
…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>
@nathanwhit
nathanwhit merged commit d859c22 into denoland:main Jul 17, 2026
267 of 270 checks passed
bartlomieju pushed a commit that referenced this pull request Jul 23, 2026
…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>
bartlomieju pushed a commit that referenced this pull request Jul 23, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

heapsnapshot files sometimes 0 byte

3 participants