Skip to content

Fix startup race in example - #315

Merged
ryanofsky merged 2 commits into
bitcoin-core:masterfrom
xyzconstant:fix-race-in-mpexample
Jul 30, 2026
Merged

Fix startup race in example#315
ryanofsky merged 2 commits into
bitcoin-core:masterfrom
xyzconstant:fix-race-in-mpexample

Conversation

@xyzconstant

@xyzconstant xyzconstant commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Since #274, connection setup has been split into two calls: MakeStream followed by ConnectStream. Between these calls, the event loop's reference count can temporarily drop to zero, allowing EventLoop::loop() to exit (and the EventLoop to be destroyed) before ConnectStream posts its work. This crashes mpexample on startup.

Fix this by keeping an EventLoopRef alive in main() so the loop stays running while it is in use. This same pattern is already used in Bitcoin Core (m_loop_ref member of CapnpProtocol).

A second commit documents the reference-counted EventLoop lifetime in the EventLoopRef class comment and in doc/usage.md.

NOTE: On macOS, mpexample was crashing intermittently on startup (sometimes failing the m_post_fn == nullptr assert in the EventLoop destructor, sometimes with a mutex lock failure), depending on timing. With this change, the crashes are gone.

@DrahtBot

DrahtBot commented Jul 22, 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
ACK ryanofsky
Stale ACK ViniciusCestarii

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

@xyzconstant
xyzconstant force-pushed the fix-race-in-mpexample branch from b031c1f to ff9f84c Compare July 22, 2026 03:59
@xyzconstant

Copy link
Copy Markdown
Contributor Author

failed CI job seems unrelated

@xyzconstant
xyzconstant force-pushed the fix-race-in-mpexample branch from ff9f84c to f2fabf6 Compare July 22, 2026 04:19

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

tACK f2fabf6 nice catch! I was able to reproduce on linux and it also intermittently fails without this fix. I liked the doc explanation too.

nit: a more surgical fix for against against master could look like:

+#include "mp/proxy.h"
 #include <init.capnp.h>
 #include <init.capnp.proxy.h>
 
int main(int argc, char** argv)
         loop.loop();
     });
     mp::EventLoop* loop = promise.get_future().get();
+    mp::EventLoopRef loop_ref{*loop};
 
     auto [printer_init, printer_pid] = Spawn(*loop, argv[0], "mpprinter");
     auto [calc_init, calc_pid] = Spawn(*loop, argv[0], "mpcalculator");
int main(int argc, char** argv)
     mp::WaitProcess(calc_pid);
     printer_init.reset();
     mp::WaitProcess(printer_pid);
+    loop_ref.reset();
     loop_thread.join();
     std::cout << "Bye!" << std::endl;
     return 0;

@xyzconstant
xyzconstant force-pushed the fix-race-in-mpexample branch from f2fabf6 to 265302b Compare July 23, 2026 23:26

@ryanofsky ryanofsky left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Code review ACK 265302b. Nice catch and this fix looks correct, but it seems a little more complicated than it needs to be and I suggested a simpler version below.

I was initially confused how #274 causes this bug, but it happens specifically because of the loop.sync call in MakeStream. Each time loop.sync is called it causes the event loop to spin and check the reference count and potentially exit. The sync call in MakeStream is actually not necessary in practice, but was added as precaution in case the the wrapFd call was changed to update shared state. But because creating the stream object and connecting used to happen in one sync call and now happens in two calls, adding an extra reference to the event loop is necessary.

Comment thread example/example.cpp Outdated
namespace fs = std::filesystem;

static auto Spawn(mp::EventLoop& loop, const std::string& process_argv0, const std::string& new_exe_name)
static auto Spawn(const mp::EventLoopRef& loop_ref, const std::string& process_argv0, const std::string& new_exe_name)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

In commit "Fix startup race in mpexample" (f433a3f)

I don't think it actually makes sense to change this function and pass in a loop ref object when this isn't going to actually change the reference count. Would be better to revert changes to this function.

Similarly I think most of the changes below are not needed. Would suggest a simpler fix:

--- a/example/example.cpp
+++ b/example/example.cpp
@@ -55,6 +55,7 @@ int main(int argc, char** argv)
         loop.loop();
     });
     mp::EventLoop* loop = promise.get_future().get();
+    mp::EventLoopRef loop_ref{*loop};
 
     auto [printer_init, printer_pid] = Spawn(*loop, argv[0], "mpprinter");
     auto [calc_init, calc_pid] = Spawn(*loop, argv[0], "mpcalculator");
@@ -71,6 +72,7 @@ int main(int argc, char** argv)
     mp::WaitProcess(calc_pid);
     printer_init.reset();
     mp::WaitProcess(printer_pid);
+    loop_ref.reset();
     loop_thread.join();
     std::cout << "Bye!" << std::endl;
     return 0;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done at 3a997e1

Thanks!

Comment thread example/example.cpp Outdated
std::thread loop_thread([&] {
mp::EventLoop loop("mpexample", LogPrint);
promise.set_value(&loop);
promise.set_value(mp::EventLoopRef(loop));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

In commit "Fix startup race in mpexample" (f433a3f)

Suggested an alternative in diff above, and I think creating an EventLoopRef here and then moving it into another EventLoopRef variable is too complicated and not necessary. It should only be necessary to increment the event loop usage count before using the event loop, and doesn't have to be done when creating it.

Since bitcoin-core#274, connection setup has been split into two calls: `MakeStream`
followed by `ConnectStream`. Between these calls, the event loop's reference
count can temporarily drop to zero, allowing `EventLoop::loop()` to exit
before `ConnectStream` posts its work, crashing the example on startup.

Keep an `EventLoopRef` alive in main() so the loop stays running while it
is in use.
`EventLoop::loop()` exits when the last `EventLoopRef` is released, so
code making multiple calls against the loop needs to hold its own
reference. State this in the `EventLoopRef` comment and usage.md.
@xyzconstant
xyzconstant force-pushed the fix-race-in-mpexample branch from 265302b to 36c6c63 Compare July 30, 2026 14:18
@xyzconstant

xyzconstant commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the reviews!

The same diff has been suggested twice, so I just applied it in the latest push (36c6c63).

With #323 now merged, CI jobs should be green.

@ryanofsky ryanofsky left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Code review ACK 36c6c63. Thanks for the fix, documentation, and simplification!

@ryanofsky
ryanofsky merged commit 8d6d464 into bitcoin-core:master Jul 30, 2026
13 checks passed
Sjors added a commit to Sjors/sv2-tp that referenced this pull request Aug 20, 2026
d0eea62c58 ci: add Windows cross-compilation config using MinGW and Wine
ae6cf017d4 test: Add TCP SocketListener and Windows compat to socketlistener.h
1938c199d7 util: make pthreads optional on Windows to enable MSVC builds
97011d4008 util: Fix Windows SpawnProcess hang when child exits before connecting to named pipe
7861351f24 util: Add Windows support
ee09c2b269 util: Add Windows CommandLineFromArgv escaping function
860e2ffb5c util, test: guard Unix-only code for Windows build
c79b49afe1 util, test: Replace UnixListener with SocketListener
15aa914f03 util, test: Add CloseSocket, use SocketId
be5f87655a util: Improve SpawnProcess API and documentation
390b5f901f Merge bitcoin-core/libmultiprocess#344: test: listen_tests and connect_tests follow-ups
e18ca520f4 Merge bitcoin-core/libmultiprocess#343: test: fix race in connect_tests disconnect-deferred-failure test
c39c7850c6 doc: note construct() call in valid init interface test
b9c36c6175 test: close sockets unconditionally and check errors with KJ_SYSCALL
7eb741e635 test: drop unnecessary KJ_EXPECT(true)
113f1d4d28 test: join server thread unconditionally in connect tests
44bc4630bc test: drop mp:: prefixes in connect tests
038d33eb31 test: share DefaultLogHandler between test files
b54a163308 test: drop TestSetup socket members in connect tests
70467c5a72 test: add m_ prefix to TestSetup members in connect tests
cc260f2526 test: replace capnp fix link with upstream PR
137a6e4e03 test: fix race in connect_tests disconnect-deferred-failure test
8dab0d4bde Merge bitcoin-core/libmultiprocess#341: ci: add -Wextra-semi to llvm config
b3b134eed8 ci: add -Wextra-semi to llvm config
bdd0cd6941 Merge bitcoin-core/libmultiprocess#339: refactor: add `[[noreturn]]` attributes
a779a09764 ci: add -Wmissing-noreturn
636aaff576 refactor: add missing [[noreturn]] attributes
cc11c2b1b4 Merge bitcoin-core/libmultiprocess#338: test: check ReadList return value
2d6e863c77 Merge bitcoin-core/libmultiprocess#334: ci: Set CMAKE_BUILD_PARALLEL_LEVEL to enable parallelism by default
d4d10ff98a Merge bitcoin-core/libmultiprocess#332: ci: add -Wextra-semi to default config
b540e70f25 Merge bitcoin-core/libmultiprocess#324: proxy: Name threads spawned by the event loop
e5e367e785 Merge bitcoin-core/libmultiprocess#312: util: report back child errors to parent and throw
2220df68c9 Merge bitcoin-core/libmultiprocess#298: Fix error handling when creating clients (`mp::ConnectStream`)
51defb79ef Merge bitcoin-core/libmultiprocess#340: ci: Update `capnproto` prerequisites on NetBSD
7e94790b08 ci: Update `capnproto` prerequisites on NetBSD
9f25ffca5b test: Cover OS thread names for worker, pool, and async threads
648a18589c proxy: Name threads spawned by the event loop
49834b2609 ci: add -Wextra-semi to default config
fae9a637e3 example: Remove unused kj/async.h include
bb473690c9 Fix error handling when creating clients
44d191420c Add test coverage for ConnectStream
231361ae5a Correct stale UnixListener doc comment
060c1a50d0 Extract `UnixListener` class to a dedicated file
62f25af06c test: check ReadList return value
ce51d73725 ci: Set CMAKE_BUILD_PARALLEL_LEVEL to enable parallism in build jobs by default
67302cd132 Merge bitcoin-core/libmultiprocess#331: Remove code for Cap'n Proto versions before 0.9
f13c64ab54 Merge bitcoin-core/libmultiprocess#330: ci: Compile with minimum supported g++ in olddeps
8e026f6625 Merge bitcoin-core/libmultiprocess#327: build: avoid unnecessary capnp-rpc dependency for mpgen
e5206e9eb5 Merge bitcoin-core/libmultiprocess#325: cmake: Remove `QUIET` option from `find_package(CapnProto ...)`
879efea2bc Merge bitcoin-core/libmultiprocess#321: ci: Roll NetBSD releases to 11.0, drop 9.4
abf127a314 Merge bitcoin-core/libmultiprocess#317: ipc: Fix mpgen capnp tool path for vcpkg/Windows builds
c437d7f107 Merge bitcoin-core/libmultiprocess#310: test: cover immediate client disconnects for `ListenConnections`
31bff8a673 Merge bitcoin-core/libmultiprocess#307: refactor: memcpy -> std::ranges::copy
f355108b0a Merge bitcoin-core/libmultiprocess#303: type-chrono: Add CustomBuildField/CustomReadField overloads for std::chrono::time_point
2d678177c1 Merge bitcoin-core/libmultiprocess#296: ci: Bump channel to nixos-26.05
3f05b11624 util: kill and reap child on SpawnProcess error
4a56c1837a util: report back child error to parent and throw
a9e70dbe77 ci: Add NetBSD release 11.0
2d33b14fb0 ci: Switch to default compiler on NetBSD 9.4
36f7400277 ci: Drop NetBSD release 9.4
bd508311b5 refactor: Drop stray semicolons after function definitions
788f17a850 Remove code for Cap'n Proto versions before 0.9
7402affd0c ci: Pin oldeps config to older nixpkgs channel to compile older cmake with older gcc
edf6343562 ci: Compile with minimum supported g++-11 in olddeps
fa47449afe cmake: avoid unnecessary capnp-rpc dependency for mpgen
a494b764de cmake: Remove `QUIET` option from `find_package(CapnProto ...)`
26452e02d7 refactor: memcpy -> std::ranges::copy
e1dcc6eb18 Merge bitcoin-core/libmultiprocess#316: cmake: Fix stale codegen when mpgen binary changes
7a72df02e2 type-chrono: Add CustomBuildField/CustomReadField overloads for std::chrono::time_point
45b685c3f5 type-number, type-chrono: Fix static assert signed/unsigned comparisons
45f6255975 type-number: exclude bool from the integral overload
8d6d464948 Merge bitcoin-core/libmultiprocess#315: Fix startup race in example
a6fc80d254 Merge bitcoin-core/libmultiprocess#311: bugfix: clear FD_CLOEXEC in child instead of parent before fork
496fb84e69 test: cover immediate client disconnects for `ListenConnections`
36c6c63520 doc: Document reference-counted EventLoop lifetime
3a997e113c Fix startup race in mpexample
f5c15ce33f Merge bitcoin-core/libmultiprocess#323: refactor: access ThreadContext through CurrentThread(), ci: switch Bitcoin Core to master
66298c737f ci: Switch back to Bitcoin Core's master branch
86b4810501 refactor: access ThreadContext through CurrentThread()
eea9c64f6e cmake: Fix stale codegen when mpgen binary changes
a26a08496b cmake: Fix mpgen capnp tool path for vcpkg/Windows builds
140d9ba6ff test: allow custom log handler in `ListenSetup`
1e0c7ff9a5 util: Clear FD_CLOEXEC in child instead of parent before fork
8550ee6a31 util, refactor: Add ChildFail helper for post-fork child errors
17eab90b52 test: Fix typo in listen_tests.cpp
ce865a9ba8 refactor: Directly use value in CustomBuildField
3f221b5bfd Merge bitcoin-core/libmultiprocess#274: Add nonunix platform support
1b0f605606 doc: Remove trailing whitespace
d8f8ca3119 ipc: Wrap mpgen main() in try-catch to print errors
fbe5a14ad4 ci: Check out bitcoin/bitcoin PR #35084 instead of master
39d3690d83 types: Replace SFINAE with requires clauses to avoid MSVC C2039 error
ba68520203 proxy, refactor: Fix C4305 truncation warning in Accessor on MSVC
1d81d47811 util, refactor: Fix PtrOrValue constructor for move-only types on MSVC
b883fe1e52 proxy: Fix shutdownWrite() exception handling on macOS with dynamic libraries
0012411ccc proxy: Call shutdownWrite() in Connection destructor
38312ad191 proxy, refactor: Change ConnectStream and ServeStream to accept stream objects
e96d5d742a proxy, refactor: Replace EventLoop wakeup fd integers with KJ stream objects
db4f9a3d73 cmake: Bump minimum required Cap'n Proto version to 0.9
652934fb79 util, refactor: Add SocketPair() and use it in SpawnProcess
1c6ef7a26c util, refactor: Do not fork() and exec() separately
1389cf3132 util, refactor: Add SpawnConnectInfo type alias and use it
c7ca1f00b6 util, refactor: Add SocketId type alias and use it
be46a35203 util, refactor: Add ProcessId type alias and use it
91a78db780 doc: Bump version 13 > 14
fa2c56ec27 ci: Bump channel to nixos-26.05

git-subtree-dir: src/ipc/libmultiprocess
git-subtree-split: d0eea62c58928f9660b8dc5541a62ea395c565ef
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.

5 participants