Skip to content

proxy-io: Add Connection::disconnect() and a tracker to wait for in-flight calls - #335

Open
ryanofsky wants to merge 3 commits into
bitcoin-core:masterfrom
ryanofsky:pr/keepconn
Open

ryanofsky wants to merge 3 commits into
bitcoin-core:masterfrom
ryanofsky:pr/keepconn

Conversation

@ryanofsky

@ryanofsky ryanofsky commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Add a Connection::disconnect() method that disconnects and frees a connection, and returns a tracker whose waitDrained() method waits for in-flight IPC calls to finish.

Without this, the only way to forcibly close an IPC connection is to delete its Connection object, and there is no generic way to wait for server method bodies that were already dispatched to worker threads and keep running after the disconnect. Individual IPC interfaces like the Bitcoin mining interface would need custom synchronization to avoid race conditions during shutdown. Followup PR bitcoin/bitcoin#35932 uses this API in disconnectIncoming() to avoid IPC mining crashes on Bitcoin Core shutdown without changing the mining code. A unit test is added here simulating these crashes.

After disconnect(), a connection is freed automatically the same way as after a remote disconnect: an incoming connection is removed from the event loop's incoming connection list, and a connection owned by a ProxyClient is deleted. So callers only call disconnect() and wait on the returned tracker, which stays valid after the connection is gone:

std::vector<mp::Connection::Tracker> disconnected;
loop.sync([&] {
    for (mp::Connection& c : loop.incomingConnections()) disconnected.push_back(c.disconnect());
});
for (const auto& tracker : disconnected) tracker->waitDrained();

Possible followups

  • proxy-io: Reference-count Connection objects #336 could change how Connection lifetimes are managed internally, so ProxyContext::connection pointers can't dangle, without changing this API.
  • Exception safety in disconnect(): if a cleanup step throws, later steps are skipped. This is the same as ~Connection on master, so it was kept out of this PR's scope: #335 (comment)

@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 nullfail, 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:

  • #342 (Allow request cancellation for wrapped C++ methods by nullfail)
  • #336 (proxy-io: Reference-count Connection objects 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.

@nullfail

nullfail commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@enochaz

enochaz commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

CI seems upset?

/home/runner/work/libmultiprocess/libmultiprocess/src/mp/proxy.cpp should add these lines:
#include <capnp/rpc-twoparty.h>  // for TwoPartyVatNetwork

@ryanofsky

ryanofsky commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

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

Code Review 901a090

Separating connection teardown from destruction and providing a server-call drain functioanlity is a good addition. The overall approach makes sense. I intend to review this more

I think the commit messages and code documentation are a bit too verbose. The explanations are nice to have, but it overexplains quite often, which ultimately makes it a bit harder to understand. Would suggest some revisions to the commit messages and the documentation to increase clarity

In commit 39cc757: ipc: add Connection::disconnect() separating teardown from destruction

I also think this is not exactly a behavior-neutral change; the commit message itself says Two details are new: as we now explicitly cancel m_on_disconnect handlers before severing the connection, and explicitly release m_thread_pool and m_thread_map during disconnect() rather than relying on member destruction.

The m_on_disconnect change is especially not something I would call behavior-neutral, as now we have to proactively cancel because Connection remains alive after the transport is severed and is no longer a consequence of destruction teardown. So even though the externally observable behaviour might seem unchanged, the lifetime and cancellation behaviour has changed, and I think that distinction matters

So the text saying

“This is a behavior-neutral refactor: the same steps run in the same order on destruction.”

is a bit misleading i think?

Also, in commit a40189f, there does not seem to be a clear commit title and description here; they are together

Left a few more suggestions and nits below

Comment thread src/mp/proxy.cpp Outdated
// Disconnecting triggers I/O and tears down capnp state, so it must run on
// the event loop thread, like the destructor.
assert(std::this_thread::get_id() == m_loop->m_thread_id);
if (m_disconnected) return;

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 39cc757: ipc: add Connection::disconnect() separating teardown from destruction

disconnect() sets m_disconnected = true; later on we clean everything up, so I am unsure, but if there was a scenario where one of the cleanups threw, it would not complete the rest. This might not be a problem, but another call to disconnect() would be a no-op.

I do not think all the operations after this can cause this to throw and lead to this, but shutdownWrite() might if it throws an exception other than the ones mentioned.

A simple fix is to set the m_disconnected = true only after all teardown that must run has completed.

index 0aaa58a..8b9f458 100644
--- a/src/mp/proxy.cpp
+++ b/src/mp/proxy.cpp
@@ -124,7 +124,6 @@ void Connection::disconnect()
     // the event loop thread, like the destructor.
     assert(std::this_thread::get_id() == m_loop->m_thread_id);
     if (m_disconnected) return;
-    m_disconnected = true;

     // Cancel pending onDisconnect handlers first. Severing the connection
     // below completes m_network.onDisconnect() promises, and the registered
@@ -253,6 +252,8 @@ void Connection::disconnect()
     // stream.
     m_network.reset();
     m_stream = nullptr;
+
+    m_disconnected = true;
 }

 void Connection::waitDrained()

or a better solution that make sure the the cleanup happens even if shutdownWrite fails?

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: #335 (comment)

I think I want to drop the m_disconnected variable and just treat m_network being nullopt the same as m_disconnected being true, which I think should be equivalent to your suggestions.

It's also true that cleanup functions throwing is not something that this library handles very well generally, and could handle better in many cases.

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: #335 (comment)

I think I want to drop the m_disconnected variable and just treat m_network being nullopt the same as m_disconnected being true, which I think should be equivalent to your suggestions.

I did drop this extra variable in latest push, but didn't look into the exception safety yet. As mentioned previously there are many other places in the library where unexpected exceptions from callbacks will cause problems. I do want revisit and see if there's an improvement that can be made here but would want to keep scope limited and not get into fixing preexisting problems because that could really increase the size of this change.

Comment thread include/mp/proxy-io.h Resolved
Comment thread include/mp/proxy-io.h Outdated
// to the EventLoop TaskSet to avoid "Promise callback destroyed itself"
// error in the typical case where f deletes this Connection object.
m_on_disconnect.add(m_network.onDisconnect().then(
m_on_disconnect->add(m_network->onDisconnect().then(

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 39cc757: ipc: add Connection::disconnect() separating teardown from destruction

The listener now keeps a counter of the active connections added in 39a10ce. When it is full, it stops accepting new connections, and when a client disconnects, a callback decreases the counter, and the listener can start accepting again.

But when the server calls disconnect() it cancels that callback. The connection closes, but the counter does not change, so the listener might think it is full and never accept another connection

Added this change to so that the listener count can be updated for every disconnect, while automatic deletion happens only for remote disconnects

index 1f77b26..30627ec 100644
--- a/include/mp/proxy-io.h
+++ b/include/mp/proxy-io.h
@@ -1016,10 +1016,12 @@ void _Serve(EventLoop& loop, kj::Own<kj::AsyncIoStream>&& stream, InitImpl& init
     auto it = loop.m_incoming_connections.begin();
     MP_LOG(loop, Log::Info) << "IPC server: socket connected.";
     if (loop.testing_hook_connected) loop.testing_hook_connected();
-    it->onDisconnect([&loop, it, on_disconnect = std::forward<OnDisconnect>(on_disconnect)]() mutable {
+    it->addSyncCleanup([on_disconnect = std::forward<OnDisconnect>(on_disconnect)]() mutable {
+        on_disconnect();
+    });
+    it->onDisconnect([&loop, it]() mutable {
         MP_LOG(loop, Log::Info) << "IPC server: socket disconnected.";
         loop.m_incoming_connections.erase(it);
-        on_disconnect();
         if (loop.testing_hook_disconnected) loop.testing_hook_disconnected();
     });
 }

This test could also be added to verify the above behaviour

index a9d4dca..240af3f 100644
--- a/test/mp/test/listen_tests.cpp
+++ b/test/mp/test/listen_tests.cpp
@@ -265,6 +265,29 @@ KJ_TEST("ListenConnections enforces a local connection limit")
     KJ_EXPECT(client3->client->add(3, 4) == 7);
 }

+KJ_TEST("ListenConnections resumes after a local disconnect")
+{
+    ListenSetup server(/*max_connections=*/1);
+
+    auto client1 = std::make_unique<ClientSetup>(server.listener.MakeConnectedSocket());
+    server.WaitForConnectedCount(1);
+    KJ_EXPECT(client1->client->add(1, 2) == 3);
+
+    auto client2 = std::make_unique<ClientSetup>(server.listener.MakeConnectedSocket());
+    (**server.m_loop_ref).sync([] {});
+    KJ_EXPECT(server.ConnectedCount() == 1);
+
+    EventLoop& loop{**server.m_loop_ref};
+    loop.sync([&] {
+        KJ_REQUIRE(loop.m_incoming_connections.size() == 1);
+        loop.m_incoming_connections.front().disconnect();
+        loop.m_incoming_connections.pop_front();
+    });
+
+    server.WaitForConnectedCount(2);
+    KJ_EXPECT(client2->client->add(2, 3) == 5);
+}
+
 KJ_TEST("ListenConnections accepts multiple connections")
 {
     // With max-connections=2, two clients should be accepted and usable at the

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: #335 (comment)

Good catch and nice test!

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: #335 (comment)

Added this change to so that the listener count can be updated for every disconnect, while automatic deletion happens only for remote disconnects

Thanks for the bug report, and fix, and test. This is a separate, preexisting bug so I made a new PR #361 to address it. Your changes are in bb21177 there. This bug isn't a practical problem for bitcoin core because it does not disconnect IPC clients except when it is shutting down. But it could a problem for other IPC servers using this code. The problem is also not new to this PR. Even though this PR is adding a disconnect method which makes it possible to disconnect clients without deleting the Connection objects, it was always possible to disconnect clients by deleting the Connection objects.

Comment thread include/mp/proxy-io.h
: m_loop(loop), m_stream(kj::mv(stream_)),
m_network(*m_stream, ::capnp::rpc::twoparty::Side::CLIENT, ::capnp::ReaderOptions()),
m_rpc_system(::capnp::makeRpcClient(m_network)) {}
m_network(std::in_place, *m_stream, ::capnp::rpc::twoparty::Side::CLIENT, ::capnp::ReaderOptions()),

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 39cc757: ipc: add Connection::disconnect() separating teardown from destruction

Connection can now remain alive after it has been disconnected, but the class does not define which methods are safe to call afterwards.

Previously, disconnection meant destroying the whole object, but now the connection object still exists. This is needed so callers can use methods such as waitDrained, but other methods still behave as if the connection is active.

Could some documentation, assertion, or runtime check be helpful for 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: #335 (comment)

Connection can now remain alive after it has been disconnected, but the class does not define which methods are safe to call afterwards.

Added some documentation that after calling disconnect method methods that perform i/o won't work. In general, I would like to make methods safe to call and avoid having unnecessary restrictions.

Comment thread src/mp/proxy.cpp Outdated
// Blocking the event loop thread here would deadlock: in-flight call
// bodies sync() back to the event loop to deliver their results, and
// server objects are destroyed on the event loop thread.
assert(std::this_thread::get_id() != m_loop->m_thread_id);

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 631d8d9: ipc: add Connection::waitDrained() to wait for in-flight server calls

The documentation for the waitDrained method in proxy-io.h says it is meant to be called after disconnect() call, but does nothing to enforce it, i think we can assert that the disconnect method has been called before calling waitDrained as such

index 0aaa58a..6a318b0 100644
--- a/src/mp/proxy.cpp
+++ b/src/mp/proxy.cpp
@@ -261,6 +261,7 @@ void Connection::waitDrained()
     // bodies sync() back to the event loop to deliver their results, and
     // server objects are destroyed on the event loop thread.
     assert(std::this_thread::get_id() != m_loop->m_thread_id);
+    assert(m_disconnected);
     m_server_objects->wait();
 }

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: #335 (comment)

i think we can assert that the disconnect method has been called before calling waitDrained as such

Was there a specific scenario that made this assert seem useful? It should be fine to call waitDrained regardless of whether the disconnect method was called. It would seem useful to do that if you want to detect when there's a disconnect and server objects are no longer in use, and don't care whether the disconnect was initiated locally or remotely.

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.

Was there a specific scenario that made this assert seem useful?

No specific scenario, I was going off the doc comment in proxy-io.h, which reads as if calling disconnect first is a precondition. Your explanation makes sense, waiting for server objects to drain is useful regardless of whether the disconnect was initiated locally or remotely, so the assert would be wrong. Dropping the suggestion

Comment thread include/mp/proxy-io.h Resolved
Comment thread test/mp/test/test.cpp Outdated
// disconnect error), but the body is still blocked on the worker thread,
// so its server object must still be alive.
foo->m_context.loop->sync([&] { connection->disconnect(); });
KJ_EXPECT(connection->pendingServerObjects() == 1);

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 092d1db: test: cover draining in-flight server call after disconnect

I think using an exact count of one is a bit brittle; the test only needs to establish that something remains in flight. This would be less implementation-specific

index 5bccb86..da47fde 100644
--- a/test/mp/test/test.cpp
+++ b/test/mp/test/test.cpp
@@ -463,13 +463,13 @@ KJ_TEST("Waiting for in-flight server call to finish after disconnect")

     // The FooInterface server object is the connection's only counted server
     // object, and its call body is executing.
-    KJ_EXPECT(connection->pendingServerObjects() == 1);
+    KJ_EXPECT(connection->pendingServerObjects() > 0);

     // Disconnect. This cancels the call's promise (the client above sees the
     // disconnect error), but the body is still blocked on the worker thread,
     // so its server object must still be alive.
     foo->m_context.loop->sync([&] { connection->disconnect(); });
-    KJ_EXPECT(connection->pendingServerObjects() == 1);
+    KJ_EXPECT(connection->pendingServerObjects() > 0);

     // A drain must block while the body runs and return only once it
     // finishes, which is what Ipc::disconnectIncoming relies on during

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: #335 (comment)

I think using an exact count of one is a bit brittle; the test only needs to establish that something remains in flight. This would be less implementation-specific

It is true test could be a little more brittle, but I think checking actual counts makes the test easier to understand and makes the code match the comments. But I would agree if there was a change that did cause these checks to break, that would be evidence these are too brittle, and would be good to make checks less strict at that point.

Comment thread test/mp/test/test.cpp Resolved
Comment thread src/mp/proxy.cpp Outdated
// concurrently remove entries when connections are broken (see SetThread
// cleanup function), then destroy the removed ProxyClient<Thread> with the
// mutex released, since its destructor needs to lock EventLoop::m_mutex
// and Waiter::m_mutex must not be held when EventLoop::m_mutex is

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 901a090: Fix thread map teardown race causing use-after-free on disconnect

The Waiter documentation says

//! This mutex can be held at the same time as
//! EventLoop::m_mutex as long as Waiter::mutex is locked first and
//! EventLoop::m_mutex is locked second.

But the new commit says

//! Waiter::m_mutex must not be held when EventLoop::m_mutex is
//! acquired

It also says releasing the waiter mutex avoids locking the Waiter mutex before the EventLoop mutex, these rules cannot both be correct.

I think an actual order should be identified and updated here

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: #335 (comment)

I think an actual order should be identified and updated here

Nice catch. This is actually not the first comment that got the order backwards so I added a new commit to base PR #361 to improve all the documentation about lock order. (It's part of #361 not this PR because I also moved the "Fix thread map teardown race causing" commit you referenced to #361.)

@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 review! Great catches and suggestions. Just left some quick feedback below to make sure I didn't miss anything

Comment thread src/mp/proxy.cpp Outdated
// Disconnecting triggers I/O and tears down capnp state, so it must run on
// the event loop thread, like the destructor.
assert(std::this_thread::get_id() == m_loop->m_thread_id);
if (m_disconnected) return;

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: #335 (comment)

I think I want to drop the m_disconnected variable and just treat m_network being nullopt the same as m_disconnected being true, which I think should be equivalent to your suggestions.

It's also true that cleanup functions throwing is not something that this library handles very well generally, and could handle better in many cases.

Comment thread include/mp/proxy-io.h Resolved
Comment thread include/mp/proxy-io.h Outdated
// to the EventLoop TaskSet to avoid "Promise callback destroyed itself"
// error in the typical case where f deletes this Connection object.
m_on_disconnect.add(m_network.onDisconnect().then(
m_on_disconnect->add(m_network->onDisconnect().then(

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: #335 (comment)

Good catch and nice test!

@nullfail

Copy link
Copy Markdown
Contributor

Code review 901a090

I agree with @enirox001 that some comments and commit messages are quite confusing. Some are written like a story, e.g., "Previously..." clauses that add little value to the code. I had to ignore them because reading the code itself was simpler for me to understand the changes.

Planning to review again once there are more updates.

@ryanofsky

Copy link
Copy Markdown
Collaborator Author

Thanks for the reviews! I implemented fixes for the two preexisting bugs that were pointed out here in a new PR #361, that this PR is now based on so it would makes sense to review that PR first. I've partially addressed some other comments here as well but am still working on things.

Rebased 901a090 -> 33ab215 (pr/keepconn.4 -> pr/keepconn.5, compare) based on #361 implementing most review feedback

ryanofsky added a commit to ryanofsky/libmultiprocess that referenced this pull request Sep 11, 2026
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 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
ryanofsky added a commit to ryanofsky/libmultiprocess that referenced this pull request Sep 11, 2026
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 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>

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

Updated 33ab215 -> 40cfb93 (pr/keepconn.5 -> pr/keepconn.6, compare) improving comments and naming and moving more changes to base PR #361 to simplify commits here.

re: #335 (review)

I also think this is not exactly a behavior-neutral change

Thanks, clarified commit message to say this is a behavior-neutral change for existing callers not calling the new methods. For callers that do specifically call the new disconnect() method, there are some differences from destroying the Connection object.

Rebased 40cfb93 -> abdcf05 (pr/keepconn.6 -> pr/keepconn.7, compare) onto master to fix CI failures (the default job compiler exited with no error message, the netbsd job failed installing packages), also fixing three commit titles that showed a body paragraph

Rebased abdcf05 -> f96eb26 (pr/keepconn.7 -> pr/keepconn.8, compare) due to conflicts with #365 and #382, also fixing the IWYU failure in the default job (an unused #include <list> in listen_tests.cpp, which #371 now reports instead of failing silently)

Comment thread test/mp/test/test.cpp Resolved
Comment thread test/mp/test/test.cpp Outdated
// disconnect error), but the body is still blocked on the worker thread,
// so its server object must still be alive.
foo->m_context.loop->sync([&] { connection->disconnect(); });
KJ_EXPECT(connection->pendingServerObjects() == 1);

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: #335 (comment)

I think using an exact count of one is a bit brittle; the test only needs to establish that something remains in flight. This would be less implementation-specific

It is true test could be a little more brittle, but I think checking actual counts makes the test easier to understand and makes the code match the comments. But I would agree if there was a change that did cause these checks to break, that would be evidence these are too brittle, and would be good to make checks less strict at that point.

Comment thread src/mp/proxy.cpp Outdated
// concurrently remove entries when connections are broken (see SetThread
// cleanup function), then destroy the removed ProxyClient<Thread> with the
// mutex released, since its destructor needs to lock EventLoop::m_mutex
// and Waiter::m_mutex must not be held when EventLoop::m_mutex is

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: #335 (comment)

I think an actual order should be identified and updated here

Nice catch. This is actually not the first comment that got the order backwards so I added a new commit to base PR #361 to improve all the documentation about lock order. (It's part of #361 not this PR because I also moved the "Fix thread map teardown race causing" commit you referenced to #361.)

ryanofsky added a commit to ryanofsky/libmultiprocess that referenced this pull request Oct 2, 2026
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 <[email protected]>
This change was written with Claude Fable 5.
ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Oct 2, 2026
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/libmultiprocess#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 <[email protected]>
This change was written with Claude Fable 5.
ryanofsky added a commit that referenced this pull request Oct 13, 2026
f0a1475 cmake: Show include-what-you-use diagnostics when it fails (Ryan Ofsky)
92127a9 cmake: Pass -w to include-what-you-use (Ryan Ofsky)

Pull request description:

  **Problem:** The IWYU check in the default CI job can fail with a bare `Error 1` and no diagnostics ([example](https://github.com/bitcoin-core/libmultiprocess/actions/runs/34642191878/job/103404374280)). IWYU's clang frontend receives the GCC job's warning flags, so with `-Werror -Wpedantic` every `KJ_TEST` reports `'__COUNTER__' is a C2y extension` and the GCC-only `-Wtrailing-whitespace` is an unknown option. A file with 19 or more `KJ_TEST`s reaches clang's error limit, clang gives up before IWYU checks anything, and CMake discards IWYU's output because it contains no include suggestions. `test/mp/test/test.cpp` has 16 tests now. #335 adds three more and its default job fails this way, and master will hit it too once a few more tests are added.

  **Solution:** Pass `-w` to IWYU so compiler warning flags no longer affect it, and run it through a small wrapper script that makes CMake print IWYU's output whenever it fails without suggesting includes. The wrapper works around a CMake bug ([cmake#28020](https://gitlab.kitware.com/cmake/cmake/-/issues/28020); an upstream fix in [cmake!9210](https://gitlab.kitware.com/cmake/cmake/-/merge_requests/9210) was approved but never finished) and can be dropped once CMake fixes it.

ACKs for top commit:
  xyzconstant:
    LGTM ACK f0a1475
  hebasto:
    ACK f0a1475, I have reviewed the code and it looks OK.

Tree-SHA512: 3174270ac5bb3ec01a224b4a41761728870643f34f03f1d5826d2460de55853b615a900ed47685aa47f94886754450b753b8bf7d90bac512268e6993cdfcbe1b
ryanofsky added a commit to ryanofsky/libmultiprocess that referenced this pull request Nov 13, 2026
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 <[email protected]>
This change was written with Claude Fable 5.
ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Nov 13, 2026
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/libmultiprocess#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 <[email protected]>
This change was written with Claude Fable 5.

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

ACK f96eb26

Thanks for making the changes since my last review 901a090:

  • The listener fix, the queued onDisconnect fix and the thread map race fix moved to #361
  • m_disconnected was dropped, and m_network being empty is now used as the disconnected state
  • Docs were added on what is still valid after disconnect
  • testing_hook_wait was added so the drain test no longer depends on timing
  • The commit message now says the change is behavior neutral only for existing callers

Could we update the comments that still refer to Connection::waitDrained and Connection::pendingServerObjects as mentioned in the description? Since both are now reached through Connection::tracker.

I also think the CI failure is unrelated. The netbsd job failed before the build started.

Also left a non-blocking comment about whether keeping only the tracker could replace disconnect.

Comment thread include/mp/proxy-io.h Outdated
//!
//! Cancels the KJ promise of any in-flight call, but a server method body
//! already dispatched to a worker thread runs to completion.
void disconnect();

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 3b3960b: proxy-io: add Connection::disconnect() separating teardown from destruction

The current approach works, but I wonder if disconnect is needed. The tracker is already a shared_ptr that outlives the Connection, so we could keep only the tracker, destroy the connection as usual, and then wait?

auto tracker = conn->tracker();
// destroy the connection as usual
tracker->waitDrained();

This would also cover remote disconnects, where the Connection is deleted automatically and a saved pointer can't be used anymore.

It would also mean we don't need to keep a disconnected Connection alive, which reduces the surface area for crashes. For example, I noticed that calling disconnect on a client-owned connection leaves nothing to delete it, so the event loop never exits.

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: #335 (comment)

In commit "proxy-io: add Connection::disconnect() separating teardown from destruction" (876c514)

The tracker is already a shared_ptr that outlives the Connection, so we could keep only the tracker, destroy the connection as usual, and then wait?

Thanks, this comment and your review of #336 led to a better API. You were right that keeping a disconnected Connection alive was the wrong thing for callers to deal with: bitcoin/bitcoin#35932 had exactly the bug you pointed out in #336, leaving disconnected connections in the incoming list so the node never exited if an IPC client was connected at shutdown.

In the latest push, disconnect() frees the connection itself: after a local disconnect, the same handlers that run after a remote disconnect remove the connection from the incoming list on a later event loop turn. And disconnect() returns the tracker, which is what callers wait on:

std::vector<mp::Connection::Tracker> disconnected;
m_loop->sync([&] {
    for (mp::Connection& c : m_loop->incomingConnections()) {
        if (&c != m_parent_connection) disconnected.push_back(c.disconnect());
    }
});
for (const auto& tracker : disconnected) tracker->waitDrained();

So callers don't manage the connection after disconnecting at all, and this is the only API change: #336 keeps the same API and only changes the implementation.

I noticed that calling disconnect on a client-owned connection leaves nothing to delete it, so the event loop never exits.

This is fixed by the same change: the client's disconnect handler now deletes the connection after a local disconnect too.

ryanofsky added a commit to ryanofsky/libmultiprocess that referenced this pull request Nov 24, 2026
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 <[email protected]>
This change was written with Claude Fable 5.
ryanofsky and others added 3 commits November 23, 2026 21:27
…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.

Also cover disconnect() on a client-owned (outgoing) connection, the case
that leaked when disconnect() expired m_alive: the ProxyClient's connection
pointer is cleared, the connection is freed once the event loop runs its
onDisconnect handler, and later calls fail with "IPC client method called
after disconnect."

This change was written with Claude Fable 5.
Co-Authored-By: Enoch Azariah <[email protected]>
This change was written with Claude Opus 5.5.
ryanofsky added a commit to ryanofsky/libmultiprocess that referenced this pull request Nov 24, 2026
…uction

Split connection teardown out of ~Connection into an idempotent disconnect()
method, with the destructor delegating to it. For existing callers, this is a
behavior-neutral refactor: the same steps run in the same order on destruction.

Calling disconnect() directly closes a connection without the caller having
to free it: afterwards, the connection's onDisconnect handlers free it on a
later event loop turn, the same way they do after a remote disconnect. An
incoming connection is removed from EventLoop::m_incoming_connections, and a
connection owned by a ProxyClient is deleted. So callers only call
disconnect(), and can do so while iterating over incomingConnections(). The
next commits use this to let shutdown code wait for in-flight server calls to
finish after a disconnect (bitcoin/bitcoin#35845).

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 run
  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 was suggested by enochaz in
bitcoin-core#335 (comment)
after an earlier version left disconnected connections for callers to remove,
which callers could forget.

This change was written with Claude Fable 5.
This change was written with Claude Opus 5.5.
@ryanofsky ryanofsky changed the title proxy-io.h: Add Connection disconnect and waitDrained methods proxy-io: Add Connection::disconnect() and a tracker to wait for in-flight calls Nov 24, 2026

@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 review! Suggestion about erasing connections was really helpful and I think API should be safer and easier to use nowi.

Updated f96eb26 -> f65fdc9 (pr/keepconn.8 -> pr/keepconn.9, compare) on top of #361 pr/ondis.6, adding a commit that makes disconnect() free disconnected connections and return a tracker callers wait on, instead of leaving them for callers to remove (fixes a shutdown hang in bitcoin/bitcoin#35932 and a leak when disconnecting a client-owned connection, both found by enochaz), and fixing doc typos

Updated f65fdc9 -> eb98e9c (pr/keepconn.9 -> pr/keepconn.10, compare) with documentation changes only: rewriting the Connection class comment as a self-contained description of connection ownership (who owns incoming and outgoing connections, what destroy_connection means, and how disconnect() mirrors a remote disconnect), shortening the disconnect() comment to match, and updating the disconnect() commit message to say why a separate disconnect() method is useful

Comment thread include/mp/proxy-io.h
Comment on lines +464 to +496
//! Connection, used to wait for a disconnected connection's server side to
//! become quiescent.
//!
//! This count is non-zero as long as the client is holding any object handles
//! or as long as any server methods are running, even after the client as
//! disconnected or freed all its handles. When this is zero it means no more
//! ProxyServer method calls can originate from the connection and it is safe to
//! free any resources accessed through the connection.
//
//! Why counting live server objects is a valid "no server call body running"
//! signal: a ProxyServer object is reference counted and is not destroyed
//! until its outstanding calls finish. Cap'n Proto keeps the target capability
//! alive for the duration of a call, and the mp.Context PassField overload and
//! ProxyServer<Thread>::post() additionally pin it (self = thisCap()) until
//! the call body running on a worker thread completes and its result is
//! delivered. So "object destroyed" implies "its call bodies finished", and a
//! connection whose live-object count reached zero after a disconnect has no
//! server code running. This matters because disconnecting only cancels the
//! KJ promise of an in-flight call; it does not interrupt a call body that
//! was already dispatched to a worker thread (see Connection::disconnect).
//!
//! The counter is held via shared_ptr by the Connection and by every
//! ProxyServer object created for the connection, because a ProxyServer
//! object kept alive by an in-flight call can outlive the Connection (see
//! ~ProxyServerBase), and its destructor must decrement state that is still
//! valid.
//!
//! ProxyServer<Thread> and ProxyServer<ThreadMap> are separate
//! specializations (not ProxyServerBase instances) and are intentionally not
//! counted: every application method body runs on an interface ProxyServer,
//! which is counted and stays alive for the duration of the body, so counting
//! those is sufficient.
struct ServerObjectTracker

@ryanofsky ryanofsky Nov 24, 2026 •

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: enochaz #335 (review)

In commit "proxy-io: return a tracker from disconnect() to wait for in-flight server calls" (f67af0d)

the commit messages and code documentation are a bit too verbose ... it overexplains quite often

Thanks to you and @xyzconstant (#335 (comment)) for this feedback. Since then the biggest changes have been:

  • The commit message adding the tracker and waitDrained() is much shorter and points to the code comments for how the counting works, instead of repeating them.
  • The disconnect() documentation is written for callers (what it does and how to wait, with an example), and the implementation details are in comments in proxy.cpp.
  • The lock order documentation that got the order backwards was rewritten (in #361).
  • The bug fixes and their comments moved to #361, so this PR is smaller.

I didn't want to drop information that seems useful for understanding the code, but if there are specific comments or sentences you think should be cut or simplified, please point them out and I'm happy to change them.

Comment thread include/mp/proxy-io.h Outdated
//!
//! Cancels the KJ promise of any in-flight call, but a server method body
//! already dispatched to a worker thread runs to completion.
void 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: #335 (comment)

In commit "proxy-io: add Connection::disconnect() separating teardown from destruction" (876c514)

The tracker is already a shared_ptr that outlives the Connection, so we could keep only the tracker, destroy the connection as usual, and then wait?

Thanks, this comment and your review of #336 led to a better API. You were right that keeping a disconnected Connection alive was the wrong thing for callers to deal with: bitcoin/bitcoin#35932 had exactly the bug you pointed out in #336, leaving disconnected connections in the incoming list so the node never exited if an IPC client was connected at shutdown.

In the latest push, disconnect() frees the connection itself: after a local disconnect, the same handlers that run after a remote disconnect remove the connection from the incoming list on a later event loop turn. And disconnect() returns the tracker, which is what callers wait on:

std::vector<mp::Connection::Tracker> disconnected;
m_loop->sync([&] {
    for (mp::Connection& c : m_loop->incomingConnections()) {
        if (&c != m_parent_connection) disconnected.push_back(c.disconnect());
    }
});
for (const auto& tracker : disconnected) tracker->waitDrained();

So callers don't manage the connection after disconnecting at all, and this is the only API change: #336 keeps the same API and only changes the implementation.

I noticed that calling disconnect on a client-owned connection leaves nothing to delete it, so the event loop never exits.

This is fixed by the same change: the client's disconnect handler now deletes the connection after a local disconnect too.

Comment thread include/mp/proxy-io.h Outdated
Comment on lines +598 to +600
//! disconnects. The handler runs at most once, and only while this
//! Connection is still alive: if the connection is torn down locally before
//! the handler runs, the handler is not called.

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: #335 (review)

In commit "proxy-io: return a tracker from disconnect() to wait for in-flight server calls" (f67af0d)

Could we update the comments that still refer to Connection::waitDrained and Connection::pendingServerObjects

Thanks for the ACK and the careful summary! Updated these: waitDrained() and pendingServerObjects() are called on the tracker that disconnect() now returns (see the reply about keeping only the tracker). Also fixed the ServerObjectTracker doc typo.

ryanofsky added a commit to ryanofsky/libmultiprocess that referenced this pull request Nov 24, 2026
…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.
ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Nov 24, 2026
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/libmultiprocess#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 <[email protected]>
This change was written with Claude Fable 5.
ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Nov 24, 2026
…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#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/libmultiprocess#335 (comment)

This change was written with Claude Fable 5.
This change was written with Claude Opus 5.5.

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

Code review eb98e9c

Thanks for the update and for adopting the tracker approach. I think the API is much simpler and safer now as callers only call disconnect and wait on the returned tracker, and the connection is freed the same way as after a remote disconnect, so callers no longer need to manage the connection after disconnecting it.

I don't intend to make this review bikesheddy, but I think adopting this approach left some stale comments. Since disconnect no longer expires m_alive, the onDisconnect handlers now also run after a local disconnect, but a few comments still say they only run on a remote disconnect. I left a comment with a suggested diff, and I think these should be addressed since they describe the behaviour the opposite way from how it works now, which could be confusing for anyone touching this code later.

I also left a non blocking suggestion for a test covering disconnect on a client owned connection, since the current test only covers incoming connections, and that was the case that leaked before.

Happy to ACK once the comments are updated.

Comment thread include/mp/proxy-io.h Resolved
Comment thread test/mp/test/test.cpp Resolved
ryanofsky added a commit that referenced this pull request Dec 1, 2026
260c62c proxy: Fix thread map teardown race causing use-after-free on disconnect (Ryan Ofsky)
d7831c8 proxy-io: fix race deleting a disconnected Connection twice (Ryan Ofsky)
8d685ac proxy-io: fix listener stuck at capacity after a local disconnect (Ryan Ofsky)
dfef888 doc: Improve Waiter/EventLoop lock order documentation (Ryan Ofsky)
a0b919a doc: Improve disconnect callback comments (Ryan Ofsky)
f229166 proxy: Remove redundant m_disconnect_cb check in ~ProxyClient<Thread> (Ryan Ofsky)

Pull request description:

  Two bugs in `Connection::onDisconnect` were pointed out in #335 review by enochaz:

  - [ListenConnections failing to accept new connections](#335 (comment)) if max connections limit was reached and a disconnect of an existing connection was initiated locally, rather than remotely.
  - [Race condition in Connection::onDisconnect](#335 (comment)) implementation caused by using `evalLater` could allow an onDisconnect handler to run after a Connection object was destroyed.

  A third "thread map teardown race" bug was also encountered in a new unit test introduced by #335, and Sjors hit it independently while testing sv2-tp when Bitcoin Core disappears from under it (#361 (comment)). This PR fixes each bug in a separate commit and also includes documentation commits to help make the changes more understandable.

  The first two bugs are "theoretical" just in the sense that they haven't been seen in practice and were found in code review. The first ListenConnections bug can't currently happen in bitcoin core because it doesn't disconnect IPC clients except when it is shutting down, and it would not make sense to accept new connections. The second race condition bug has just existed for many years and not been seen previously.

ACKs for top commit:
  enochaz:
    re-ACK 260c62c

Tree-SHA512: 5ced54f703e35f47e67b2c31e7968eea77b68cf3491266a7af250ddcf1968d820fbd471af0bbfeb3225343abcdd3c6471d48973df340214c3f337a2b6bdceb0a

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

Updated eb98e9c -> 6e11cc8 (pr/keepconn.10 -> pr/keepconn.11, compare) fixing comments that still said onDisconnect handlers only run on a remote disconnect (#335 (comment)) and adding a test for disconnecting a client-owned connection (#335 (comment))

Comment thread include/mp/proxy-io.h Resolved
Comment thread test/mp/test/test.cpp Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants