Repository navigation
Release Rust jsg::Rc and jsg::Weak under their isolate's lock - #8111
Conversation
There was a problem hiding this comment.
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/TracedGlobalwithout the lock, add a short pointer to the newRc/Weakrelease rules insrc/rust/jsg/README.md, including thatRc::newtakes a lock. (src/rust/AGENTS.md:42)
View full review
src/rust/AGENTS.mddescribes what happens when aGlobalorTracedGlobalis dropped without the lock. It doesn't mention thatRcandWeaknow follow similar rules, or thatRc::newtakes the resource's lock. A short pointer to the new section insrc/rust/jsg/README.mdwould 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_lockandisolate_disposedbridge 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_lockandisolate_disposedbridge declarations insrc/rust/jsg/lib.rswere 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_lockanddrain_disposednever drop aReleasedwhile the queue mutex is held, so a release that triggers further drops cannot deadlock.closedrainsreleased_awaiting_lockagain after it setsclosed, so a push that races withcloseisn't lost.isolate_disposedsetsdraining_disposedtogether withdisposed, anddrain_disposedclears 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.
RcandWeakdrops (src/rust/jsg/resource.rs)Rc::droptakes eachManuallyDropfield exactly once.removeStrongRefis skipped when tracing has weakened the reference, and in theDisposedcontext.Weak::drophandles a missing state.- The new
Arc::ptr_eqcheck inwrapruns before any wrapping happens.
- FFI. The new
wrappable_remove_strong_refsignature matches acrossffi.c++,ffi.handv8.rs. - Call sites. The
Rc::new(lock, …)migration insrc/rust/api,jsg-macros, the tests and the bench is consistent. The new cross-isolatewrappanic 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 anRcnow needsjsg::Rc::new(lock, …). Add alock: &mut Lockparameter to the example. (src/rust/jsg-macros/README.md:111)
View full review
src/rust/jsg-macros/README.md:111: the staticcreatefactory example returnsjsg::Rc<Self>but takes no lock. Constructing anRcnow needsjsg::Rc::new(lock, resource), so add alock: &mut Lockparameter to the example, asDnsUtil::newinsrc/rust/api/dns.rsnow 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_lockorclose. - After disposal, they're released only by the single thread that holds
draining_disposed.
- Queue checks.
releasechecksis_closed()under the same mutex thatcloseholds when it setsclosed. A reference queued while the state is open is therefore always released by the next lock or byclose. - 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_locktakes the mutex once perIsolateBase::Lockand swaps the vectors out. - Size. The extra 8 bytes per
RcandWeak, plus the uncontended atomic increment and decrement on theArc, match the costs measured in the description.
Reviewed commit: c504811b
c504811 to
acc4b77
Compare
There was a problem hiding this comment.
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_lockandisolate_disposedbridge 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_lockandisolate_disposedbridge declarations insrc/rust/jsg/lib.rsstill need rewrapping. Line 111 is 104 characters long.
What I checked and found correct
RcandWeakdrops: 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_lockordrain_disposed. - FFI: the
realm_drain_awaiting_lockrename and the newwrappable_remove_strong_refsignature match betweenlib.rsandffi.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_lockorclose. - After disposal, only the thread holding
draining_disposedreleases them, so two releases never overlap.
release: it checksis_closed()under the same mutexcloseholds when it setsclosed, 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_refsignature matches acrossffi.c++,ffi.handv8.rs.
📖 AGENTS.md: ✅ LGTM
src/rust/AGENTS.md:42describes what happens when aGlobalorTracedGlobalis dropped without the lock.- It doesn't mention that
RcandWeaknow follow similar rules, or thatRc::newtakes a lock. - A short pointer to the new section on dropping references in
src/rust/jsg/README.mdwould 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
RcandWeak, 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 staticcreateexample returnsjsg::Rc<Self>but takes no lock.Rc::newnow requires a lock, so add alock: &mut Lockparameter, asDnsUtil::newinsrc/rust/api/dns.rsnow has.
Reviewed commit: acc4b776
acc4b77 to
c850b4c
Compare
There was a problem hiding this comment.
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_calldoc 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_lockandisolate_disposedbridge 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 thetermination_survives_calldoc comment is 139 characters long. The lines around it wrap at about 100.src/rust/jsg/lib.rs:111: the doc comments on therealm_drain_awaiting_lockandisolate_disposedbridge declarations still need rewrapping. Line 111 is 104 characters long.
What I checked and found correct
- Queue mutex:
release,closeanddrain_awaiting_locknever hold it while releasing a reference, so a release that drops more references cannot deadlock. - No lost pushes:
closetakes the queue a second time after it setsclosed. Thedraining_disposedhandoff holds under the mutex, anddrain_disposedloops until it picks up pushes that arrive while it drains. RcandWeakdrops: each field is taken exactly once. A default-constructedWeakhas no state and is skipped.- State propagation:
new,clone,FromJSandWeak::upgradeall build throughfrom_parts, so everyRccarries its isolate's state. wrap: the isolate-identity check runs before any wrapping.- FFI: the
realm_drain_awaiting_lockrename and the one-argumentwrappable_remove_strong_refmatch acrosslib.rs,ffi.c++,ffi.handv8.rs. - Tests: the
Rc::new(lock, …)migration is mechanical. The new lifetime tests ingc.rsandisolates.rscover 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_disposedreleases 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
Rcclone and drop matches the benchmarks in the description.
📝 Documentation: ✅ LGTM
No new documentation issues.
Reviewed commit: c850b4ca
c850b4c to
4aea4f8
Compare
There was a problem hiding this comment.
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::Weakguidance leaves out what happens to queued references after theRealmis 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 nextIsolateBase::Lock. That is not true after theRealmis dropped: from then on, queued references are kept until the isolate is disposed. TheGlobal/TracedGloballine 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_calldoc comment intermination.rsand therealm_drain_awaiting_lock/isolate_disposeddoc comments injsg/lib.rsare now wrapped at 100 columns. - Rust
RcandWeakdrops: each field is still taken exactly once. wrap: the isolate check still runs before any wrapping.- FFI: the
realm_drain_awaiting_lockrename and the one-argumentwrappable_remove_strong_refmatch acrosslib.rs,ffi.c++,ffi.handv8.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
Rcclone and drop is the cost the description reports with benchmarks.
📝 Documentation: ✅ LGTM
No new documentation issues.
Reviewed commit: 4aea4f8d
4aea4f8 to
2bdda02
Compare
There was a problem hiding this comment.
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::Weakline leaves out that, once theRealmis dropped, queued references are kept until the isolate is disposed. (src/rust/AGENTS.md:43)
View full review
src/rust/AGENTS.md:43says a drop without the lock is released at the nextIsolateBase::Lock. That stops being true once theRealmis dropped: after that, queued references are kept until the isolate is disposed. TheGlobal/TracedGloballine 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.rsgets the same mechanicalRc::new(lock, …)update as the other tests. RcandWeakdrops: each field is taken exactly once.Weak::drophandles a default-constructedWeak, which has no state.IsolateState::release:- The closed check and
closeuse the same mutex, so a reference queued while the state is open can't be missed. drain_awaiting_lockanddrain_disposedrelease references outside the mutex, so a release that drops further references can't deadlock.
- The closed check and
wrap: the isolate check runs before any wrapping.- FFI: the
realm_drain_awaiting_lockrename and the one-argumentwrappable_remove_strong_refmatch acrosslib.rs,ffi.c++,ffi.handv8.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
2bdda02 to
cc800f3
Compare
There was a problem hiding this comment.
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.
RcandWeakdrops: each field is taken exactly once.Weak::drophandles a default-constructedWeak, which has no state.- Teardown in
isolate_state.rs: queue locking, the order ofclose, and the hand-off throughdraining_disposedare consistent. References are released outside the mutex. wrap: the isolate check runs before any wrapping.- FFI: every caller of
wrappable_remove_strong_refnow holds the isolate lock, so callingremoveStrongRef()directly does the same thing the old path did. Therealm_drain_awaiting_lockrename matches acrosslib.rs,ffi.c++andffi.h. - Tests: the
Rc::new(lock, …)updates are mechanical. The new tests ingc.rsandisolates.rscover drops without the lock, drops on another thread, drops after theRealmis dropped and after the isolate is disposed, theWeakcase, 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
left a comment
There was a problem hiding this comment.
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
cc800f3 to
d0063f1
Compare
There was a problem hiding this comment.
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.
RcandWeakdrops: each field is taken exactly once.Weak::drophandles a default-constructedWeak, which has no state.- Teardown in
isolate_state.rs: queue locking, the order ofclose, and the hand-off throughdraining_disposedare consistent. References are released outside the mutex. wrap: the isolate check runs before any wrapping.- FFI: every caller of
wrappable_remove_strong_refnow holds the isolate lock, so callingremoveStrongRef()directly does the same thing the old path did. Therealm_drain_awaiting_lockrename matches acrosslib.rs,ffi.c++andffi.h. - Tests: the
Rc::new(lock, …)updates are mechanical. The new tests ingc.rsandisolates.rscover drops without the lock, drops on another thread, drops after theRealmis dropped and after the isolate is disposed, theWeakcase, 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)
d0063f1 to
66d260c
Compare
There was a problem hiding this comment.
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:
releasechecksclosedunder the queue mutex, andclosesets it under the same mutex.- References are released outside the mutex.
- After disposal,
draining_disposedserializes 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
66d260c to
2307a78
Compare
There was a problem hiding this comment.
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
RcandWeakDroppaths inresource.rs. - The panic on a cross-isolate
wrap. - The renamed
realm_drain_awaiting_lockhook.
⚡ 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
2307a78 to
fba94e6
Compare
There was a problem hiding this comment.
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_builtinexample insrc/rust/jsg/README.mdstill callsDnsUtil::new(), but this pull request makes the constructor take a lock. Use|lock| Ok(DnsUtil::new(lock)), matchingsrc/rust/api/lib.rs:57. (src/rust/jsg/README.md:47)
View full review
src/rust/jsg/README.md:47: theadd_builtinexample still callsDnsUtil::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
fba94e6 to
c57d424
Compare
There was a problem hiding this comment.
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_builtinexample insrc/rust/jsg/README.mdstill callsDnsUtil::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)), assrc/rust/api/lib.rs:57does. (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_lockorclose. - After disposal, only the thread holding
draining_disposedreleases them, and that flag is set under the same mutex asdisposed.
📖 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_queuesmutex is held. - A drop made during a drain is queued, and the drain picks it up.
closedis set under the mutex, so nothing pushed beforecloseis missed.
In resource.rs:
Droptakes the parts out of theManuallyDropexactly once.- A weakened ref skips
removeStrongRef. wrapchecks withArc::ptr_eqthat 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
c57d424 to
b80229a
Compare
There was a problem hiding this comment.
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_builtinexample insrc/rust/jsg/README.mdstill callsDnsUtil::new(), but the constructor now takes a lock, so the example doesn't compile. Use|lock| Ok(DnsUtil::new(lock)), assrc/rust/api/lib.rs:57does. (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
b80229a to
2baf6dc
Compare
There was a problem hiding this comment.
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.
closeandreleasecoordinate 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_disposedanddrain_disposedpaths and theRc/WeakDropimplementations are consistent. - The new cross-isolate check in
wrapruns beforeto_js. - The
Rc::new(lock, …)call-site updates are complete, including thetraceable_gc.rschanges.
⚡ 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
2baf6dc to
2b8d4c2
Compare
There was a problem hiding this comment.
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.
closeandreleasecoordinate 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/WeakDropimplementations agree withIsolateState::release,drain_awaiting_lock,close,isolate_disposedanddrain_disposed. wrappable_remove_strong_ref: it now callsremoveStrongRef()directly. That is safe because every caller holds the lock:ReleasedRc::releaseruns only underReleaseContext::Locked, andwrap_opaqueandFunction::newrun under a liveLock.- Cross-isolate check in
wrap: it runs beforeto_js. On failure it leaks theRcrather than dropping it under the wrong isolate's lock. Rc::new(lock, …)call sites: the updates are complete acrosssrc/rust/api,jsg-macros,jsg-benchand the tests, including the newly touchedcallable.rs,json.rsandrest_arguments.rs.- New tests:
gc.rsandisolates.rscover 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
2b8d4c2 to
ca5f2aa
Compare
There was a problem hiding this comment.
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 usesRc::new(lock, …)throughout. Each value is bound beforeset_global, which avoids a double mutable borrow oflock. The assertions are unchanged.- Core logic: the release, queue and dispose paths in
isolate_state.rsandresource.rsare 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.
ca5f2aa to
b8061a3
Compare
There was a problem hiding this comment.
✅ 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/Weakdrop paths: both hand their parts toIsolateState::release.ReleasedRckeeps the old drop order and honours thestrongflag.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
#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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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'sstd::rc::Rc<R>and itsWrappable'skj::Rc(KjRc).jsg::Weak<R>holds astd::rc::Weak<R>.An
RcorWeakcan 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 theremoveStrongRefcall, throughmaybeDeferDestruction, and only if theWrappablehad been wrapped. TheKjRcandstd::rc::Rccounts 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
RcandWeaknow keep theIsolateStateof the isolate their resource was created in. That's the stateGlobalandTracedGlobalalready use to queue handles dropped without the lock.removeStrongRefif theRcstill counts as strong, then theKjRcandstd::rc::Rcdrop.IsolateBase::Lockreleases 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::Refwaiting in the deferred destruction queue.Weakqueues itsstd::rc::Weakthe same way. It keeps its own copy of the state because its target may already be gone, as C++jsg::WeakRefdoes withIsolateLiveness.Realm::dropreleases anything still queued before it closes the state. After that, every drop is kept until the isolate is disposed, sincedropWrappersandDisposestill 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 unwrappedWrappablecan 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_refnow just callsremoveStrongRef(). Rust no longer goes throughmaybeDeferDestruction.API changes
Rc::newnow takes aLock: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::newandInspectorModule::newinsrc/rust/apitake a lock accordingly.jsg-macroscall sites already had one.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.Cost
Each
Rcgrows from 40 to 48 bytes and eachWeakfrom 16 to 24, for theArc<IsolateState>. EveryRcclone and drop also does one uncontended atomic increment and decrement on thatArc.jsg-bench, built with--config=benchmarkon 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 resourcenative-memory, bytes per resourcekj::addRefor builds aRefToDelete.Reviewer notes
src/rust/jsg/isolate_state.rs(release,drain_awaiting_lock,close,isolate_disposed,drain_disposed,ReleaseContext) andsrc/rust/jsg/resource.rs(Rc/WeakDrop,ReleasedRc,wrap).Rc::new(lock, …)change in tests.Releasedhas anunsafe impl Send. Its parts are!Sendonly because their counts aren't atomic. Queuing moves them without touching any count. Before disposal they're released under the lock, bydrain_awaiting_lockorclose. After disposal they're released only by the thread holdingdraining_disposed, which is set together withdisposed, so two releases never overlap.realm_reset_globals_awaiting_locktorealm_drain_awaiting_lock, since it now releases references too.