Skip to content

Rust JSG: external memory accounting - #8411

Merged
bartlomieju merged 10 commits into
mainfrom
biwanczuk/rust-jsg-external-memory
Nov 18, 2026
Merged

bartlomieju merged 10 commits into
mainfrom
biwanczuk/rust-jsg-external-memory

Conversation

@bartlomieju

@bartlomieju bartlomieju commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Add Rust bindings for ExternalMemoryAdjustment and
ExternalMemoryTarget so resources can report native allocations
through C++ JSG's existing per-isolate accounting.

Adjustments support updates and drops on any thread, deferred
reporting without the owning isolate's lock, and cleanup after isolate
teardown. Add tests covering accounting, concurrency, garbage
collection, and isolate teardown.

@codecov-commenter

codecov-commenter commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 104 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.74%. Comparing base (bb08e38) to head (2912438).

Files with missing lines Patch % Lines
src/rust/jsg/external_memory.rs 0.00% 45 Missing ⚠️
src/rust/jsg/ffi.c++ 0.00% 39 Missing ⚠️
src/rust/jsg/v8.rs 0.00% 19 Missing ⚠️
src/rust/jsg/ffi.h 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8411      +/-   ##
==========================================
- Coverage   66.77%   66.74%   -0.04%     
==========================================
  Files         797      798       +1     
  Lines      204128   204232     +104     
  Branches    31719    31720       +1     
==========================================
+ Hits       136312   136313       +1     
- Misses      49215    49322     +107     
+ Partials    18601    18597       -4     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bartlomieju
bartlomieju force-pushed the biwanczuk/rust-jsg-external-memory branch from caab703 to 3ceecca Compare November 13, 2026 11:56
An ExternalMemoryAdjustment made without the isolate lock reports its
amount to the target's pending total, which V8 gets at the next lock.
Moved to the thread holding the lock and lowered or destroyed there
before then, it sent V8 the decrease while V8 had not seen the increase.
V8 checks that its total never falls below zero, in release builds too
(Heap::UpdateExternalMemory), so this aborted the process whenever the
isolate's reported total was smaller than the amount.

ExternalMemoryTarget::decreaseNow() now nets the pending total into a
decrease made under the lock, from maybeDeferAdjustment() and from
adjustNow(). V8 gets the net decrease; if the pending total exceeds the
decrease, the net rise goes back to the pending total for the next lock
and V8 gets nothing. Every adjustment's reported changes sum to zero or
more, so V8's total plus the pending total plus the decrease is zero or
more, and the net decrease can't take V8's total below zero. A decrease
never sends V8 a rise: a rise can make V8 force a GC or start
incremental marking, and a decrease often runs in a destructor,
including a cppgc finalizer while V8 sweeps, where starting a GC is not
safe. The pending total is exchanged only when it is nonzero.

adjustNow() of an adjustment whose target is another isolate, or one
already destroyed, reported the change to the lock's isolate, which had
never counted the memory. It now goes through maybeDeferAdjustment(), as
a change made without that isolate's lock.

Tests: decreases (destruction, adjust(), adjustNow()) of a 1 GiB pending
increase made on another thread, a pending total larger than the
decrease staying pending net of it, and adjustNow() of a destroyed
isolate's adjustment under another isolate's lock. Without the change,
the 1 GiB cases abort.
Add jsg::ExternalMemoryAdjustment and jsg::ExternalMemoryTarget, which
wrap C++ JSG's types of the same names, so Rust and C++ report external
memory to one total per isolate. A resource keeps an adjustment in a
field (lock.external_memory_adjustment(amount)) and changes it with
adjust/set; dropping it, as when V8 collects the resource, releases the
memory. Both are Send and Sync. A change made by a thread that has
entered the isolate, as every thread holding its lock in workerd has,
reaches V8 at once (debug builds assert it for a new adjustment); any
other goes to the target's pending total, which IsolateBase hands to V8
at the next lock, as in C++. After the isolate is destroyed, nothing
reaches V8.

adjust() returns a jsg::Result: its shim calls C++ adjust(), whose
check throws when the amount would fall below zero, and the bridge
returns that exception as an internal error. A method passes it on with
?, so JavaScript catches the same error a C++ method throws. The set()
shim caps a rise at SSIZE_MAX, since C++ set() passes the difference as
a ssize_t and would wrap a larger rise to a throwing fall; capped, any
amount of 32 GiB or more aborts as C++ JSG does, so set() can't fail.
adjustNow() and setNow() have no counterpart: they report at once
without asking which isolate is entered, and a lock holder in workerd
has entered it, so adjust and set report at once there too.

ffi.h defines the adjustment as an interface that ffi.c++ implements
around the C++ type, since the crates including ffi.h don't depend on
jsg.h. The shims use IsolateBase's target and adjustments, which Rust
JSG shares with C++ JSG like IsolateBase itself; the README says so.

Tests cover changes with and without the lock, under another isolate's
lock, after the isolate is gone, below zero (from Rust and from
JavaScript), adjustments made on one thread and lowered or dropped under
the lock on another (which rely on the parent commit), concurrent use
with and without the lock, a resource collected by GC, and a resource
still alive at teardown.

This unblocks ports that account for native memory (zlib, RPC,
HTMLRewriter).
@bartlomieju
bartlomieju force-pushed the biwanczuk/rust-jsg-external-memory branch from 3ceecca to 5cfb925 Compare November 13, 2026 15:29

@guybedford guybedford 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. Two small optional suggestions inline.

AI generated under my review

Comment thread src/rust/jsg/ffi.c++ Resolved
Comment thread src/rust/jsg/README.md Resolved
…ternal-memory

# Conflicts:
#	src/rust/jsg/README.md
C++ set() passes `amount - getAmount()` to adjust() as a ssize_t. With
the amount capped at SSIZE_MAX both operands are in range (an
adjustment is always below 32 GiB), so the difference converts without
wrapping, and a capped amount still aborts in
checkReasonableExternalMemoryTotal. That lets C++ set() do the
subtraction and drops the shim's two branches. Also rejoin a line the
README broke mid-paragraph.
@bartlomieju
bartlomieju marked this pull request as ready for review November 16, 2026 12:58
@bartlomieju
bartlomieju requested review from a team as code owners November 16, 2026 12:58

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 92bc2315.

This review, of c1247ea3

💬 Approved with comments — The C++ fixes and the Rust wrappers look correct. Two INFO notes: a debug-only assertion that contradicts the new cross-isolate branch in adjustNow(), and one awkward README sentence.

Findings: 2 info (2 are inline comments on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 1 info

The core logic is sound. A debug assertion in adjustNow() contradicts the new cross-isolate handling.

Recommendation: 💬 Optional Nits

  • [INFO] adjustNow(): the existing KJ_DEBUG assertion (target == js.v8Isolate) still fires for another live isolate's adjustment, so the new branch is reachable in debug builds only for destroyed isolates. (src/workerd/jsg/jsg.c++:611)
View full review
  • src/workerd/jsg/jsg.c++:604-616: the existing #ifdef KJ_DEBUG block asserts target == js.v8Isolate whenever the target isolate is non-null. In a debug build, adjustNow() of an adjustment counted against another live isolate therefore fails that assertion before it reaches the new branch. The branch's comment says this case is handled. Only the destroyed-isolate case is reachable and tested: the C++ test uses a destroyed isolate, and the Rust cross-isolate test goes through adjust(). Release builds behave as described.

ExternalMemoryTarget::decreaseNow() looks correct: netting the pending total keeps V8's total non-negative, and a net rise is returned to the pending total rather than sent to V8.


📝 Documentation: 💬 1 info

One awkward sentence in the Rust JSG README.

Recommendation: 💬 Optional Nits

  • [INFO] README: "as it catches the error a C++ method throws then" reads awkwardly. (src/rust/jsg/README.md:677)
View full review
  • src/rust/jsg/README.md:676-677: the sentence ending "as it catches the error a C++ method throws then" reads awkwardly.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security concerns in the FFI shims or the accounting changes.


📖 AGENTS.md: ✅ LGTM

The change follows the repository's guidance, including the safety rule that Rust JSG shims must not use C++ JSG.


⚡ Performance: ✅ LGTM

No performance concerns.


Reviewed commit: c1247ea3

Comment thread src/workerd/jsg/jsg.c++ Resolved
Comment thread src/rust/jsg/README.md Resolved
The shims that make an adjustment from Rust passed a size_t on as a
ssize_t (an int64_t through IsolateBase), so an amount above SSIZE_MAX
wrapped to a fall below zero and C++ threw, which the bridge turned into
a panic rather than the abort the docs promise. All three shims that take
an amount now cap it at SSIZE_MAX through one helper, so such an amount
aborts as too large.

decreaseNow() nets only a pending rise into a decrease reported to V8. A
pending fall is left for the next lock: V8's total plus the decrease is
zero or more without it, and leaving it out keeps the call within the
bound already checked for the decrease, which V8 checks too (a fall of
32 GiB or more in one call aborts).

adjustNow() no longer asserts in debug builds that the target is the
lock's isolate: the fallback for another isolate's adjustment handles it,
and the assert fired after the adjustment's amount had changed.

Tests: a pending decrease staying pending (C++ and Rust), adjustNow() of
a live isolate's adjustment under another isolate's lock, and threads
releasing reported memory without the lock while the lock holder makes
and lowers its own. Without the change, the first two fail.

Also tidy the ffi.h and README wording and the Send safety comment.

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 95934ec5.

This review, of 92bc2315

💬 Approved with comments — The C++ accounting fixes and the Rust wrappers look correct, and the earlier debug-assertion note is fixed. One README wording note (INFO) is still open.

Findings: 1 info

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📝 Documentation: 💬 1 info

One awkward README sentence is still open.

Recommendation: 💬 Optional Nits

  • [INFO] README: "as it catches the error a C++ method throws then" reads awkwardly. (src/rust/jsg/README.md:677)
View full review
  • src/rust/jsg/README.md:676-677: the sentence ending "as it catches the error a C++ method throws then" reads awkwardly.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security concerns in the FFI shims or the accounting changes.


📖 AGENTS.md: ✅ LGTM

The change follows the repository's guidance, including the safety rule that Rust JSG shims must not use C++ JSG.


📋 Code Quality: ✅ LGTM

The KJ_DEBUG assertion target == js.v8Isolate is gone from ExternalMemoryTarget::adjustNow() (src/workerd/jsg/jsg.c++:603-617). adjustNow() of another live isolate's adjustment, or of a destroyed isolate's, now takes the deferred path in every build, and both cases have tests.

On decreaseNow():

  • Netting a pending rise into a decrease keeps V8's total at zero or above.
  • A net rise goes back to the pending total.
  • A concurrent change to the pending total between its load and its exchange is restored with fetch_add.

All three Rust shims that take an amount cap it at SSIZE_MAX.


⚡ Performance: ✅ LGTM

No performance concerns.


Reviewed commit: 92bc2315

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

The netting fix in 5491e42 looks right to me, and it matters beyond Rust. Heap::UpdateExternalMemory does CHECK_GE(total_before, -delta), so a decrease that reaches V8 before its pending increase aborts in release builds too. Any C++ adjustment made without the lock and then lowered or dropped under it before the next lock can hit that today. Since that commit stands on its own, it might be worth landing as a separate PR, so it can be reviewed and bisected apart from the much larger Rust change.

A few things on the Rust side:

  • Cost guidance. Every adjustment is a heap allocation for the FFI wrapper plus an atomic refcount on the target, and each change can call into V8. That's fine for a handful of large, variable allocations per resource (a codec's state, an owned buffer), but it gets expensive fast if it's used per string or per small object. The atomic refcounting is what makes fine-grained adjustments costly. I'd add one line to the README section and the ExternalMemoryAdjustment docs: keep one adjustment per resource, sized to its large allocations, and update it at coarse points (construction, growth, release), not on every small allocation. The ExternalBuffer example already follows that pattern; spelling it out as a rule would stop it being copied into hot paths.
  • adjust() returning jsg::Result. Lowering an adjustment below zero is a bug in the resource's own bookkeeping, not something the script did, so surfacing it to JavaScript as an internal error turns an accounting bug into a user-visible exception. It matches C++ adjust(), so parity is a fair reason to keep it. But a debug_assert! plus clamping at zero (or a panic) would surface these bugs in tests rather than in production scripts. Worth a thought, not a blocker.
  • README length. The External memory section explains the threading model in one long paragraph. A resource author mostly needs three facts: make it under the lock, keep it in a field and set() it as the memory changes, and it's safe to drop on any thread. The netting and deferral details could move to the doc comment in external_memory.rs, where the reasoning lives.

Document adjustment costs and recommend per-resource accounting at coarse
update points. Keep the README focused on usage and failure behavior,
with reporting and deferral details in the API documentation.
@bartlomieju

Copy link
Copy Markdown
Collaborator Author

@littledivy In response to your review:

Split the C++ accounting fixes into #8497, which is now merged.

Added cost guidance to the README and ExternalMemoryAdjustment docs: keep one adjustment per resource for its significant native allocations, updated at construction, growth, and release, rather than creating adjustments for individual small allocations.

On adjust(), I'm keeping the existing checked error behavior. C++ rejects underflow before changing the amount or reporting anything to V8, so the failed operation leaves accounting unchanged. Clamping would conceal the bookkeeping error; making it fatal would let a resource accounting bug take down the runtime process. The Rust wrapper therefore keeps Result and the same failure behavior as C++. The docs now recommend set(total) when the resource knows its allocation size.

Shortened the README to focus on usage, threading guarantees, and error behavior, with the netting and deferral details in external_memory.rs.

Validation after merging main: 1,115 Rust JSG tests passed, including all 15 external-memory tests, plus both C++ JSG allowlist checks. The subsequent documentation changes passed formatting checks.

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 3955a657.

This review, of 95934ec5

✅ Approved — The earlier README wording note is fixed, and the updated README and external_memory.rs changes have no new issues.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security concerns in the FFI shims or the Rust wrappers.


📖 AGENTS.md: ✅ LGTM

The change follows the repository's guidance, including the rule that Rust JSG's C++ shims must not use C++ JSG.


📋 Code Quality: ✅ LGTM

The README and external_memory.rs changes since the last review are accurate. The set() shim caps the amount before C++ set() does the subtraction, so the difference stays in range.


⚡ Performance: ✅ LGTM

No performance concerns. The README recommends one adjustment per resource, updated at coarse points, which keeps per-update costs low.


📝 Documentation: ✅ LGTM

The awkward sentence in src/rust/jsg/README.md has been replaced with clear wording about lowering an adjustment below zero.


Reviewed commit: 95934ec5

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of dfc71ca5.

This review, of 3955a657

✅ Approved — The earlier README wording note is fixed, and the updated README and external_memory.rs changes have no new issues.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security concerns in the FFI shims or the Rust wrappers.


📖 AGENTS.md: ✅ LGTM

The change follows the repository's guidance, including the rule that Rust JSG's C++ shims must not use C++ JSG.


📋 Code Quality: ✅ LGTM

The README and external_memory.rs changes since the last review are accurate. The set() shim caps the amount before C++ set() does the subtraction, so the difference stays in range.


⚡ Performance: ✅ LGTM

No performance concerns. The README recommends one adjustment per resource, updated at coarse points, which keeps per-update costs low.


📝 Documentation: ✅ LGTM

The awkward sentence in src/rust/jsg/README.md has been replaced with clear wording about lowering an adjustment below zero.


Reviewed commit: 3955a657 — same changes as 95934ec5, so this is that commit's review (no new review was run; line numbers are as of 95934ec5)

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

The generated output of @cloudflare/workers-types matches the snapshot in types/generated-snapshot 🎉

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 29124387.

This review, of dfc71ca5

✅ Approved — No issues found. The only change since the last review is in external_memory.rs, which now uses the unchecked tracing macro from main. That is correct, since both wrapped C++ types hold no GC references.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security concerns in the FFI shims or the Rust wrappers.


📖 AGENTS.md: ✅ LGTM

The change follows the repository's guidance, including the rule that Rust JSG's C++ shims must not use C++ JSG.


📋 Code Quality: ✅ LGTM

No issues found.

Since the last review, src/rust/jsg/external_memory.rs has changed in one place: it now uses jsg_traced_unchecked!(ExternalMemoryAdjustment, ExternalMemoryTarget), the form of the macro on main. Neither wrapper holds a GC reference, so a no-op Traced and a HoldsNoGcReferences claim are correct for both.

All the earlier review threads have been dealt with:

  • The set() cap now applies to the amount.
  • The README wording has been fixed.
  • The adjustNow() debug assertion was fixed in #8497, which landed separately.

⚡ Performance: ✅ LGTM

No performance concerns. Each adjustment costs one FFI wrapper allocation. The docs recommend one adjustment per resource, updated at coarse points, which keeps that cost low.


📝 Documentation: ✅ LGTM

The README and API docs match the behaviour of the code.


Reviewed commit: dfc71ca5

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved — No issues found. The only change since the last review is in external_memory.rs, which now uses the unchecked tracing macro from main. That is correct, since both wrapped C++ types hold no GC references.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security concerns in the FFI shims or the Rust wrappers.


📖 AGENTS.md: ✅ LGTM

The change follows the repository's guidance, including the rule that Rust JSG's C++ shims must not use C++ JSG.


📋 Code Quality: ✅ LGTM

No issues found.

Since the last review, src/rust/jsg/external_memory.rs has changed in one place: it now uses jsg_traced_unchecked!(ExternalMemoryAdjustment, ExternalMemoryTarget), the form of the macro on main. Neither wrapper holds a GC reference, so a no-op Traced and a HoldsNoGcReferences claim are correct for both.

All the earlier review threads have been dealt with:

  • The set() cap now applies to the amount.
  • The README wording has been fixed.
  • The adjustNow() debug assertion was fixed in #8497, which landed separately.

⚡ Performance: ✅ LGTM

No performance concerns. Each adjustment costs one FFI wrapper allocation. The docs recommend one adjustment per resource, updated at coarse points, which keeps that cost low.


📝 Documentation: ✅ LGTM

The README and API docs match the behaviour of the code.


Reviewed commit: 29124387 — same changes as dfc71ca5, so this is that commit's review (no new review was run; line numbers are as of dfc71ca5)

@bartlomieju
bartlomieju merged commit 12fbdea into main Nov 18, 2026
23 checks passed
@bartlomieju
bartlomieju deleted the biwanczuk/rust-jsg-external-memory branch November 18, 2026 11:41
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.

5 participants