Registry Mirror
Skip to content

Conversation

@ryanofsky

@ryanofsky ryanofsky commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Use reference counting to manage Connection object lifetimes. This implements an old idea from #176 (comment) and has two benefits:

  • Makes it possible to wait for objects associated with a Connection to be freed, to support unclean shutdowns better. This was implemented in base PR proxy-io: Add Connection::disconnect() and a tracker to wait for in-flight calls #335 for server objects, and this PR extends it to treat client and server objects symmetrically.
  • Allows dropping the cleanup handlers ProxyClient objects register with Connections, so Connection objects no longer need to store lists of ProxyClient objects and can just use use counts instead.

Status (2026-11-23)

This is a draft. It waits on #335 (and #361 below it), and its direction is being reconsidered. It is an internal cleanup that makes Connection objects reference counted, and it doesn't require changes in Bitcoin Core beyond bitcoin/bitcoin#35932. enochaz's review pointed out that reference counting creates a cycle, so dropping a connected Connection without calling disconnect() leaks it. Options being considered: making connection owners disconnect automatically when they let go, reference counting only from ProxyClient objects (which avoids the cycle), or leaving this until after #335 merges.


This is based on #335. The non-base commits are:

@DrahtBot

DrahtBot commented Aug 7, 2026 •

Copy link
Copy Markdown

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK enochaz

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #405 (proxy: Fix deadlocks and a data race in server methods running on worker threads by ryanofsky)
  • #342 (Allow request cancellation for wrapped C++ methods by nullfail)
  • #335 (proxy-io: Add Connection::disconnect() and a tracker to wait for in-flight calls by ryanofsky)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • include/mp/proxy-types.h: std::make_unique<ProxyClient<Interface>>(input.get(), server_context.proxy_server.m_context.connection.get(), false)

2026-11-24 05:01:47

@ryanofsky

ryanofsky commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

Rebased a067599 -> 5187179 (pr/notrack.1 -> pr/notrack.2, compare) on top of #335 pr/keepconn.4 due to conflict with #298

Rebased 5187179 -> 6c7f1bf (pr/notrack.2 -> pr/notrack.3, compare) with various improvements in base PRs.

Rebased 6c7f1bf -> 4874ee0 (pr/notrack.3 -> pr/notrack.4, compare) due to conflicts with #363, on top of updated pr/keepconn and pr/connserve, removing <list> and <capnp/rpc-twoparty.h> includes that IWYU flags as unused after this PR's changes

ryanofsky added a commit to ryanofsky/libmultiprocess that referenced this pull request Sep 4, 2026
Add accessors to avoid libmultiprocess applications needing to create
Connection objects directly or access their internals. It adds an
EventLoop::incomingConnections method and a ServeStream overload that
accepts a shared interface pointer instead a reference.

This is just a refactoring that does not change behavior. It allows
Bitcoin Core code to be simplified and to avoiding needing to change
again with upcoming PRs such as bitcoin-core#336 which the change the way Connection
objects work.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ryanofsky added a commit that referenced this pull request Nov 4, 2026
…in tests

326ccfc test: simplify TestSetup using ServeStream/ConnectStream (Ryan Ofsky)
e468765 proxy-io: add destroy_connection parameter to ServeStream and ConnectStream (Ryan Ofsky)
01808ba proxy-io: let ServeStream take ownership of init object (Ryan Ofsky)
034e0d2 proxy-io: add EventLoop::incomingConnections() (Ryan Ofsky)

Pull request description:

  Generalize `ConnectStream` and `ServeStream` functions to simplify test setup in libmultiprocess and bitcoin core code (in followup ryanofsky/bitcoin@990f259). Also add an `incomingConnections` accessor so Bitcoin Core code does not need to directly access the incoming connections list to disconnect clients.

  These changes help with #336 by getting rid of external code that would need to change with its changes to the `Connection` representation.

Top commit has no ACKs.

Tree-SHA512: 3b7fe09a7e66cc7c5eec4401bebf0007bccf0a856b7f3a3b81b814040603dc172fdc1e93e4bd2507cda6c711155611195f4e588f49ed79af71333b60a99ec45f

@enochaz enochaz left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Concept ACK, did an initial look through the changes.

This implements the connection refcounting idea from #176 (comment). Connections are now held by a shared pointer, and every proxy object keeps a reference to its connection. So the connection can't be deleted while something is still using it.

Off the bat, I like that the connection pointer in ProxyContext can't dangle anymore, and that client objects don't need to register cleanup callbacks with the connection. Clients and servers are also handled the same way now, and so are local and remote disconnects. It also fixes the case I mentioned in #335 (comment), since the client that owns the connection now frees it when it is destroyed.

In that comment I suggested keeping only the tracker and deleting the connection as usual. After going through the changes, I see that keeping disconnected connections alive is on purpose. Since proxy objects now share the connection, a separate tracker isn't really needed, so I'm fine with this approach.

One thing I'm a bit worried about is that the disconnect method now always has to be called before a connection is dropped. The comment on Connection::make() says:

//! Note: dropping shared_ptr references alone will not usually destroy a
//! connected Connection, because connected state holds capability
//! references to server objects which themselves hold references back to
//! the Connection (m_rpc_system exports -> ProxyServer objects ->
//! ProxyContext::connection). disconnect() breaks these cycles, so every
//! code path that tears down a connection must call it; after that, the
//! object is destroyed when the last reference is dropped.

If a caller forgets to call it, nothing crashes, but the connection is never freed and keeps the event loop running, so shutdown hangs. Wouldn't that be harder to debug than a crash? The listen test already had to add a disconnect call before removing the connection from the list. I think disconnectIncoming in bitcoin/bitcoin#35932 might have a similar problem, since it disconnects the connections but never removes them from the incoming connections list.

Could the owner of the connection disconnect it automatically when it lets go of it? Then removing a connection from the list would be enough, and calling disconnect directly would only be needed to disconnect early. If that's too much for this PR, maybe a debug assert that catches a connection being dropped from the list while it is still connected?

Left a few inline comments as well.

Comment thread include/mp/proxy-io.h
//! Tracker for live ProxyServer objects associated with this connection,
//! used by waitDrained().
std::shared_ptr<ServerObjectTracker> m_server_objects{std::make_shared<ServerObjectTracker>()};
ServerObjectTracker m_server_objects;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In commit 0ef5407: proxy-io: make server object tracker a plain Connection member

nit: This member looks unused now. This commit also makes Connection inherit from ServerObjectTracker, and addServerObject, removeServerObject and tracker all go through the base class, so I think it can be removed.

The commit title says "plain Connection member", which also doesn't match the inheritance?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

re: #336 (comment)

This member looks unused now.

Thanks, good catch. This commit ended up half one approach and half the other. In the latest push it does what the title says: Connection holds the tracker as a plain m_server_objects member and no longer inherits from ServerObjectTracker.

Comment thread include/mp/proxy-io.h Outdated
//! no server call body is still executing (see ServerObjectTracker).
using Tracker = std::shared_ptr<ServerObjectTracker>;
Tracker tracker() { return m_server_objects; }
Tracker tracker() { return shared_from_this(); }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In commit 0ef5407: proxy-io: make server object tracker a plain Connection member

Since tracker now returns the Connection itself, is the Tracker type still needed?

I think callers could just hold the Connection shared pointer and call waitDrained on it directly. Or is it kept for compatibility with bitcoin/bitcoin#35932?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

re: #336 (comment)

is the Tracker type still needed?

It's still used, but tracker() is gone. After your #335 comments, disconnect() returns the tracker, and that is how callers wait (#335 (comment)). In this PR the tracker is now an aliasing shared_ptr pointing at the plain m_server_objects member and sharing ownership of the Connection, so this PR doesn't change the API #335 adds, and bitcoin/bitcoin#35932 works the same with or without it.

Comment thread include/mp/proxy-io.h
//! last reference to the EventLoop, and exit after the last disconnect.
template <typename F>
void onDisconnect(F&& f)
void afterDisconnect(F&& f)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In commit ef84b20: proxy-io: manage Connection lifetime with shared_ptr

The "onDisconnect handler does not run after the connection is destroyed" test was removed in this commit,

But I couldn't find a test for the new afterDisconnect behaviour (a null pointer when the connection is gone, skipped when disconnected is true). Could we add one, maybe for a remote disconnect racing a local disconnect?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

re: #336 (comment)

Could we add one, maybe for a remote disconnect racing a local disconnect?

Good idea. I'm reconsidering the direction of this PR after your review (see the status section in the description), so I'll add this test once that is settled. The cases you describe apply to any version that keeps the deferred afterDisconnect handler.

Comment thread include/mp/proxy-io.h Outdated
connection->onDisconnect([&loop, connection] {
m_context.connection->afterDisconnect([&loop](Connection* conn) {
// If conn is null or disconnected() is true, a disconnect was
// already trigged locally, so there is nothing to do and an

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In commit ef84b20: proxy-io: manage Connection lifetime with shared_ptr

nit: "trigged" -> "triggered"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

re: #336 (comment)

Thanks, fixed.

ryanofsky and others added 9 commits November 23, 2026 09:14
Drop the outer `if (m_disconnect_cb)` check in ~ProxyClient<Thread>. It
has been redundant since 4a269b2, which
moved the removeSyncCleanup() call into loop->sync() and repeated the
check inside the lambda.

The outer check also read m_disconnect_cb without synchronization on the
thread destroying the ProxyClient<Thread>, while the SetThread disconnect
callback can reset it on the event loop thread. With the check removed,
m_disconnect_cb is only accessed on the event loop thread. This should
not change behavior, aside from removing that unsynchronized read.

Suggested by xyzconstant in
bitcoin-core#361 (comment)

This change was written with Claude Opus 5.5.
This is a documentation-only change meant to make upcoming commits easier to
understand.

This change was written with Claude Opus 4.8 (1M context).
Correct the ThreadContext "Synchronization note", which said
Waiter::m_mutex must not be locked before EventLoop::m_mutex. That is
the reverse of the documented and actual lock order (Waiter::m_mutex
first, as ~ProxyServer<Thread> does). The constraint it was reaching for
is the EventLoop blocking rule now documented on Waiter::m_mutex.

This change was written with Claude Fable 5.1.
Currently, a ListenConnections listener that reaches its max-connection limit
stops accepting new connections permanently if one of its connections is closed
locally instead of by a remote disconnect. Closing a connection locally (e.g.
erasing it from m_incoming_connections) leaves the listener's active-connection
count stuck at the limit, so it never resumes accepting.

This happens because the count is decremented by a callback which only fires on
a remote disconnects, not local disconnects. Fix by moving the decrement to
callback which fires on both local and remote disconnects.

Add a regression test that closes a connection locally and checks the listener
resumes accepting; it fails before this change (the listener never accepts the
waiting client) and passes after.

Co-Authored-By: Enoch Azariah <enirox001@gmail.com>
This change was written with Claude Opus 4.8 (1M context).
Fix a use-after-free, possible since the destroy_connection option was added
in 2019 (c685fa9): a Connection's disconnect handler could run after the
Connection had already been destroyed, deleting it a second time and
crashing. Reported by enirox001 in
bitcoin-core#335 (comment)

Give each Connection a shared_ptr "alive" token that disconnect handlers hold
a weak_ptr to and check before running, so a handler is skipped once its
Connection is gone. Having this check also enables the simplifications
described below.

Previously each Connection kept its disconnect handlers in its own
kj::TaskSet, and when the network disconnected it moved a handler onto the
shared event loop TaskSet with kj::evalLater. Destroying the Connection
destroyed that per-connection TaskSet, canceling a still-pending handler --
but a handler already moved onto the shared TaskSet was no longer canceled
and could run after the Connection was gone. (The evalLater step existed only
to avoid a "promise callback destroyed itself" error when a handler deletes
its own Connection, which the per-connection TaskSet made possible.)

With the token doing the cancellation, neither the per-connection TaskSet nor
the evalLater step is needed, and both are removed.

Co-Authored-By: Enoch Azariah <enirox001@gmail.com>
This change was written with Claude Fable 5.
Fix a race between a thread exiting after making IPC calls and its
connection being destroyed on the event loop thread, which could destroy
the same ProxyClient<Thread> object twice. ~ThreadContext destroyed the
thread-local request_threads/callback_threads maps with no locking while
the SetThread cleanup callback run by ~Connection erased entries from the
same maps. When both ran at once, each side destroyed the entry's
ProxyClient<Thread>, and ~Connection then ran the ProxyClientBase
disconnect callback on the freed map node (heap-use-after-free, then a
glibc "double free or corruption" abort).

Fix by making map entry removal decide which side destroys an entry:
~ThreadContext and the SetThread callback each remove entries under
Waiter::m_mutex before destroying them, and a side that finds an entry
already gone leaves it to the other. See the code comments for why the
entries are destroyed with the mutex released.

Add a regression test, "Thread exiting while its connection is
destroyed", which uses a new testing_hook_thread_client_destroy hook to
interleave the two sides deterministically and fails on every run
without the fix.

The race is long-standing and reachable on master via connections
created by ConnectStream, whose onDisconnect handler deletes the client
Connection on the event loop thread when the peer disconnects.

This change was written with Claude Fable 5.1.
…uction

Split connection teardown out of ~Connection into an idempotent disconnect()
method, with the destructor delegating to it. Having disconnect() separate
from the destructor gives callers more control over shutdown: they can close
several connections at once and then wait for all of their pending calls to
finish, which the next commits use to fix bitcoin/bitcoin#35845, or close a
connection without waiting for it to be torn down. For existing callers, this
is a behavior-neutral refactor: the same steps run in the same order on
destruction.

Two details are new in disconnect() compared to the destructor:

- The m_alive token, which stops onDisconnect handlers from running, is
  expired by ~Connection but not by disconnect(), so the handlers still free
  the connection after a local disconnect (see the disconnect() code
  comment).

- disconnect() explicitly releases m_thread_pool and m_thread_map so worker
  thread teardown happens at disconnect time. Previously this happened
  implicitly during member destruction.

Letting the handlers free the connection after a local disconnect was
prompted by enochaz's review in
bitcoin-core#335 (comment)

This change was written with Claude Fable 5.
This change was written with Claude Opus 5.5.
…rver calls

Add a per-connection ServerObjectTracker counting live ProxyServer objects,
incremented in the ProxyServerBase constructor and decremented in its
destructor, and make Connection::disconnect() return it. Its waitDrained()
method blocks until the count reaches zero, and pendingServerObjects()
exposes the count for logging.

Disconnecting a connection cancels the KJ promise of an in-flight call, but a
C++ server method body already dispatched to a worker thread runs to
completion. Waiting on the tracker lets shutdown code wait for those bodies
to finish before freeing application state they use (bitcoin/bitcoin#35845).
disconnect() returns the tracker, rather than the connection providing a
waitDrained() method, because the connection may be freed right after
disconnect() returns, while the tracker stays valid as long as it is held.
The ServerObjectTracker comments explain why the count reaching zero means no
call body is still running, and why the tracker is held by shared_ptr.

This change was written with Claude Fable 5.
This change was written with Claude Opus 5.5.
Add a deterministic mptest regression test for bitcoin/bitcoin#35845: hold a
server method body in flight on a worker thread, call
Connection::disconnect(), and check that waitDrained() on the returned
tracker blocks until the body finishes and its server object is destroyed.
Also check that disconnect() removes the connection from the incoming
connection list without the test erasing it, so it does not keep the event
loop running.

This change was written with Claude Fable 5.
Co-Authored-By: Enoch Azariah <enirox001@gmail.com>
This change was written with Claude Opus 5.5.
Make Connection objects shared_ptr-owned, created via a new Connection::make()
factory, and have every proxy object share ownership of its connection
(ProxyContext::connection becomes a shared_ptr, populated via
enable_shared_from_this). A Connection now always outlives its proxy objects
and survives disconnect() as an inert husk until its last reference drops.

Sharing ownership removes two workarounds that existed only because a
Connection could previously be destroyed while proxy objects still referenced
it:

- ~ProxyServerBase no longer has to avoid dereferencing m_context.connection;
  the connection is guaranteed to still exist.

- The separate m_alive liveness token is dropped. The deferred disconnect
  handler (renamed onRemoteDisconnect -> afterDisconnect, since it fires on any
  disconnect and not only remote ones) instead runs off a weak_ptr to the
  Connection and passes each handler a Connection* -- the live connection, or
  null if it was already destroyed before the handler ran. Call sites branch on
  that explicitly rather than the framework silently skipping them; handler
  bodies are idempotent disconnect() calls, not deletions.

Two supporting changes fall out of this and are documented at the code rather
than repeated here: connection construction is split into make() and serve()
(see their comments), and because the shared references form a cycle that
reference-dropping can't break, all teardown now routes through disconnect() --
so every teardown path calls it (see the note on Connection::make). The _Serve
disconnect handler's list bookkeeping changed to match (see the comment there).

disconnect() keeps the contract keepconn defines: callers only call it, and
the connection leaves the incoming-connection list by itself. The _Serve
afterDisconnect handler removes the connection from the list after local
disconnects as well as remote ones, and disconnect() returns a tracker that
shares ownership of the connection, so waiting on it is safe however long
the connection stays on the list.

Also drop the test that checked a queued disconnect handler does not run after
its Connection is destroyed. It reproduced the m_alive race by constructing a
Connection directly and freeing it while the handler was still queued. Both
premises are gone: a Connection can only be built through make() now, and
handler bodies no longer delete anything, so the double deletion the test
guarded against is structurally impossible. afterDisconnect now hands such a
handler a null Connection* instead, which its callers handle explicitly, and
the ordinary disconnect and drain tests exercise that path.

This change was written with Claude Fable 5.
This change was written with Claude Opus 5.5.
Remove the per-client disconnect tracking from ProxyClientBase: client
objects no longer register a cleanup callback with their Connection, and a
disconnect no longer eagerly releases their m_client capability handles or
nulls their connection pointers.

Neither is necessary now that proxy objects share ownership of their
Connection. The connection pointer stays valid after a disconnect because the
Connection outlives its proxies, and keeping the capability handle is safe:
Cap'n Proto's per-connection state is refcounted and outlives the RPC system as
long as handles reference it, with calls on handles of a disconnected
connection failing cleanly with DISCONNECTED errors. The handle is simply
released (on the event loop thread, since capability refcounts are not thread
safe) whenever the client object is eventually destroyed, and clientInvoke
checks the connection's disconnected() predicate instead of a nulled pointer,
throwing the same 'IPC client method called after disconnect' error as before.

This deletes the detach machinery from ~ProxyClientBase, including the FIXME'd
duplicate-cleanup code path. Connection::onDisconnect (the renamed
addSyncCleanup) remains for its one other user, the per-thread connection maps
(see SetThread), which the next commit converts.

Because the connection pointer is no longer nulled on disconnect, ~ProxyClient
<Thread> can no longer use it to tell whether Connection::disconnect() has
already run and freed its m_disconnect_cb cleanup node. It now keys off the
connection's disconnected() predicate instead: if the connection is
disconnected the node is already gone and must not be passed to
cancelOnDisconnect. Without this, ~ProxyClient<Thread> erased an already-freed
list node -- a heap-use-after-free (see the "Waiting for in-flight server call
to finish after disconnect" test, which this commit re-enables).

That test also has to hold its own shared reference to the server Connection
across the disconnect() + waitDrained() sequence, the way Ipc::disconnect
Incoming does: under shared ownership the last server proxy (destroyed once the
drained body finishes) would otherwise free the Connection while the test is
still observing it.

This change was written with Claude Fable 5.
This change was written with Claude Opus 4.8.
Update comments to reflect that after the previous commit, the sync cleanup
callback list has exactly one remaining purpose: eagerly removing a
disconnected connection's ProxyClient<Thread> entries from the thread_local
per-thread connection maps (ThreadContext::request_threads /
callback_threads) via callbacks registered by SetThread.

Unlike interface clients, these entries cannot simply be left alive across a
disconnect: they are owned by other threads that may never touch their maps
again, and a surviving entry would hold the disconnected Connection object
-- and through its EventLoopRef the event loop -- alive indefinitely,
preventing the loop from ever exiting. (Replacing the callbacks with lazy
garbage collection in SetThread was tried and hangs mptest for exactly this
reason: entries owned by long-lived threads pin the loop after their
connection is gone.) So this per-object disconnect tracking is retained by
design, now clearly documented as thread-map-specific rather than a general
client-object mechanism.

This change was written with Claude Fable 5.
Now that proxy objects hold shared ownership of their Connection, a
ProxyServer object kept alive by an in-flight call can no longer outlive the
Connection, so ~ProxyServerBase can always reach the tracker through
m_context.connection. Drop the shared_ptr indirection that existed to keep
the tracker valid past the Connection's death, and the separate tracker
handle member on ProxyServerBase.

The Tracker returned by disconnect() now points at the member and shares
ownership of the Connection (an aliasing shared_ptr), so it stays valid
while the caller holds it. No change for callers.

This change was written with Claude Fable 5.
This change was written with Claude Opus 5.5.
Needed because changing m_incoming_connections type is an API change.

@ryanofsky ryanofsky left a comment •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks @enochaz for the review! This PR is on hold while #361 and #335 get reviewed, and your review made me reconsider its direction.

The goal is an internal cleanup: making Connection objects reference counted so ProxyContext::connection can't dangle. That removes the cleanup callbacks ProxyClient objects register with connections and the m_alive token, which are where two of the bugs fixed in #361 came from. It doesn't require changes to Bitcoin Core beyond bitcoin/bitcoin#35932.

The cost, which your review pointed out, is a reference cycle: a connection holds its RPC system, which holds the ProxyServer objects, which hold references back to the connection. Only disconnect() breaks the cycle, so an owner that drops a connected Connection without disconnecting it leaks it, and the leaked connection keeps the event loop running. Directions I'm considering:

  1. Keep this design and break the cycle at the owner: list entries and what ServeStream returns would be a small owning type whose destructor calls disconnect(), so releasing a connection works the way erasing it did before this PR.
  2. Reference count connections only from ProxyClient objects. Clients aren't part of the cycle, so there would be nothing to break, and this keeps most of the benefit (no dangling client pointers or cleanup callbacks), while server objects keep using the tracker from #335.
  3. Close this PR and open a new one, if the result ends up different enough that this history would be confusing.

The second option seems promising but I haven't worked it out yet. Feedback on which direction seems better is welcome.


Rebased 4874ee0 -> c11b9c0 (pr/notrack.4 -> pr/notrack.5, compare) on top of #335 pr/keepconn.9, dropping the merge of #365 (now merged), keeping the #335 disconnect() behavior by removing connections from the incoming list after local disconnects too, making the server object tracker a plain Connection member (dropping tracker()), and fixing a typo

Updated c11b9c0 -> 2bbe22a (pr/notrack.5 -> pr/notrack.6, compare) to fix CI: a ThreadSanitizer data race where Connection::make()'s deleter deleted the connection inside sync() without holding an EventLoopRef, so the event loop could exit while the caller was still returning from sync() https://github.com/bitcoin-core/libmultiprocess/actions/runs/45321627369/job/138201298394?pr=336

Comment thread include/mp/proxy-io.h
//! Tracker for live ProxyServer objects associated with this connection,
//! used by waitDrained().
std::shared_ptr<ServerObjectTracker> m_server_objects{std::make_shared<ServerObjectTracker>()};
ServerObjectTracker m_server_objects;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

re: #336 (comment)

This member looks unused now.

Thanks, good catch. This commit ended up half one approach and half the other. In the latest push it does what the title says: Connection holds the tracker as a plain m_server_objects member and no longer inherits from ServerObjectTracker.

Comment thread include/mp/proxy-io.h Outdated
//! no server call body is still executing (see ServerObjectTracker).
using Tracker = std::shared_ptr<ServerObjectTracker>;
Tracker tracker() { return m_server_objects; }
Tracker tracker() { return shared_from_this(); }

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

re: #336 (comment)

is the Tracker type still needed?

It's still used, but tracker() is gone. After your #335 comments, disconnect() returns the tracker, and that is how callers wait (#335 (comment)). In this PR the tracker is now an aliasing shared_ptr pointing at the plain m_server_objects member and sharing ownership of the Connection, so this PR doesn't change the API #335 adds, and bitcoin/bitcoin#35932 works the same with or without it.

Comment thread include/mp/proxy-io.h
//! last reference to the EventLoop, and exit after the last disconnect.
template <typename F>
void onDisconnect(F&& f)
void afterDisconnect(F&& f)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

re: #336 (comment)

Could we add one, maybe for a remote disconnect racing a local disconnect?

Good idea. I'm reconsidering the direction of this PR after your review (see the status section in the description), so I'll add this test once that is settled. The cases you describe apply to any version that keeps the deferred afterDisconnect handler.

Comment thread include/mp/proxy-io.h Outdated
connection->onDisconnect([&loop, connection] {
m_context.connection->afterDisconnect([&loop](Connection* conn) {
// If conn is null or disconnected() is true, a disconnect was
// already trigged locally, so there is nothing to do and an

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

re: #336 (comment)

Thanks, fixed.

Comment thread include/mp/proxy-io.h
Comment on lines +598 to +604
//! Note: dropping shared_ptr references alone will not usually destroy a
//! connected Connection, because connected state holds capability
//! references to server objects which themselves hold references back to
//! the Connection (m_rpc_system exports -> ProxyServer objects ->
//! ProxyContext::connection). disconnect() breaks these cycles, so every
//! code path that tears down a connection must call it; after that, the
//! object is destroyed when the last reference is dropped.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

re: #336 (review)

In commit "proxy-io: manage Connection lifetime with shared_ptr" (a07e7ac)

I think disconnectIncoming in bitcoin/bitcoin#35932 might have a similar problem, since it disconnects the connections but never removes them from the incoming connections list.

Thanks for the Concept ACK and for catching this. You're right, and it was a real bug in bitcoin/bitcoin#35932 even without this PR: if an IPC client was still connected when the node shut down, shutdown finished but the process never exited, because the disconnected connections stayed in the list and kept the event loop alive.

I fixed it in #335 by making disconnect() remove incoming connections from the list itself, the same way a remote disconnect does, and return the tracker callers wait on, so callers never need to remove connections. bitcoin/bitcoin#35932 also has a new functional test that stops the node with a client connected. This PR keeps that behavior: the _Serve handler now removes the connection after local disconnects too.

Could the owner of the connection disconnect it automatically when it lets go of it?

I think that's the right fix if this PR keeps strong references from proxy objects back to the connection, and it's one of the directions I describe in the review summary. A debug assert wouldn't really work, since nothing runs when the last owner lets go while the cycle exists.

@enochaz

enochaz commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the quick updates and for addressing the comments @ryanofsky

  1. Reference count connections only from ProxyClient objects. Clients aren't part of the cycle, so there would be nothing to break, and this keeps most of the benefit (no dangling client pointers or cleanup callbacks), while server objects keep using the tracker from #335.

I spent some time looking at the options, and this option sounds promising to me. Just to check I understand it correctly, is this roughly what it would look like?

flowchart LR
    owner[owner] --> conn[Connection]
    clients[clients] --> conn
    conn --> server[server objects]
    server -. plain pointer .-> conn
Loading

So the incoming list and the client from ConnectStream would still own the connection, and other ProxyClient objects would hold their own shared_ptr references to it? Since the connection doesn't hold the clients, there's no cycle, so dropping a connection without calling disconnect wouldn't leak it or keep the event loop running? And server objects would keep using the tracker from #335 for waitDrained?

If that's right, the server side still keeps a plain Connection* in m_context like today, which can dangle once the connection is freed.

I was wondering if server objects could hold a weak_ptr instead, so there's no cycle but it can't dangle either? I'm not sure it's worth it though, since every place server code uses the connection would need to handle it being null, and locking it on a worker thread could mean the connection gets freed off the event loop thread.

Do you think that would be worth it, or is the plain pointer handled well enough today?

@ryanofsky ryanofsky left a comment •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks for the feedback! Replied below in #336 (comment)

Comment thread include/mp/proxy.h
Comment on lines +72 to +76
//! Connection this proxy object is associated with. Holding shared
//! ownership (Connection objects are always owned by shared_ptr, see
//! Connection::make) guarantees the Connection outlives this proxy
//! object, so the pointer stays valid even after a disconnect.
std::shared_ptr<Connection> connection;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

re: #336 (comment)

In commit "proxy-io: manage Connection lifetime with shared_ptr" (ea30948)

Just to check I understand it correctly, is this roughly what it would look like?

Yes, that's a good depiction of option 2: owners and other ProxyClient objects hold shared_ptr references, the connection holds its server objects, and server objects point back with a plain pointer, so there's no cycle, and server objects keep using the #335 tracker.

I'm not ready to pick option 2 yet, though. What I like about option 1 is that the incoming connection list and ServeStream callers would hold owning pointers with a guarantee: when that pointer goes away, the connection is destroyed. With shared_ptr owners there's no such guarantee, since a ProxyClient somewhere else could keep the connection alive. I'd probably want to compare implementations of both before deciding.

If that's right, the server side still keeps a plain Connection* in m_context like today, which can dangle once the connection is freed.

Agree this is fragile. As far as I can tell, the current server code only dereferences the pointer while the connection is known to exist: thread lookup and pool dispatch run on the event loop thread when a request arrives, the cleanup after the call body only uses the pointer as a map key, callback arguments are wrapped in a ProxyClient (which would hold its own reference under option 2), and ~ProxyServerBase avoids dereferencing it. But that's a convention, not something the type enforces, so new server code could easily break it. A weak_ptr would turn the convention into a check, at the cost of handling null wherever server code uses the connection.

locking it on a worker thread could mean the connection gets freed off the event loop thread

This part should be OK: Connection::make's deleter already runs the destructor on the event loop thread when another thread drops the last reference. The cost is that the worker thread blocks until the event loop gets to it.

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.

3 participants