While adding coverage for ConnectStream in #298, the CI job for NetBSD 9.4 was crashing in the new test "Passing a disconnected socket will throw" with:
[ TEST ] connect_tests.cpp:94: Passing a disconnected socket will throw
assertion "m_loop" failed: file "/home/runner/work/libmultiprocess/libmultiprocess/include/mp/proxy.h", line 59, function "mp::EventLoop& mp::EventLoopRef::operator*() const"
*** Received signal [#6](/bitcoin-core-multiprocess/6/): Abort trap
stack:
The race occurs on all platforms, the NetBSD runner is just slow enough that the event loop thread always wins. Asked Claude to try to reproduce it locally and came up with placing (in ConnectStream)
std::this_thread::sleep_for(std::chrono::milliseconds(100));
between the loop.sync(...) block and the client construction to extend the race window so that the event loop thread wins the race (as it consistently did in the failing job), thereby exposing the issue.
The sequence of events is as follows:
ConnectStreamruns aloop.sync(...)block (which executes the body on the event loop thread) that creates theConnection, obtainsinit_client, and registers anonDisconnecthandler that runsdelete connection_ptr. At this point, theProxyClientinstance that will own the connection does not yet exist.- The RPC system hits EOF on its first read of the disconnected socket.
- The event loop then resolves
m_network.onDisconnect(), running the handler from step 1, resulting in theConnectionbeing deleted. Connection::~Connectionresets itsEventLoopRef m_loopmember, and the memory is freed.- The caller thread then wakes up and constructs the
ProxyClient<InitInterface>, whoseProxyContextconstructor reads the freedConnection: https://github.com/bitcoin-core/libmultiprocess/blob/8412fcdc659e1379f9b4dea896c26bc1c5f3afa8/src/mp/proxy.cpp#L82
Steps 2-4 run on the event loop thread, while step 5 runs on the caller thread, with no ordering between them so an early disconnect lets the deletion win.
The fix is already available in #298, I'm opening this issue to make it more visible and easier to review.