Skip to content

fix: release onRpcBroken callbacks when a remote stub is disposed - #286

Open
ndisidore wants to merge 7 commits into
mainfrom
fix/on-rpc-broken-dispose
Open

ndisidore wants to merge 7 commits into
mainfrom
fix/on-rpc-broken-dispose

Conversation

@ndisidore

@ndisidore ndisidore commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

onRpcBroken() callbacks were never released. A session kept every callback registered on a remote stub until the connection ended, then called all of them, including those for stubs the app had disposed long before. On a long-lived connection that keeps making and dropping capabilities, that is a leak plus a burst of stale callbacks at disconnect. Disposing a remote stub and all its dups now unregisters its callbacks.

Closes #210.

  • Unregister on disposal, don't call. First half of the alternative floated on Accept an AbortSignal in onRpcBroken and cleanup registrations when stubs are disposed #250 (dispose the stub to unregister its callback), the behavior proposed on onRpcBroken should return a Disposable so registrations can be undone #234 for a stub fully disposed while the session is healthy, and E's Ref.whenBroken: a reference collected before a partition doesn't inform its reactor.
  • Main stub is the exception. Disposing it ends the session, which calls every callback.
  • Tracking is per import, not per handle. Callbacks go away once the stub and every dup are disposed; disposing one dup unregisters nothing. So the other half of the Accept an AbortSignal in onRpcBroken and cleanup registrations when stubs are disposed #250 idea, registering on a dup() and disposing it to drop one callback, does not work with this PR. That needs per-handle tracking or onRpcBroken should return a Disposable so registrations can be undone #234's handle.
  • Registrations are {callback, index} records shared by the session and the owning import. Deleting slots on disposal, as the issue sketches, misses callbacks registered on a promise: resolve() moves them to the resolved stub but keeps the original slot so they still fire in registration order, and the new owner needs that slot's index.
  • Nothing unregisters once an abort starts (session.aborting, set before any app code runs). Otherwise a broken-connection handler (onSendError, the transport's abort(), or an earlier callback) that disposes child stubs would drop their callbacks before they fire. Callbacks registered from onSendError or the transport's abort() still fire, as on main. The session drops the whole list after calling it.
  • User-visible: a stub received as a call parameter is disposed when the call completes, so its callback no longer fires at disconnect unless the stub was dup()ed. Covered in the changeset, the disposal and stubs docs, and a test.
  • Docs say to register on the stub you keep: a dup() of an un-awaited promise is a separate import and doesn't carry the promise's callbacks. Sessions guide no longer says onRpcBroken "cannot be unregistered".
  • No single-callback unregister; that's onRpcBroken should return a Disposable so registrations can be undone #234. It may reshape the records and the resolve() handoff, but the behavior and tests here hold under either design proposed there.
  • Not touched: callbacks registered from inside another callback during an abort, and resolve() reentrancy. Both pre-existing.
  • Ran the Node and workerd projects locally. Browser projects not run locally.

Final disposal of an unresolved import now deletes its registrations from
the session's callback list, so they are no longer retained for the
session's lifetime and called at teardown.

Registrations become {callback, index} records shared by the session and
the owning import, so a callback moved by a same-session resolve() keeps
its original slot and stays removable by its new owner. Session abort
detaches the list before running app code, so a callback that disposes
another stub cannot unregister callbacks that have yet to fire.

Closes #210
@changeset-bot

changeset-bot Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: a19061a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
capnweb Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@pkg-pr-new

pkg-pr-new Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/cloudflare/capnweb@286
npm i https://pkg.pr.new/cloudflare/capnweb/capnweb-validate@286

commit: a19061a

@ask-bonk

ask-bonk Bot commented Oct 23, 2026

Copy link
Copy Markdown

LGTM

github run

@clanky-the-clanker

clanky-the-clanker Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

This pull request's reviews are posted as pull request reviews: see the review of 25731264.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

🚀 Deploying Preview to Cloudflare 🚀

Preview URL: https://fix-on-rpc-broken-dispose.pr.capnweb.com (commit a19061a)

This URL reflects your latest Preview deployment

Preview Deployments by commit

Status Deployment URL Commit Updated (UTC) See this deployment's details
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://24a6af2b.pr.capnweb.com a19061a 2026-11-18T21:49:30.337Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://94bbce3c.pr.capnweb.com 3655f16 2026-11-09T15:27:08.352Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://50345b00.pr.capnweb.com 2573126 2026-11-02T18:30:39.063Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://ace874b2.pr.capnweb.com 624e13a 2026-10-23T16:31:25.895Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://3fcf9d94.pr.capnweb.com 1185d55 2026-10-23T16:23:12.089Z Visit the dashboard ↗

@srikrsna srikrsna left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think the following behavior is worth documenting with a test:

it("callbacks are retained by dups", async () => {
  let harness = new TestHarness(new TestTarget());
  let counter = await harness.stub.makeCounter(0);
  let calls = 0;
  counter.onRpcBroken(() => { ++calls; });
  let dup = counter.dup();
  counter[Symbol.dispose]();

  harness.clientTransport.forceReceiveError(new Error("test disconnect"));
  await pumpMicrotasks();
  expect(calls).toBe(1);
});

Comment thread src/rpc.ts
Comment on lines +236 to +240
// here. So, let's move the newly-added registration into the original's slot, updating
// its index so that its new owner can still unregister it.
// TODO: This is quite hacky, think about whether this is really the right answer.
moved.index = index;
this.session.onBrokenCallbacks[index] = moved;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Just a note, nothing to change but I think this has become even more hacky now as it depends on the newly created registration (the index update) in a different import hook along side the session.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, it now writes into the new owner's record on top of the existing endIndex check. I left it since it's the same TODO, and this handoff is what #234 has to revisit anyway: a handle created before a promise resolves needs to keep working after its callback moves. That seems like the right place to decide what this should look like.

@ndisidore
ndisidore requested a review from srikrsna November 2, 2026 18:30

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 3655f163.

This review, of 25731264

💬 Approved with comments — The fix is correct and tested, and the new test covers dup retention as requested in the discussion. One INFO note remains about stale registration indexes during abort. It can't make any callback fire wrongly.

Findings: 1 info

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


📋 Code Quality: 💬 1 info

The fix is correct. The new dup test covers the retention behaviour requested in the discussion. One informational note about the abort window remains.

Recommendation: 💬 Optional Nits

  • [INFO] During abort, imports keep registration indexes that point into the detached callback array, while dispose() and resolve() write to the fresh one. A stale index could delete an onRpcBroken registered during the abort window. No callback fires wrongly, because the fresh array is never iterated. (src/rpc.ts:272)
View full review

Stale indexes during abort (INFO, unchanged since the last review)

  • src/rpc.ts:940-941: abort() swaps onBrokenCallbacks for a fresh [] before any app code runs.
  • Imports keep their onBrokenRegistrations until the final abort loop, so their index values still point into the detached array.
  • If a stub is disposed in that window, dispose() at src/rpc.ts:272 deletes an entry from the fresh array. If app code registered a new onRpcBroken in the same window, that delete could remove the unrelated registration. resolve() at src/rpc.ts:240-244 can make the same kind of write.
  • The fresh array is never iterated after an abort, so no callback ever fires wrongly.
  • The description says registration during abort was left alone on purpose.
  • A cheap guard, if you want one: skip the delete when session.abortReason !== undefined.

Tests

The new test callbacks are retained by dups (__tests__/index.test.ts:2434) pins down the retention behaviour suggested in the discussion. Unregistering on full disposal is already covered by does not call back for capabilities disposed before the connection is lost.

resolve() handoff

The discussion on the resolve() handoff (src/rpc.ts:240) is noted. Writing into the new owner's record there is an existing TODO, and #234 is the natural place to rework it.


✅ All other checks passed

🚀 Release: ✅ LGTM

The changeset is present and appropriate for a bug fix. Risk: low.


🔒 Security: ✅ LGTM

No security concerns in this change.


📖 AGENTS.md: ✅ LGTM

No agent instruction files are affected.


⚡ Performance: ✅ LGTM

No performance concerns. Disposal and abort do O(1) work per registration, and disposed stubs no longer keep their callbacks alive for the lifetime of the session.


📝 Documentation: ✅ LGTM

The disposal and sessions guides accurately describe the new behaviour: callbacks are unregistered when a stub is disposed.


Reviewed commit: 25731264

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of a19061a6.

This review, of 3655f163

✅ Approved — The fix is correct and well tested. The new commits add tests for dup retention and for parameter stubs, plus accurate docs, and they introduce no issues. One earlier informational note about stale indexes during abort remains open as the author's choice.

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


✅ All checks passed

🚀 Release: ✅ LGTM

The changeset is present and appropriate for a bug fix. Risk: low.


🔒 Security: ✅ LGTM

No security concerns in this change.


📖 AGENTS.md: ✅ LGTM

No agent instruction files are affected.


📋 Code Quality: ✅ LGTM

Since the last review, this pull request adds tests and updates the docs. I found no problems in them.

  • __tests__/index.test.ts covers four behaviours, and all four match the code in src/rpc.ts:
    • callbacks are unregistered once the stub is fully disposed, including a callback that resolve() moved from a promise to a stub;
    • callbacks are kept while a dup is alive;
    • a callback still fires when an earlier callback has already disposed its stub, because abort() detaches the callback list first;
    • a callback on a parameter stub fires only if a dup outlives the call.
  • disposal.mdx, stubs.mdx and sessions.mdx describe what the code does.

One earlier note, about stale registration indexes during abort, is still open. Its code has not changed and nobody has replied to it, so it is left to the author.


⚡ Performance: ✅ LGTM

No performance concerns.

  • Disposal, resolve() and abort each do O(1) work per registration.
  • Disposed stubs no longer keep their callbacks alive for the life of the session.
  • Deleting entries leaves holes in the sparse callback array. Those holes cost far less memory than the callbacks that used to be retained.

📝 Documentation: ✅ LGTM

The changeset and the disposal, stubs and sessions docs accurately describe the new behaviour. This includes the note about parameter stubs and the advice to register onRpcBroken() on the stub you keep.


Reviewed commit: 3655f163

abort() swapped in a fresh callback list before running app code, so a
callback registered from onSendError or the transport's abort() landed in
a list that was never called. On main those callbacks fire.

Keep one list. abort() sets `aborting` before any app code runs, and
disposing an import skips unregistering while it is set, so a handler
that disposes stubs still cannot drop callbacks that have yet to fire.
The list is cleared once every callback has been called.

This also removes the stale-index hazard of the swap, where disposing an
import registered before the abort deleted a slot in the fresh list.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved — The fix is correct and well tested. The new single-list abort handling keeps callbacks that are registered or disposed during abort, and the docs and changeset accurately describe the behaviour.

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


✅ All checks passed

🚀 Release: ✅ LGTM

The changeset specifies a patch bump and documents the change in when onRpcBroken() callbacks fire for disposed remote stubs. Tests cover disposal, dups, parameter stubs and abort.


🔒 Security: ✅ LGTM

No security concerns in this change.


📖 AGENTS.md: ✅ LGTM

No agent instruction files are affected.


📋 Code Quality: ✅ LGTM

  • resolve() handoff: Reusing the moved record and setting its index keeps the new owner consistent with the session list. The old owner's registrations are cleared, so nothing is deleted twice.
  • Unregister on dispose: This happens only on the final disposal of an unresolved import, and only when the session is not aborting.
  • Abort: aborting is set before any app code runs. The callback loop skips deleted slots, and the list is released after the loop.
  • Tests: They cover unregistering after disposal, dup retention, parameter stubs, callbacks registered during abort, and a disposal made from inside an earlier callback.

One earlier note, about stale indexes during abort, is still open as the author's choice.


⚡ Performance: ✅ LGTM

No performance concerns. Disposed stubs no longer keep their callbacks alive for the life of the session.


📝 Documentation: ✅ LGTM

The changeset and the disposal, stubs and sessions docs accurately describe the new behaviour.


Reviewed commit: a19061a6

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

onRpcBroken callbacks are retained for the session's lifetime after their import is disposed (and fire at teardown)

3 participants