Skip to content

Unbind every Wrappable from its isolate at teardown - #8315

Merged
nathanwhit merged 1 commit into
mainfrom
nathanwhit/unbind-wrappable-teardown
Nov 10, 2026
Merged

nathanwhit merged 1 commit into
mainfrom
nathanwhit/unbind-wrappable-teardown

Conversation

@nathanwhit

Copy link
Copy Markdown
Member

At teardown, HeapTracer::clearWrappers cleared Wrappable::isolate only on Wrappables that had a wrapper. But visitRef also binds unwrapped children to the parent's isolate. Any of those that outlives the isolate keeps a dangling pointer, so destroying a Ref to it calls v8::Locker::IsLocked on a freed isolate.

Nothing in production is known to hit this. Rust JSG's jsg_cpp::Ref will.

Fix: HeapTracer also tracks bound Wrappables without a wrapper (unwrapped), and teardown unbinds both lists. Wrappable stays 96 bytes. Debug builds assert that bound Wrappables are destroyed under the lock and are only wrapped in their own isolate.

Tests: three jsg-test cases destroy a Ref after teardown: a child with no wrapper, a wrapped parent, and a detached wrapper. All three crash on main and pass with this change.

@nathanwhit
nathanwhit requested review from a team as code owners November 9, 2026 21:06

@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 27552cc8.

This review, of 0eeb9cbe

💬 Approved with comments — The teardown fix is correct and has tests. The open points are a debug assertion the description promises but the diff does not add, and a README sentence this change makes false. Neither affects production behaviour.

Findings: 1 warning · 1 info · 1 suggestion (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.

🔧 Fix with your agent

Paste the following into your coding agent to investigate and fix these issues.

Fix the following code review issues found in pull request #8315.

Before making changes, review each issue and present a brief summary table:
- For each finding, state whether you agree, disagree, or need clarification
- If you disagree (e.g., the fix would require disproportionate changes
  for minimal ROI, or the finding is factually incorrect), explain why
- If you need to clarify something before deciding, ask those questions
- Then share your plan for which issues to tackle and in what order

## WARNING (1)

### [Documentation] src/rust/jsg/README.md:511-512 still says a Wrappable that teardown never wrapped may point to the disposed isolate; this change unbinds such Wrappables at teardown, so the explanation is now false.
- **File:** src/rust/jsg/README.md:511

## INFO (1)

### [Code Quality] The 'only wrapped in its own isolate' debug assertion from the description is missing; a Wrappable bound in one isolate and wrapped in another would silently corrupt both tracers' lists.
- **File:** src/workerd/jsg/wrappable.c++:70

## SUGGESTION (1)

### [AGENTS.md] Consider recording the bound-Wrappable lifecycle invariant in src/workerd/jsg/AGENTS.md.
- **File:** src/workerd/jsg/wrappable.h:462

📖 AGENTS.md: 💬 1 suggestion

Optional: document the new Wrappable binding invariant in the JSG guidance.

Recommendation: 💬 Optional Nits

  • [SUGGESTION] Consider recording the bound-Wrappable lifecycle invariant in src/workerd/jsg/AGENTS.md. (src/workerd/jsg/wrappable.h:462)
View full review

src/workerd/jsg/AGENTS.md asks for its guidance to be updated when a JSG change introduces an invariant. This change adds one: a Wrappable bound to an isolate must be destroyed under that isolate's lock, and every bound Wrappable is tracked so teardown can unbind it.


📋 Code Quality: 💬 1 info

The fix is correct. The 'only wrapped in its own isolate' debug assertion from the description is not in the diff.

Recommendation: 💬 Optional Nits

  • [INFO] The 'only wrapped in its own isolate' debug assertion from the description is missing; a Wrappable bound in one isolate and wrapped in another would silently corrupt both tracers' lists. (src/workerd/jsg/wrappable.c++:70)
View full review

The two-list handoff is correct in detachWrapper, destroyLiveWrappableInstances and the condemned path. isCondemned() now tests linkedInWrappers, and visitRef binds a child only when the parent is bound.

The description says debug builds assert that bound Wrappables are only wrapped in their own isolate, but the diff does not add that check. Suppose visitRef binds a Wrappable to isolate A and isolate B later wraps it. addWrapper on B's tracer then removes it from B's unwrapped list while it is actually linked in A's list. Nothing catches this, and both lists' bookkeeping ends up corrupted. The case needs one Wrappable shared across isolates, so it is unlikely, but a KJ_DASSERT here would catch it cheaply.


📝 Documentation: ⚠️ 1 warning

The Rust JSG README says something about teardown that this change makes false.

Recommendation: 📝 Minor Comments

  • [WARNING] src/rust/jsg/README.md:511-512 still says a Wrappable that teardown never wrapped may point to the disposed isolate; this change unbinds such Wrappables at teardown, so the explanation is now false. (src/rust/jsg/README.md:511)
View full review

src/rust/jsg/README.md:511-512 says that releases after isolate disposal "only give back the counts, with no wrapper left to update, since a Wrappable that teardown never wrapped may still point to the disposed isolate." With this change, teardown also unbinds Wrappables that never had a wrapper, so that clause is no longer true. Please update the sentence, and keep whatever reason for routing those releases through the queue still holds.


✅ All other checks passed

🔒 Security: ✅ LGTM

No security concerns.


⚡ Performance: ✅ LGTM

No performance concerns. The new tracking adds a bool and a list operation per bind or unbind, and the description says Wrappable stays 96 bytes.


Reviewed commit: 0eeb9cbe

Comment thread src/workerd/jsg/wrappable.c++ Resolved
Comment thread src/workerd/jsg/wrappable.h Resolved
@codecov-commenter

codecov-commenter commented Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.95062% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.47%. Comparing base (19ca235) to head (cda006c).

Files with missing lines Patch % Lines
src/workerd/jsg/wrappable.c++ 74.41% 4 Missing and 7 partials ⚠️
src/workerd/jsg/jsg-test.c++ 97.14% 0 Missing and 1 partial ⚠️
src/workerd/jsg/wrappable.h 66.66% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8315      +/-   ##
==========================================
+ Coverage   65.46%   65.47%   +0.01%     
==========================================
  Files         759      759              
  Lines      192409   192479      +70     
  Branches    30344    30355      +11     
==========================================
+ Hits       125952   126018      +66     
+ Misses      48842    48837       -5     
- Partials    17615    17624       +9     

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

@nathanwhit
nathanwhit force-pushed the nathanwhit/unbind-wrappable-teardown branch from 0eeb9cb to 27552cc Compare November 9, 2026 22:00

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

This review, of 27552cc8

✅ Approved — All three earlier points are fixed: the cross-isolate debug assertion, the outdated README sentence and the missing AGENTS.md invariant. I found nothing new.

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.


📖 AGENTS.md: ✅ LGTM

src/workerd/jsg/AGENTS.md now states that a Wrappable bound to an isolate must be destroyed under that isolate's lock, and that it is wrapped only in that isolate.


📋 Code Quality: ✅ LGTM

attachWrapper now asserts that a bound Wrappable is wrapped only in its own isolate (src/workerd/jsg/wrappable.c++:97-98). The teardown handoff between the wrappers and unwrapped lists is consistent: clearWrappers handles detached wrappers, children bound while a wrapper is detached, and condemned Wrappables. visitRef binds a child only when the parent is bound. The three new tests cover each teardown case.


⚡ Performance: ✅ LGTM

The change adds a constant-time intrusive-list operation per bind, unbind or detach, and one bool per Wrappable. The teardown loops are linear and run once. The new assertions run only in debug builds.


📝 Documentation: ✅ LGTM

src/rust/jsg/README.md no longer claims that a Wrappable teardown never wrapped may still point to the disposed isolate.


Reviewed commit: 27552cc8

@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 2360488d.

This review, of f3112e87

💬 Approved with comments — The teardown fix is sound and nothing blocks it. One INFO: the lockfile changes are unrelated to the fix and downgrade hermetic_launcher.

Findings: 1 info (1 is an inline comment 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 teardown logic and tests are correct; the lockfile has changes unrelated to the fix.

Recommendation: 💬 Optional Nits

  • [INFO] MODULE.bazel.lock changes transitive dependencies (hermetic_launcher 0.0.17 → 0.0.16, aspect_tools_telemetry 0.5.1 → 0.5.2) that nothing in this pull request needs. (MODULE.bazel.lock:145)
View full review
  • MODULE.bazel.lock: MODULE.bazel is not changed, yet the lockfile is:

    • hermetic_launcher goes from 0.0.17 back to 0.0.16.
    • aspect_tools_telemetry goes from 0.5.1 to 0.5.2.
    • The yq.bzl usagesDigest changes.

    This looks like a lockfile regenerated on a stale or different base. Drop the hunk or regenerate it from current main.

The Wrappable changes look correct:

  • The wrappers/unwrapped handoff in addWrapper, removeWrapper, moveToUnwrapped and unbind keeps linkedInWrappers in step with the list the link is on.
  • isCondemned() keeps its meaning.
  • clearWrappers() handles condemned and detached wrappers, then unbinds what is left on unwrapped.
  • visitRef binds a child only when the parent is bound.

📝 Documentation: ❌ Error

The documentation review did not complete.

Recommendation: ❌ Error

View full review

This review did not cover the documentation changes in src/rust/jsg/README.md and src/workerd/jsg/AGENTS.md this time.


✅ All other checks passed

🔒 Security: ✅ LGTM

The change removes a dangling isolate pointer and adds no exposure. The lockfile change is noted under Code Quality.


📖 AGENTS.md: ✅ LGTM

The new src/workerd/jsg/AGENTS.md invariant matches the code: a Wrappable bound to an isolate is destroyed under that isolate's lock and is wrapped only in that isolate.


⚡ Performance: ✅ LGTM

Each bind, unbind or detach adds a constant-time list operation, and the teardown loops are linear. The new assertions run only in debug builds.


Reviewed commit: f3112e87

Comment thread MODULE.bazel.lock Resolved

@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, nice fix.

Comment thread src/workerd/jsg/wrappable.c++ Resolved
@nathanwhit
nathanwhit force-pushed the nathanwhit/unbind-wrappable-teardown branch 2 times, most recently from 2360488 to 57125ae Compare November 10, 2026 01:09

@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 57125ae5.

This review, of 2360488d

💬 Approved with comments — The fix is sound, and the approver's request to make both invariants release-mode checks has been addressed. The only finding is an INFO about wording in the new AGENTS.md invariant.

Findings: 1 info (1 is an inline comment on the diff)

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


📝 Documentation: 💬 1 info

The new invariant slightly overstates how long a bound Wrappable stays linked.

Recommendation: 💬 Optional Nits

  • [INFO] The new invariant says a bound Wrappable stays in a HeapTracer list until teardown, but destroying it under the lock unlinks it earlier. (src/workerd/jsg/AGENTS.md:157)
View full review

src/workerd/jsg/AGENTS.md:157-158 says a bound Wrappable stays in a HeapTracer list until isolate teardown unbinds it. In fact, destroying it under the lock unlinks it earlier.


✅ All other checks passed

🔒 Security: ✅ LGTM

The change removes a dangling isolate pointer and adds no new exposure.


📖 AGENTS.md: ✅ LGTM

The new invariant 15 matches the code, including its statement that breaking either rule aborts or throws.


📋 Code Quality: ✅ LGTM

Both invariants are now enforced in release builds:

  • unlinkFromTracer() aborts when a bound Wrappable is destroyed without its isolate's lock. Aborting is the right choice here, because throwing from a destructor would leave freed memory linked in the list.
  • attachWrapper uses KJ_ASSERT to refuse wrapping in a second isolate.

The wrappers/unwrapped handoff is consistent on every path checked:

  • detachFromShim and removeWrapper
  • destroyLiveWrappableInstances, which uses moveToUnwrapped
  • the second unwrapped loop in clearWrappers, which unbinds children that visitRef bound during teardown
  • shim destruction after teardown, which takes the isolate == nullptr path

The three new tests in jsg-test.c++ cover the unwrapped child, the wrapped parent and the detached wrapper.


⚡ Performance: ✅ LGTM

Each bind, unbind or detach adds one constant-time list operation, and the teardown loops are linear. Wrappable keeps its size, and the new release checks are cheap: a pointer compare, plus a lock check that runs only when a bound Wrappable is destroyed.


Reviewed commit: 2360488d

Comment thread src/workerd/jsg/AGENTS.md Resolved

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

This review, of 57125ae5

💬 Approved with comments — The fix is sound, and the approver's request to make both invariants release-mode checks has been addressed. The only finding is an INFO about wording in the new AGENTS.md invariant.

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

The new invariant slightly overstates how long a bound Wrappable stays linked.

Recommendation: 💬 Optional Nits

  • [INFO] The new invariant says a bound Wrappable stays in a HeapTracer list until teardown, but destroying it under the lock unlinks it earlier. (src/workerd/jsg/AGENTS.md:157)
View full review

src/workerd/jsg/AGENTS.md:157-158 says a bound Wrappable stays in a HeapTracer list until isolate teardown unbinds it. In fact, destroying it under the lock unlinks it earlier.


✅ All other checks passed

🔒 Security: ✅ LGTM

The change removes a dangling isolate pointer and adds no new exposure.


📖 AGENTS.md: ✅ LGTM

The new invariant 15 matches the code, including its statement that breaking either rule aborts or throws.


📋 Code Quality: ✅ LGTM

Both invariants are now enforced in release builds:

  • unlinkFromTracer() aborts when a bound Wrappable is destroyed without its isolate's lock. Aborting is the right choice here, because throwing from a destructor would leave freed memory linked in the list.
  • attachWrapper uses KJ_ASSERT to refuse wrapping in a second isolate.

The wrappers/unwrapped handoff is consistent on every path checked:

  • detachFromShim and removeWrapper
  • destroyLiveWrappableInstances, which uses moveToUnwrapped
  • the second unwrapped loop in clearWrappers, which unbinds children that visitRef bound during teardown
  • shim destruction after teardown, which takes the isolate == nullptr path

The three new tests in jsg-test.c++ cover the unwrapped child, the wrapped parent and the detached wrapper.


⚡ Performance: ✅ LGTM

Each bind, unbind or detach adds one constant-time list operation, and the teardown loops are linear. Wrappable keeps its size, and the new release checks are cheap: a pointer compare, plus a lock check that runs only when a bound Wrappable is destroyed.


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

@nathanwhit
nathanwhit force-pushed the nathanwhit/unbind-wrappable-teardown branch from 57125ae to daa3364 Compare November 10, 2026 01:31

@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 3a9b0e06.

This review, of daa33647

✅ Approved — The teardown fix is sound and its invariants are now enforced in release builds. The earlier AGENTS.md wording note is fixed, and no open findings remain.

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

The change removes a dangling isolate pointer and adds no new exposure.


📖 AGENTS.md: ✅ LGTM

Invariant 15 matches the code: destroying a bound Wrappable off its isolate's lock aborts, and wrapping it in another isolate throws.


📋 Code Quality: ✅ LGTM

The wrappers/unwrapped handoff in HeapTracer is consistent on every path:

  • detach and removal of a wrapper
  • destroyLiveWrappableInstances
  • the teardown loops in clearWrappers
  • shim destruction after teardown

The new release-mode assertions guard both invariants. The three new tests cover an unwrapped child, a wrapped parent and a detached wrapper.


⚡ Performance: ✅ LGTM

Binding, unbinding and detaching each add one constant-time list operation, and the teardown loops are linear. Wrappable stays 96 bytes. The release-mode checks are cheap: a pointer compare, plus a lock check that runs only when a bound Wrappable is destroyed.


📝 Documentation: ✅ LGTM

Invariant 15 in src/workerd/jsg/AGENTS.md now says correctly that a bound Wrappable stays in a HeapTracer list until it is destroyed or isolate teardown unbinds it.


Reviewed commit: daa33647

@nathanwhit
nathanwhit force-pushed the nathanwhit/unbind-wrappable-teardown branch from daa3364 to 3a9b0e0 Compare November 10, 2026 18:01

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

This review, of 3a9b0e06

✅ Approved — The teardown fix is sound and its invariants are now enforced in release builds. The earlier AGENTS.md wording note is fixed, and no open findings remain.

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

The change removes a dangling isolate pointer and adds no new exposure.


📖 AGENTS.md: ✅ LGTM

Invariant 15 matches the code: destroying a bound Wrappable off its isolate's lock aborts, and wrapping it in another isolate throws.


📋 Code Quality: ✅ LGTM

The wrappers/unwrapped handoff in HeapTracer is consistent on every path:

  • detach and removal of a wrapper
  • destroyLiveWrappableInstances
  • the teardown loops in clearWrappers
  • shim destruction after teardown

The new release-mode assertions guard both invariants. The three new tests cover an unwrapped child, a wrapped parent and a detached wrapper.


⚡ Performance: ✅ LGTM

Binding, unbinding and detaching each add one constant-time list operation, and the teardown loops are linear. Wrappable stays 96 bytes. The release-mode checks are cheap: a pointer compare, plus a lock check that runs only when a bound Wrappable is destroyed.


📝 Documentation: ✅ LGTM

Invariant 15 in src/workerd/jsg/AGENTS.md now says correctly that a bound Wrappable stays in a HeapTracer list until it is destroyed or isolate teardown unbinds it.


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

`Wrappable::isolate` is set when a wrapper is attached, and also when a
parent bound to an isolate first visits a `Ref<T>` to it (`visitRef`).
`HeapTracer::clearWrappers` cleared it only on the Wrappables that had a
wrapper at teardown. Any other Wrappable that outlived its isolate kept a
dangling pointer, and destroying a `Ref<T>` to it crashed:
`maybeDeferDestruction` calls `v8::Locker::IsLocked` on the freed
isolate. That covers:

- a child that never had a wrapper, held past teardown;
- the children of a wrapped object that outlives the isolate: detaching
  its wrapper at teardown visits them, which binds them;
- an object whose wrapper was detached earlier, as by a minor GC.

Nothing in production is known to hold such a `Ref<T>`: hibernatable
WebSockets, which outlive their isolate, visit only V8 handles, which
check `IsolateLiveness`. A Rust `jsg_cpp::Ref` held past teardown does.

The HeapTracer now also keeps a list of the bound Wrappables without a
wrapper, `unwrapped`. It shares the `link` of `wrappers`, with a flag in
existing padding saying which list it is in, so `Wrappable` stays 96
bytes. Teardown unbinds the Wrappables in both lists, and `~Wrappable`
unlinks itself. Unlinking relies on bound Wrappables being destroyed
under the isolate lock, which `maybeDeferDestruction` ensures for
`Ref<T>`. Breaking that rule, or wrapping a bound Wrappable in another
isolate, would corrupt the lists, so both are checked in every build:
destroying a bound Wrappable without the lock aborts, since throwing
from `~Wrappable` would leave it linked, and wrapping it in another
isolate throws.
@nathanwhit
nathanwhit force-pushed the nathanwhit/unbind-wrappable-teardown branch from 3a9b0e0 to cda006c Compare November 10, 2026 22:25

@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 — This commit has no findings. The teardown fix is consistent on every path, and both of its invariants are enforced in release builds.

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

The change removes a dangling isolate pointer and adds no new exposure.


📖 AGENTS.md: ✅ LGTM

Invariant 15 in src/workerd/jsg/AGENTS.md matches the enforced behaviour.


📋 Code Quality: ✅ LGTM

The wrappers/unwrapped handoff is consistent on every path:

  • addWrapper removes the Wrappable from unwrapped.
  • The teardown loops unbind each Wrappable before it can be destroyed.
  • The new visitor.parent.isolate != nullptr guard stops a parent that is already unbound from binding its children.

The isolate-mismatch check and the off-lock destroy check both run in release builds. The three new tests cover the three teardown paths.


⚡ Performance: ✅ LGTM

Each tracer list operation is constant time, the teardown loops are linear, and Wrappable stays 96 bytes.


📝 Documentation: ✅ LGTM

The src/rust/jsg/README.md and src/workerd/jsg/AGENTS.md updates match the code.


Reviewed commit: cda006cb

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.

4 participants