Skip to content

Release Rust jsg::Rc and jsg::Weak under their isolate's lock - #8111

Merged
nathanwhit merged 1 commit into
mainfrom
nathanwhit/release-rc-under-lock
Nov 5, 2026
Merged

nathanwhit merged 1 commit into
mainfrom
nathanwhit/release-rc-under-lock

Conversation

@nathanwhit

Copy link
Copy Markdown
Member

Problem

The reference counts behind Rust JSG references aren't atomic. The isolate lock is the only thing that keeps two threads from updating them at the same time:

  • jsg::Rc<R> holds the resource's std::rc::Rc<R> and its Wrappable's kj::Rc (KjRc).
  • jsg::Weak<R> holds a std::rc::Weak<R>.

An Rc or Weak can still be dropped without the lock, for example by C++ code that owns the Rust object holding it. Before this change, such a drop deferred only the removeStrongRef call, through maybeDeferDestruction, and only if the Wrappable had been wrapped. The KjRc and std::rc::Rc counts were still updated on the dropping thread, racing with the lock holder. A resource that had never been wrapped had no isolate to defer to, so its release ran entirely off-lock.

Fix

Rc and Weak now keep the IsolateState of the isolate their resource was created in. That's the state Global and TracedGlobal already use to queue handles dropped without the lock.

  • Under the lock, a drop releases the reference immediately, as before: removeStrongRef if the Rc still counts as strong, then the KjRc and std::rc::Rc drop.
  • Without the lock, the parts are moved into the state's mutex-protected queue without touching any count. The next IsolateBase::Lock releases them, through the deferred-action hook that already resets queued handles. Until then the queued reference keeps the resource and its wrapper alive, like a C++ jsg::Ref waiting in the deferred destruction queue.
  • Weak queues its std::rc::Weak the same way. It keeps its own copy of the state because its target may already be gone, as C++ jsg::WeakRef does with IsolateLiveness.
  • Teardown: Realm::drop releases anything still queued before it closes the state. After that, every drop is kept until the isolate is disposed, since dropWrappers and Dispose still touch the counts and no thread can safely ask whether it holds the lock. The dispose hook then releases them, and later drops go through the same queue, which one thread at a time drains. These releases only give back the counts: no wrapper is left, and an unwrapped Wrappable can still point to the disposed isolate, because detaching a strongly held parent's wrapper copies the isolate into its children. As in C++, a resource that outlives its isolate must then be used by one thread at a time.
  • wrappable_remove_strong_ref now just calls removeStrongRef(). Rust no longer goes through maybeDeferDestruction.

API changes

  • Rc::new now takes a Lock: jsg::Rc::new(lock, resource), mirroring C++ js.alloc<T>(). This is how a resource knows its isolate before it's ever wrapped.
    • UrlUtil::new, DnsUtil::new and InspectorModule::new in src/rust/api take a lock accordingly.
    • The two jsg-macros call sites already had one.
  • New panic in wrap: wrapping a resource in an isolate other than the one it was created in now panics, even if it has no wrapper yet. Before, this only panicked when the resource already had a wrapper in another isolate. Otherwise its queued releases could run under the wrong isolate's lock.
  • This changes no API exposed to Workers.

Cost

Each Rc grows from 40 to 48 bytes and each Weak from 16 to 24, for the Arc<IsolateState>. Every Rc clone and drop also does one uncontended atomic increment and decrement on that Arc.

jsg-bench, built with --config=benchmark on an Apple M5 Pro. The timings are medians of five processes, each with 5 interleaved repetitions. The benchmarks measure drops under the lock; the queued and post-dispose paths aren't on that path.

native/lifetime, ns per resource before after
0 clones 35.4 33.9
1 clone 47.6 44.0
16 clones 216.0 177.8
native-memory, bytes per resource before after
Rust 232 256
C++ (unchanged) 192 192
  • Clones and drops got faster despite the atomics. The drop path no longer does a kj::addRef or builds a RefToDelete.
  • The timing comparison isn't exact. The C++ cases measured 3–7% slower in the same runs. Part of that may come from the benchmark now running inside a locked isolate.

Reviewer notes

  • The core change is in src/rust/jsg/isolate_state.rs (release, drain_awaiting_lock, close, isolate_disposed, drain_disposed, ReleaseContext) and src/rust/jsg/resource.rs (Rc/Weak Drop, ReleasedRc, wrap).
  • Most of the diff is the mechanical Rc::new(lock, …) change in tests.
  • Released has an unsafe impl Send. Its parts are !Send only because their counts aren't atomic. Queuing moves them without touching any count. Before disposal they're released under the lock, by drain_awaiting_lock or close. After disposal they're released only by the thread holding draining_disposed, which is set together with disposed, so two releases never overlap.
  • The deferred-action hook is renamed from realm_reset_globals_awaiting_lock to realm_drain_awaiting_lock, since it now releases references too.

@nathanwhit
nathanwhit requested review from a team as code owners October 30, 2026 21:18

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

This review, of c504811b

💬 Approved with comments — I found no correctness or safety problems in the new queued and post-dispose release paths for Rc and Weak. What's left is one stale README example, a doc-comment wrapping nit and a pointer that could be added to the agent guidance, none of which blocks.

Findings: 1 info · 2 suggestions

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


📖 AGENTS.md: 💬 1 suggestion

The Rust agent guidance could point to the new Rc/Weak release rules.

Recommendation: 💬 Optional Nits

  • [SUGGESTION] Next to the existing guidance on dropping Global/TracedGlobal without the lock, add a short pointer to the new Rc/Weak release rules in src/rust/jsg/README.md, including that Rc::new takes a lock. (src/rust/AGENTS.md:42)
View full review
  • src/rust/AGENTS.md describes what happens when a Global or TracedGlobal is dropped without the lock. It doesn't mention that Rc and Weak now follow similar rules, or that Rc::new takes the resource's lock. A short pointer to the new section in src/rust/jsg/README.md would surface this.

📋 Code Quality: 💬 1 suggestion

The core release logic is sound. One doc-comment wrapping nit.

Recommendation: 💬 Optional Nits

  • [SUGGESTION] Rewrap the edited doc comments on the realm_drain_awaiting_lock and isolate_disposed bridge declarations: one line is cut short and another runs to about 105 characters. (src/rust/jsg/lib.rs:8)
View full review

Nit

  • The doc comments on the realm_drain_awaiting_lock and isolate_disposed bridge declarations in src/rust/jsg/lib.rs were edited in place and need rewrapping. One line is cut short and another runs to about 105 characters.

What I checked and found correct

  • IsolateState (src/rust/jsg/isolate_state.rs)
    • release, close, drain_awaiting_lock and drain_disposed never drop a Released while the queue mutex is held, so a release that triggers further drops cannot deadlock.
    • close drains released_awaiting_lock again after it sets closed, so a push that races with close isn't lost.
    • isolate_disposed sets draining_disposed together with disposed, and drain_disposed clears it only once a batch comes back empty. Post-dispose releases therefore stay serialized, and re-entrant drops on the draining thread just add to the queue.
  • Rc and Weak drops (src/rust/jsg/resource.rs)
    • Rc::drop takes each ManuallyDrop field exactly once.
    • removeStrongRef is skipped when tracing has weakened the reference, and in the Disposed context.
    • Weak::drop handles a missing state.
    • The new Arc::ptr_eq check in wrap runs before any wrapping happens.
  • FFI. The new wrappable_remove_strong_ref signature matches across ffi.c++, ffi.h and v8.rs.
  • Call sites. The Rc::new(lock, …) migration in src/rust/api, jsg-macros, the tests and the bench is consistent. The new cross-isolate wrap panic has a test.

📝 Documentation: 💬 1 info

One macro README example no longer reflects the new Rc::new(lock, …) requirement.

Recommendation: 💬 Optional Nits

  • [INFO] The static factory example create(name: String) -> Result<jsg::Rc<Self>, jsg::Error> takes no lock, but constructing an Rc now needs jsg::Rc::new(lock, …). Add a lock: &mut Lock parameter to the example. (src/rust/jsg-macros/README.md:111)
View full review
  • src/rust/jsg-macros/README.md:111: the static create factory example returns jsg::Rc<Self> but takes no lock. Constructing an Rc now needs jsg::Rc::new(lock, resource), so add a lock: &mut Lock parameter to the example, as DnsUtil::new in src/rust/api/dns.rs now has.

✅ All other checks passed

🔒 Security: ✅ LGTM

  • unsafe impl Send for Released. The invariant behind it holds:
    • Queuing touches no count.
    • Before disposal, queued parts are released only under the isolate lock, by drain_awaiting_lock or close.
    • After disposal, they're released only by the single thread that holds draining_disposed.
  • Queue checks. release checks is_closed() under the same mutex that close holds when it sets closed. A reference queued while the state is open is therefore always released by the next lock or by close.
  • Cross-isolate wrap. The new panic stops a resource's queued releases from running under another isolate's lock.
  • Clones after disposal. Clones aren't serialized once the isolate is disposed. That is a documented contract, matching C++ JSG objects that outlive their isolate.

⚡ Performance: ✅ LGTM

  • Locked drops. A drop under the lock takes no mutex and allocates nothing.
  • Off-lock drops. A drop without the lock takes the queue mutex and allocates one boxed closure. That path is rare.
  • Draining. drain_awaiting_lock takes the mutex once per IsolateBase::Lock and swaps the vectors out.
  • Size. The extra 8 bytes per Rc and Weak, plus the uncontended atomic increment and decrement on the Arc, match the costs measured in the description.

Reviewed commit: c504811b

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from c504811 to acc4b77 Compare October 30, 2026 21:22

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

This review, of acc4b776

💬 Approved with comments — Nothing blocks and there are no warnings. The only open items are the same three notes as last time: a stale README example, a doc-comment rewrap nit and a suggested pointer in the agent guidance.

Findings: 1 suggestion

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


📋 Code Quality: 💬 1 suggestion

One nit: a doc comment still needs rewrapping.

Recommendation: 💬 Optional Nits

  • [SUGGESTION] Rewrap the edited doc comments on the realm_drain_awaiting_lock and isolate_disposed bridge declarations: line 111 runs to 104 characters. (src/rust/jsg/lib.rs:111)
View full review

Nit

  • The doc comments on the realm_drain_awaiting_lock and isolate_disposed bridge declarations in src/rust/jsg/lib.rs still need rewrapping. Line 111 is 104 characters long.

What I checked and found correct

  • Rc and Weak drops: each field is taken exactly once.
  • Queue mutex: it is never held while a reference is released, so a release that triggers further drops cannot deadlock.
  • No lost references: every queued reference is eventually released, by close, drain_awaiting_lock or drain_disposed.
  • FFI: the realm_drain_awaiting_lock rename and the new wrappable_remove_strong_ref signature match between lib.rs and ffi.c++.

✅ All other checks passed

🔒 Security: ✅ LGTM

  • unsafe impl Send for Released: the invariant holds.
    • Queuing touches no reference count.
    • Before disposal, queued parts are released only under the isolate lock, by drain_awaiting_lock or close.
    • After disposal, only the thread holding draining_disposed releases them, so two releases never overlap.
  • release: it checks is_closed() under the same mutex close holds when it sets closed, so a push is never lost.
  • Cross-isolate wrap: the panic happens before any wrapping, so no release can run under another isolate's lock.
  • FFI: the wrappable_remove_strong_ref signature matches across ffi.c++, ffi.h and v8.rs.

📖 AGENTS.md: ✅ LGTM

  • src/rust/AGENTS.md:42 describes what happens when a Global or TracedGlobal is dropped without the lock.
  • It doesn't mention that Rc and Weak now follow similar rules, or that Rc::new takes a lock.
  • A short pointer to the new section on dropping references in src/rust/jsg/README.md would surface this.

⚡ Performance: ✅ LGTM

  • Drops under the lock: no mutex and no allocation.
  • Drops without the lock: one mutex acquisition and one boxed closure. This path is rare.
  • Draining: the mutex is taken once per lock acquisition, and the vectors are swapped out.
  • Cost: the extra 8 bytes per Rc and Weak, and the uncontended atomic increment and decrement on each clone and drop, match the measurements in the description.

📝 Documentation: ✅ LGTM

  • src/rust/jsg-macros/README.md:111: the static create example returns jsg::Rc<Self> but takes no lock. Rc::new now requires a lock, so add a lock: &mut Lock parameter, as DnsUtil::new in src/rust/api/dns.rs now has.

Reviewed commit: acc4b776

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from acc4b77 to c850b4c Compare November 2, 2026 20:03

@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 4aea4f8d.

This review, of c850b4ca

💬 Approved with comments — Nothing blocks and there are no warnings. The release, queue and teardown logic in isolate_state.rs and resource.rs checks out; the only open items are two doc-comment line-length nits.

Findings: 2 suggestions (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: 💬 2 suggestions

No correctness problems; two doc-comment rewrap nits.

Recommendation: 💬 Optional Nits

  • [SUGGESTION] The first line of the termination_survives_call doc comment is 139 characters; rewrap it to the file's ~100-column width. (src/rust/jsg-test/tests/termination.rs:160)
  • [SUGGESTION] Rewrap the edited doc comments on the realm_drain_awaiting_lock and isolate_disposed bridge declarations: line 111 runs to 104 characters. (src/rust/jsg/lib.rs:111)
View full review

Nits

  • src/rust/jsg-test/tests/termination.rs:160: the first line of the termination_survives_call doc comment is 139 characters long. The lines around it wrap at about 100.
  • src/rust/jsg/lib.rs:111: the doc comments on the realm_drain_awaiting_lock and isolate_disposed bridge declarations still need rewrapping. Line 111 is 104 characters long.

What I checked and found correct

  • Queue mutex: release, close and drain_awaiting_lock never hold it while releasing a reference, so a release that drops more references cannot deadlock.
  • No lost pushes: close takes the queue a second time after it sets closed. The draining_disposed handoff holds under the mutex, and drain_disposed loops until it picks up pushes that arrive while it drains.
  • Rc and Weak drops: each field is taken exactly once. A default-constructed Weak has no state and is skipped.
  • State propagation: new, clone, FromJS and Weak::upgrade all build through from_parts, so every Rc carries its isolate's state.
  • wrap: the isolate-identity check runs before any wrapping.
  • FFI: the realm_drain_awaiting_lock rename and the one-argument wrappable_remove_strong_ref match across lib.rs, ffi.c++, ffi.h and v8.rs.
  • Tests: the Rc::new(lock, …) migration is mechanical. The new lifetime tests in gc.rs and isolates.rs cover these paths:
    • drops without the lock, including from another thread;
    • release when the realm is dropped;
    • drops after dispose;
    • the new panic when a resource is wrapped in an isolate other than the one it was created in.

✅ All other checks passed

🔒 Security: ✅ LGTM

  • unsafe impl Send for Released: the invariant holds.
    • Queuing touches no reference count.
    • Before disposal, queued parts are released only under the isolate lock.
    • After disposal, only the thread holding draining_disposed releases them.
  • Cross-isolate wrap: it panics before any wrapping, so no queued release can run under another isolate's lock.

📖 AGENTS.md: ✅ LGTM

No new AGENTS.md issues.


⚡ Performance: ✅ LGTM

  • Drops under the lock: no mutex and no allocation.
  • Drops without the lock: one mutex acquisition and one boxed closure. This path is rare.
  • Draining: the mutex is taken once per lock acquisition.
  • Cost: the extra atomic increment and decrement on each Rc clone and drop matches the benchmarks in the description.

📝 Documentation: ✅ LGTM

No new documentation issues.


Reviewed commit: c850b4ca

Comment thread src/rust/jsg-test/tests/termination.rs Resolved
Comment thread src/rust/jsg/lib.rs Resolved
@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from c850b4c to 4aea4f8 Compare November 2, 2026 23:02

@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 2bdda027.

This review, of 4aea4f8d

💬 Approved with comments — Nothing blocks and there are no warnings. The earlier nits are fixed, and the one open item is an INFO on the new src/rust/AGENTS.md line, which leaves out the release path after teardown.

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.


📖 AGENTS.md: 💬 1 info

The new jsg::Rc / jsg::Weak guidance doesn't mention what happens after the Realm is dropped.

Recommendation: 💬 Optional Nits

  • [INFO] The new jsg::Rc / jsg::Weak guidance leaves out what happens to queued references after the Realm is dropped. (src/rust/AGENTS.md:43)
View full review
  • src/rust/AGENTS.md:43: the new line says a drop without the lock is released at the next IsolateBase::Lock. That is not true after the Realm is dropped: from then on, queued references are kept until the isolate is disposed. The Global / TracedGlobal line just above already states its own teardown exception.

✅ All other checks passed

🔒 Security: ✅ LGTM

No new security issues. The unsafe impl Send for Released invariant and the panic on a cross-isolate wrap are unchanged since the last review.


📋 Code Quality: ✅ LGTM

  • Earlier nits fixed: the termination_survives_call doc comment in termination.rs and the realm_drain_awaiting_lock / isolate_disposed doc comments in jsg/lib.rs are now wrapped at 100 columns.
  • Rust Rc and Weak drops: each field is still taken exactly once.
  • wrap: the isolate check still runs before any wrapping.
  • FFI: the realm_drain_awaiting_lock rename and the one-argument wrappable_remove_strong_ref match across lib.rs, ffi.c++, ffi.h and v8.rs.
  • Tests: the Rc::new(lock, …) changes are mechanical.

⚡ Performance: ✅ LGTM

  • Drops under the lock: no mutex and no allocation.
  • Drops without the lock: one mutex acquisition and one boxed closure. This path is rare.
  • Extra cost: the added atomic increment and decrement on each Rc clone and drop is the cost the description reports with benchmarks.

📝 Documentation: ✅ LGTM

No new documentation issues.


Reviewed commit: 4aea4f8d

Comment thread src/rust/AGENTS.md Resolved
@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from 4aea4f8 to 2bdda02 Compare November 2, 2026 23:18

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

This review, of 2bdda027

💬 Approved with comments — Nothing blocks and there are no warnings. The only change since the last review is the mechanical Rc::new(lock, …) update in js_string.rs. One INFO stays open on the src/rust/AGENTS.md line about drops, which leaves out what happens after teardown.

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.


📖 AGENTS.md: 💬 1 info

The new jsg::Rc / jsg::Weak line leaves out what happens to queued references after teardown.

Recommendation: 💬 Optional Nits

  • [INFO] The jsg::Rc / jsg::Weak line leaves out that, once the Realm is dropped, queued references are kept until the isolate is disposed. (src/rust/AGENTS.md:43)
View full review
  • src/rust/AGENTS.md:43 says a drop without the lock is released at the next IsolateBase::Lock. That stops being true once the Realm is dropped: after that, queued references are kept until the isolate is disposed. The Global / TracedGlobal line just above it already covers its own teardown case.

✅ All other checks passed

🔒 Security: ✅ LGTM

No new security issues. The invariant behind unsafe impl Send for Released and the panic on a cross-isolate wrap haven't changed.


📋 Code Quality: ✅ LGTM

  • Since the last review: js_string.rs gets the same mechanical Rc::new(lock, …) update as the other tests.
  • Rc and Weak drops: each field is taken exactly once. Weak::drop handles a default-constructed Weak, which has no state.
  • IsolateState::release:
    • The closed check and close use the same mutex, so a reference queued while the state is open can't be missed.
    • drain_awaiting_lock and drain_disposed release references outside the mutex, so a release that drops further references can't deadlock.
  • wrap: the isolate check runs before any wrapping.
  • FFI: the realm_drain_awaiting_lock rename and the one-argument wrappable_remove_strong_ref match across lib.rs, ffi.c++, ffi.h and v8.rs.

⚡ Performance: ✅ LGTM

No issues. A drop under the lock takes no mutex and allocates nothing. The added atomic increment and decrement on each Rc clone and drop is the cost the description already measures.


📝 Documentation: ✅ LGTM

No new documentation issues.


Reviewed commit: 2bdda027

Comment thread src/rust/AGENTS.md Resolved
@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from 2bdda02 to cc800f3 Compare November 2, 2026 23:22

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

This review, of cc800f30

✅ Approved — No findings. The one remaining note from the last review is fixed: src/rust/AGENTS.md:43 now says that once the Realm is dropped, queued references are kept until the isolate is disposed.

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 new security issues. The invariant behind unsafe impl Send for Released and the panic on a cross-isolate wrap are unchanged.


📖 AGENTS.md: ✅ LGTM

The jsg::Rc / jsg::Weak line in src/rust/AGENTS.md:43 now says that once the Realm is dropped, dropped references are kept until the isolate is disposed and then released by the dispose hook. That fixes the earlier note.


📋 Code Quality: ✅ LGTM

No issues found.

  • Rc and Weak drops: each field is taken exactly once. Weak::drop handles a default-constructed Weak, which has no state.
  • Teardown in isolate_state.rs: queue locking, the order of close, and the hand-off through draining_disposed are consistent. References are released outside the mutex.
  • wrap: the isolate check runs before any wrapping.
  • FFI: every caller of wrappable_remove_strong_ref now holds the isolate lock, so calling removeStrongRef() directly does the same thing the old path did. The realm_drain_awaiting_lock rename matches across lib.rs, ffi.c++ and ffi.h.
  • Tests: the Rc::new(lock, …) updates are mechanical. The new tests in gc.rs and isolates.rs cover drops without the lock, drops on another thread, drops after the Realm is dropped and after the isolate is disposed, the Weak case, and wrapping a resource in an isolate other than the one it was created in.

⚡ Performance: ✅ LGTM

No issues found.


📝 Documentation: ✅ LGTM

No documentation issues.


Reviewed commit: cc800f30

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

Looks good. Extending the Global drop queue to Rc and Weak closes the races on releases made without the lock, and the tests cover the cross-thread and after-dispose paths well.

One follow-up to consider, not blocking: drops are now safe anywhere, but Rc::clone, Weak::clone, Weak::upgrade and Deref still touch the same non-atomic counts, or R's cells, without needing the lock. Since Rc::new takes a lock now anyway, every other operation could take one too: rc.get(lock) -> &R instead of Deref, clone(lock) instead of Clone, and upgrade(lock). If the lock is only checked at the call (fn get<'a>(&'a self, _lock: &Lock<'_>) -> &'a R), it doesn't conflict with using &mut Lock afterwards.

A nice side effect is that Drop code, which has no lock, can no longer touch an Rc at all. The rule becomes "drop anywhere, everything else needs the lock", and the compiler enforces it. Very little production code uses jsg::Rc yet, so now seems like the cheapest time to do it.

AI generated under my review

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from cc800f3 to d0063f1 Compare November 3, 2026 01:43

@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 66d260cb.

This review, of d0063f12

✅ Approved — No findings. The one remaining note from the last review is fixed: src/rust/AGENTS.md:43 now says that once the Realm is dropped, queued references are kept until the isolate is disposed.

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 new security issues. The invariant behind unsafe impl Send for Released and the panic on a cross-isolate wrap are unchanged.


📖 AGENTS.md: ✅ LGTM

The jsg::Rc / jsg::Weak line in src/rust/AGENTS.md:43 now says that once the Realm is dropped, dropped references are kept until the isolate is disposed and then released by the dispose hook. That fixes the earlier note.


📋 Code Quality: ✅ LGTM

No issues found.

  • Rc and Weak drops: each field is taken exactly once. Weak::drop handles a default-constructed Weak, which has no state.
  • Teardown in isolate_state.rs: queue locking, the order of close, and the hand-off through draining_disposed are consistent. References are released outside the mutex.
  • wrap: the isolate check runs before any wrapping.
  • FFI: every caller of wrappable_remove_strong_ref now holds the isolate lock, so calling removeStrongRef() directly does the same thing the old path did. The realm_drain_awaiting_lock rename matches across lib.rs, ffi.c++ and ffi.h.
  • Tests: the Rc::new(lock, …) updates are mechanical. The new tests in gc.rs and isolates.rs cover drops without the lock, drops on another thread, drops after the Realm is dropped and after the isolate is disposed, the Weak case, and wrapping a resource in an isolate other than the one it was created in.

⚡ Performance: ✅ LGTM

No issues found.


📝 Documentation: ✅ LGTM

No documentation issues.


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

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from d0063f1 to 66d260c Compare November 3, 2026 03:54

@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 2307a782.

This review, of 66d260cb

✅ Approved — No findings. The lock-aware release of Rc and Weak is consistent, and the code changed since the last review introduces no 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

The invariant behind unsafe impl Send for Released still holds:

  • release checks closed under the queue mutex, and close sets it under the same mutex.
  • References are released outside the mutex.
  • After disposal, draining_disposed serializes releases.

A cross-isolate wrap panics before any wrapping happens.


📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md correctly describes how queued jsg::Rc and jsg::Weak references are released, including after the Realm is dropped.


📋 Code Quality: ✅ LGTM

The Rc::new(lock, …) updates are mechanical, and every caller of the old constructors has been updated. The new tests cover drops without the lock, drops on another thread, drops after the Realm is dropped and after dispose, and a cross-isolate wrap of a resource that has no wrapper yet.


⚡ Performance: ✅ LGTM

A drop under the lock releases the reference directly and does not queue it. A drop without the lock takes one mutex lock and allocates once. The 8-byte growth per Rc and per Weak is stated in the description.


📝 Documentation: ✅ LGTM

No documentation issues in the code changed since the last review.


Reviewed commit: 66d260cb

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from 66d260c to 2307a78 Compare November 3, 2026 04:05
@nathanwhit
nathanwhit requested a review from a team as a code owner November 3, 2026 04:05
@nathanwhit
nathanwhit requested a review from edmundhung November 3, 2026 04:05

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

This review, of 2307a782

✅ Approved — No findings. The only change since the last approved review is a mechanical update to the new Rc::new(lock, …) signature in the RTTI fixture.

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 only change since the last review is the mechanical signature update in the RTTI fixture. It does not affect the invariant behind unsafe impl Send for Released.


📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md correctly describes how queued jsg::Rc and jsg::Weak references are released.


📋 Code Quality: ✅ LGTM

The Rc::new(lock, …) migration is consistent, including the new update in types/rtti-fixture/main.rs. Several pieces hold up:

  • The queue, close and dispose-drain logic in isolate_state.rs.
  • The Rc and Weak Drop paths in resource.rs.
  • The panic on a cross-isolate wrap.
  • The renamed realm_drain_awaiting_lock hook.

⚡ Performance: ✅ LGTM

The fixture update has no performance impact.


📝 Documentation: ✅ LGTM

No documentation issues in the code changed since the last review.


Reviewed commit: 2307a782

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from 2307a78 to fba94e6 Compare November 3, 2026 16:40

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

This review, of fba94e66

💬 Approved with comments — The queue-and-release logic is sound. The only finding is one stale README example that still uses the old DnsUtil::new() signature, which doesn't affect the shipped code.

Findings: 1 warning

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 #8111.

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] The `add_builtin` example in `src/rust/jsg/README.md` still calls `DnsUtil::new()`, but this pull request makes the constructor take a lock. Use `|lock| Ok(DnsUtil::new(lock))`, matching `src/rust/api/lib.rs:57`.
- **File:** src/rust/jsg/README.md:47

📝 Documentation: ⚠️ 1 warning

One README example still uses the old DnsUtil::new() signature.

Recommendation: 📝 Minor Comments

  • [WARNING] The add_builtin example in src/rust/jsg/README.md still calls DnsUtil::new(), but this pull request makes the constructor take a lock. Use |lock| Ok(DnsUtil::new(lock)), matching src/rust/api/lib.rs:57. (src/rust/jsg/README.md:47)
View full review
  • src/rust/jsg/README.md:47: the add_builtin example still calls DnsUtil::new() with no argument, but this pull request makes it take a lock (src/rust/api/lib.rs:57).

✅ All other checks passed

🔒 Security: ✅ LGTM

The invariants behind unsafe impl Send for Released hold. Before disposal, queued references are released only under the lock. After disposal, only the thread holding draining_disposed releases them, and that flag is set under the same mutex as disposed.


📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md correctly describes how queued jsg::Rc and jsg::Weak references are released.


📋 Code Quality: ✅ LGTM

The queue, close and dispose-drain logic in isolate_state.rs is consistent, and so are the Rc and Weak Drop paths in resource.rs. The Rc::new(lock, …) call-site migration is mechanical and complete.


⚡ Performance: ✅ LGTM

No performance concerns.


Reviewed commit: fba94e66

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from fba94e6 to c57d424 Compare November 3, 2026 20:22

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

This review, of c57d4244

💬 Approved with comments — The queue, close and dispose-drain logic is sound, and so are the Rc/Weak drop paths. The one open item is a stale README example for the repository's own developers, and it doesn't affect shipped code.

Findings: 1 warning

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 #8111.

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] The `add_builtin` example in `src/rust/jsg/README.md` still calls `DnsUtil::new()`, but this pull request makes the constructor take a lock. Copying the example as written fails to compile. Use `|lock| Ok(DnsUtil::new(lock))`, as `src/rust/api/lib.rs:57` does.
- **File:** src/rust/jsg/README.md:47

📝 Documentation: ⚠️ 1 warning

One README example still uses the old DnsUtil::new() signature.

Recommendation: 📝 Minor Comments

  • [WARNING] The add_builtin example in src/rust/jsg/README.md still calls DnsUtil::new(), but this pull request makes the constructor take a lock. Copying the example as written fails to compile. Use |lock| Ok(DnsUtil::new(lock)), as src/rust/api/lib.rs:57 does. (src/rust/jsg/README.md:47)
View full review

src/rust/jsg/README.md:47 still shows |_lock| Ok(DnsUtil::new()), but DnsUtil::new now takes a lock (see src/rust/api/lib.rs:57). Change the example to |lock| Ok(DnsUtil::new(lock)). The new "Dropping references" section accurately describes the queued, post-Realm and post-dispose release paths.


✅ All other checks passed

🔒 Security: ✅ LGTM

The invariants behind unsafe impl Send for Released hold:

  • Before disposal, queued references are released only under the isolate lock, by drain_awaiting_lock or close.
  • After disposal, only the thread holding draining_disposed releases them, and that flag is set under the same mutex as disposed.

📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md correctly describes how queued jsg::Rc and jsg::Weak references are released.


📋 Code Quality: ✅ LGTM

The release, drain_awaiting_lock, close, isolate_disposed and drain_disposed paths in isolate_state.rs are consistent:

  • No release runs while the drop_queues mutex is held.
  • A drop made during a drain is queued, and the drain picks it up.
  • closed is set under the mutex, so nothing pushed before close is missed.

In resource.rs:

  • Drop takes the parts out of the ManuallyDrop exactly once.
  • A weakened ref skips removeStrongRef.
  • wrap checks with Arc::ptr_eq that the resource belongs to this isolate before it looks at the wrapper.

The Rc::new(lock, …) changes are complete across the tree.


⚡ Performance: ✅ LGTM

No performance concerns. Each clone and drop adds one uncontended atomic increment or decrement on the Arc<IsolateState>, and the drop path no longer builds a RefToDelete.


Reviewed commit: c57d4244

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from c57d424 to b80229a Compare November 5, 2026 04:46

@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 2baf6dca.

This review, of b80229aa

💬 Approved with comments — The release logic is sound. The only open item is a stale README example (DnsUtil::new() without a lock) for the repository's own developers, and it doesn't affect shipped code.

Findings: 1 warning

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 #8111.

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] The `add_builtin` example in `src/rust/jsg/README.md` still calls `DnsUtil::new()`, but the constructor now takes a lock, so the example doesn't compile. Use `|lock| Ok(DnsUtil::new(lock))`, as `src/rust/api/lib.rs:57` does.
- **File:** src/rust/jsg/README.md:47

📝 Documentation: ⚠️ 1 warning

README module-registration example still calls DnsUtil::new() without a lock

Recommendation: 📝 Minor Comments

  • [WARNING] The add_builtin example in src/rust/jsg/README.md still calls DnsUtil::new(), but the constructor now takes a lock, so the example doesn't compile. Use |lock| Ok(DnsUtil::new(lock)), as src/rust/api/lib.rs:57 does. (src/rust/jsg/README.md:47)
View full review

src/rust/jsg/README.md:47 still shows |_lock| Ok(DnsUtil::new()). DnsUtil::new now takes a lock (see src/rust/api/lib.rs:57), so this example no longer compiles. Change it to |lock| Ok(DnsUtil::new(lock)).

The new "Dropping references" section accurately describes the queued, post-Realm and post-dispose release paths.


✅ All other checks passed

🔒 Security: ✅ LGTM

The opaque.rs change doesn't alter behavior. The invariants behind unsafe impl Send for Released are unchanged:

  • Before disposal, queued references are released only under the isolate lock.
  • After disposal, they are released only by the thread holding draining_disposed.

📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md correctly describes how queued jsg::Rc and jsg::Weak references are released.


📋 Code Quality: ✅ LGTM

The opaque.rs change calls remove_strong_ref() without an argument, which matches the new signature in ffi.c++, ffi.h and v8.rs.

The release, drain_awaiting_lock, close, isolate_disposed and drain_disposed paths are still consistent, and so are the Rc/Weak Drop implementations.

The Rc::new(lock, …) call-site updates are complete across the tree.


⚡ Performance: ✅ LGTM

No new cost. Each clone and drop still adds only one uncontended atomic increment or decrement on the Arc<IsolateState>.


Reviewed commit: b80229aa

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from b80229a to 2baf6dc Compare November 5, 2026 05:04

@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 2b8d4c2a.

This review, of 2baf6dca

✅ Approved — The README example from the last review now passes the lock. The changes since then are mechanical, and nothing new needs addressing.

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 invariants behind unsafe impl Send for Released still hold:

  • Before disposal, queued references are released only under the lock.
  • close and release coordinate through the queue mutex.
  • After disposal, they are released only by the thread holding draining_disposed.

📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md correctly describes how queued jsg::Rc and jsg::Weak references are released.


📋 Code Quality: ✅ LGTM

  • The release, drain_awaiting_lock, close, isolate_disposed and drain_disposed paths and the Rc/Weak Drop implementations are consistent.
  • The new cross-isolate check in wrap runs before to_js.
  • The Rc::new(lock, …) call-site updates are complete, including the traceable_gc.rs changes.

⚡ Performance: ✅ LGTM

No new cost beyond the one uncontended atomic increment or decrement on Arc<IsolateState> per clone and drop, as described in the pull request.


📝 Documentation: ✅ LGTM

src/rust/jsg/README.md:47 now shows |lock| Ok(DnsUtil::new(lock)). The "Dropping references" section accurately describes the queued, post-Realm and post-dispose release paths.


Reviewed commit: 2baf6dca

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from 2baf6dc to 2b8d4c2 Compare November 5, 2026 18: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.

Superseded by the review of ca5f2aae.

This review, of 2b8d4c2a

✅ Approved — No findings. Since the last review, the only changes are a lockfile digest, a one-line AGENTS.md note and mechanical Rc::new(lock, …) updates in three test files. The core release, queue and dispose logic still holds up.

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 invariants behind unsafe impl Send for Released still hold:

  • Before disposal, queued references are released only under the lock.
  • close and release coordinate through the queue mutex.
  • After disposal, they are released only by the thread holding draining_disposed.

📖 AGENTS.md: ✅ LGTM

The new line in src/rust/AGENTS.md accurately describes how queued jsg::Rc and jsg::Weak references are released.


📋 Code Quality: ✅ LGTM

  • Drop paths: the Rc/Weak Drop implementations agree with IsolateState::release, drain_awaiting_lock, close, isolate_disposed and drain_disposed.
  • wrappable_remove_strong_ref: it now calls removeStrongRef() directly. That is safe because every caller holds the lock: ReleasedRc::release runs only under ReleaseContext::Locked, and wrap_opaque and Function::new run under a live Lock.
  • Cross-isolate check in wrap: it runs before to_js. On failure it leaks the Rc rather than dropping it under the wrong isolate's lock.
  • Rc::new(lock, …) call sites: the updates are complete across src/rust/api, jsg-macros, jsg-bench and the tests, including the newly touched callable.rs, json.rs and rest_arguments.rs.
  • New tests: gc.rs and isolates.rs cover the queued, cross-thread, Realm-drop and post-dispose release paths.

On @​guybedford's follow-up: Rc::clone, Weak::clone, Weak::upgrade and Deref still touch non-atomic counts without requiring the lock. That is outside what this pull request sets out to fix, and making those operations take a lock is a reasonable next step.


⚡ Performance: ✅ LGTM

There is no cost beyond what the description states: one uncontended atomic increment or decrement on Arc<IsolateState> per clone and drop.


📝 Documentation: ✅ LGTM

The README examples pass the lock. The "Dropping references" section accurately describes the queued, post-Realm and post-dispose release paths.


Reviewed commit: 2b8d4c2a

@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from 2b8d4c2 to ca5f2aa Compare November 5, 2026 20:35

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

This review, of ca5f2aae

✅ Approved — No findings. The only change since the last review is a mechanical Rc::new(lock, …) update in dispose.rs, and the core release, queue and dispose logic still holds up.

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 reasoning behind unsafe impl Send for Released still holds:

  • Before disposal, queued references are released only under the lock.
  • After disposal, they are released only by the thread holding draining_disposed.

📖 AGENTS.md: ✅ LGTM

The new note in src/rust/AGENTS.md matches how queued references are released.


📋 Code Quality: ✅ LGTM

  • dispose.rs: it now uses Rc::new(lock, …) throughout. Each value is bound before set_global, which avoids a double mutable borrow of lock. The assertions are unchanged.
  • Core logic: the release, queue and dispose paths in isolate_state.rs and resource.rs are still consistent.
  • jsg-bench: the realm outlives the resources the benchmark creates, so they are released under the lock.

⚡ Performance: ✅ LGTM

There is no cost beyond what the description states.


📝 Documentation: ✅ LGTM

The README and the comments match the release behaviour.


Reviewed commit: ca5f2aae

The reference counts behind a jsg::Rc (the std::rc::Rc of the resource and
the kj::Rc of its Wrappable) and a jsg::Weak (the std::rc::Weak) are not
atomic; the isolate lock is what serializes their updates. Yet an Rc or Weak
can be dropped without the lock, for example by C++ code that owns the Rust
object holding it. Dropping an Rc then did a kj::addRef to hand
maybeDeferDestruction an Own, and dropped the std::rc::Rc and the KjRc at
once: three unsynchronized updates racing with the thread that holds the lock.
A Weak dropped its std::rc::Weak at once. And a resource that had never been
wrapped had no isolate, so maybeDeferDestruction released it at once too.

Rc and Weak now keep the IsolateState of the isolate their resource was
created in, which already queues the handles of Globals and TracedGlobals
dropped without the lock. Under the lock, a drop releases the reference at
once, as before. Without it, the drop moves the parts into the state's queue
without touching any count, and the next IsolateBase::Lock releases them:
removeStrongRef if the Rc still counts as strong, then the KjRc and the
std::rc::Rc. Realm::drop releases what is still queued before closing the
state. After that, until the isolate is disposed, the isolate still detaches
wrappers and destroys the CppgcShims that own Wrappables, and no thread can
ask whether it holds the lock of an isolate that may already be disposed, so
drops are kept until the dispose hook releases them. Those releases, and
later ones, only give back the counts: no wrapper is left to update, and an
unwrapped Wrappable may still point to the disposed isolate, since detaching
a strongly held parent's wrapper makes its references strong again, which
records the isolate in the children, and clearWrappers only clears wrapped
Wrappables. No lock serializes them, so they still go through the queue,
which one thread at a time drains. wrappable_remove_strong_ref now just
calls removeStrongRef.

To know its isolate before it is wrapped, a resource now takes it at
creation: Rc::new takes a Lock, like C++ js.alloc<T>(). Wrapping a resource
in an isolate other than the one it was created in panics, as wrapping one
that already has a wrapper in another isolate did. The jsg-bench native
lifetime and memory cases create their resources under a lock accordingly.

Each Rc is 8 bytes larger (48 bytes) for its Arc<IsolateState>, and so is
each Weak (24 bytes). In jsg-bench's native-memory case, where each Node
resource holds an Rc field, that is 256 instead of 232 bytes per resource,
since the field also moves the resource into the next malloc size class.
Clones and drops got faster despite the Arc's atomic count, since a drop no
longer adds a kj::Rc reference and builds a RefToDelete. Medians of five
processes of native/lifetime, in ns per resource created and dropped, with
--config=benchmark on an Apple M5 Pro (the benchmark now runs under an
isolate lock):

  clones   before   after
  0        35.4     33.9
  1        47.6     44.0
  16      216.0    177.8

The C++ cases measured 3-7% slower in the same runs.

This changes no API exposed to Workers.
@nathanwhit
nathanwhit force-pushed the nathanwhit/release-rc-under-lock branch from ca5f2aa to b8061a3 Compare November 5, 2026 22:02
@nathanwhit
nathanwhit enabled auto-merge November 5, 2026 22:02

@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 findings. The only change since the last review is in resource.rs, and its drop, Weak and wrap logic is consistent with the release, queue and dispose design.

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 reasoning behind unsafe impl Send for Released still holds:

  • Before disposal, queued references are released only under the lock.
  • After disposal, they are released only by the thread holding draining_disposed.

📖 AGENTS.md: ✅ LGTM

The note in src/rust/AGENTS.md matches how queued references are released.


📋 Code Quality: ✅ LGTM

No problems found:

  • API callers: every call site passes a lock to Rc::new(lock, …).
  • Rc/Weak drop paths: both hand their parts to IsolateState::release. ReleasedRc keeps the old drop order and honours the strong flag.
  • wrap: the isolate check is consistent with its documented panic and with the tests.

⚡ Performance: ✅ LGTM

There is no cost beyond the one the description states: an extra Arc increment and decrement for each clone and drop. The queue is drained at the next lock.


📝 Documentation: ✅ LGTM

The doc comments and the README match the release behaviour.


Reviewed commit: b8061a31

@nathanwhit
nathanwhit merged commit 42bab29 into main Nov 5, 2026
23 of 24 checks passed
@nathanwhit
nathanwhit deleted the nathanwhit/release-rc-under-lock branch November 5, 2026 22:47
bartlomieju added a commit that referenced this pull request Nov 7, 2026
#8210 landed squashed, with follow-ups to the two commits of it that this
branch carries, so the conflicts in the DOMException and Rust JSG files
take its final form and keep this branch's additions on top
(tryGetDOMExceptionNameAndMessage() and its Rust shim, and
Lock::throw_value()). autogate.h keeps both RUST_MEMORY_CACHE and main's
DURABLE_OBJECT_WEBSOCKET_LIMIT_KILLSWITCH.

Adapted to Rust JSG API changes on main:

- jsg::Rc::new() takes the lock (#8111).
- Traced::trace is required, so the types that hold no GC references use
  jsg_traced!, which also marks them HoldsNoGcReferences (#8196).
nathanwhit added a commit that referenced this pull request Nov 9, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (#8111).
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
and that one kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
nathanwhit added a commit that referenced this pull request Nov 9, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (#8111).
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
and that one kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
nathanwhit added a commit that referenced this pull request Nov 10, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (#8111).
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
and that one kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
nathanwhit added a commit that referenced this pull request Nov 10, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (#8111).
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
and that one kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
nathanwhit added a commit that referenced this pull request Nov 10, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (#8111).
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
and that one kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
nathanwhit added a commit that referenced this pull request Nov 10, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (#8111).
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
and that one kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
nathanwhit added a commit that referenced this pull request Nov 10, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (#8111). A drop under the lock
    releases at once, now also while the isolate is torn down, until it is about to be
    disposed: a jsg::Rc that teardown dropped used to be kept until after Dispose, and with it
    any resource reachable only through it.
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
including one reached through a jsg::Rc, that a jsg::Rc dropped under the lock during teardown
is released at once, and that a jsg_cpp::Ref kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
nathanwhit added a commit that referenced this pull request Nov 10, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (#8111). A drop under the lock
    releases at once, now also while the isolate is torn down, until it is about to be
    disposed: a jsg::Rc that teardown dropped used to be kept until after Dispose, and with it
    any resource reachable only through it.
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
including one reached through a jsg::Rc, that a jsg::Rc dropped under the lock during teardown
is released at once, and that a jsg_cpp::Ref kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
nathanwhit added a commit that referenced this pull request Nov 10, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (#8111). A drop under the lock
    releases at once, now also while the isolate is torn down, until it is about to be
    disposed: a jsg::Rc that teardown dropped used to be kept until after Dispose, and with it
    any resource reachable only through it.
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
including one reached through a jsg::Rc, that a jsg::Rc dropped under the lock during teardown
is released at once, and that a jsg_cpp::Ref kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
nathanwhit added a commit that referenced this pull request Nov 10, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (#8111). A drop under the lock
    releases at once, now also while the isolate is torn down, until it is about to be
    disposed: a jsg::Rc that teardown dropped used to be kept until after Dispose, and with it
    any resource reachable only through it.
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
including one reached through a jsg::Rc, that a jsg::Rc dropped under the lock during teardown
is released at once, and that a jsg_cpp::Ref kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
meefs pushed a commit to meefs/workerd that referenced this pull request Nov 11, 2026
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and
its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads
from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced
and cloned without the lock, so a thread that holds one but not the lock can read the resource or
change its counts while the lock's holder does. This change makes every reference reach that
state only under its isolate's lock.

- jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the
  resource's isolate, which makes them Send, for R: Send:
  - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade,
    Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every
    build, that the lock is of the resource's isolate and that its Realm is alive: holding one
    isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get()
    bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a
    'static future.
  - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit
    (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another
    isolate leaves it as it is, so a reference that one isolate's resource holds to another's
    leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against
    such a visit.
  - A drop without the lock is queued without touching a count (cloudflare#8111). A drop under the lock
    releases at once, now also while the isolate is torn down, until it is about to be
    disposed: a jsg::Rc that teardown dropped used to be kept until after Dispose, and with it
    any resource reachable only through it.
  - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock.
- jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its
  isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and
  detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its
  constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref
  becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap
  snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends
  the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop
  no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with
  or without the lock: two references to such an object, dropped on two threads, raced on its
  count. While the isolate is torn down, a drop under the lock still drops the value then, until
  the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold
  are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global
  would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose,
  after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past
  teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its
  isolate at teardown") makes safe.
- v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count
  without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++
  reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and
  resolve_method_receiver.

The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc),
and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker).

await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it.

Resource state itself can still be anything, std::rc::Rc included; the next commit requires it
to be Send.

Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R
from get() captured in a 'static future, and one that accepts a resource with a
jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread.
jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another
isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another
isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with
no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown
destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed,
including one reached through a jsg::Rc, that a jsg::Rc dropped under the lock during teardown
is released at once, and that a jsg_cpp::Ref kept past teardown can still be dropped. Compile tests check that WrappableRc and
the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read
it inside one.

src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md
describes the new API.
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