Skip to content

ipc: make ipc::disconnectIncoming wait for in-progress calls to complete - #35932

Draft
ryanofsky wants to merge 15 commits into
bitcoin:masterfrom
ryanofsky:pr/diswait
Draft

ryanofsky wants to merge 15 commits into
bitcoin:masterfrom
ryanofsky:pr/diswait

Conversation

@ryanofsky

@ryanofsky ryanofsky commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

This fixes an antithesis bug reported in #35845 and similar bug reported in #33387 where if asynchronous IPC mining calls are made when the node is shutting down it's possible for assert(m_node.chainman) to trigger. This happens because the Ipc::disconnectIncoming method does not wait for asynchronous calls to complete after it disconnects IPC clients, so they may continue to run as the node is shutting down.

This PR changes disconnectIncoming to wait for asynchronous calls to complete to avoid this issue. It's a draft because it depends on libmultiprocess changes, but should otherwise be ready to review.

This is based on bitcoin-core/libmultiprocess#361 and bitcoin-core/libmultiprocess#335, and also includes a src/ipc/libmultiprocess subtree update. The non-base commits to review are:

Status (2026-11-23)

This is a draft because it waits on bitcoin-core/libmultiprocess#361 and bitcoin-core/libmultiprocess#335 and a subtree update that includes them. This push fixes a shutdown hang the previous version had: if an IPC client was still connected at shutdown, the disconnected connections stayed in the incoming connection list and kept the IPC event loop running, so the node never exited. bitcoin-core/libmultiprocess#335 now frees connections after disconnect(), this PR waits on the trackers disconnect() returns, and a new functional test stops the node with a client connected.

@DrahtBot DrahtBot added the IPC label Aug 7, 2026
@DrahtBot

DrahtBot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

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

External sites

Reviews

See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #37009 (ipc: stop listeners in CapnpProtocol::disconnectIncoming() by mutatrum)
  • #36572 (ipc: hold event loop references when using it in CapnpProtocol by nullfail)
  • #35916 (fuzz: improve ipc fuzz coverage by enochaz)

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.

@DrahtBot

DrahtBot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task lint: https://github.com/bitcoin/bitcoin/actions/runs/31186529513/job/92892361418
LLM reason (✨ experimental): CI failed due to the lint “subtree” check detecting a subtree directory change without a corresponding subtree merge.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@ryanofsky

ryanofsky commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Updated b0c970e -> 451f545 (pr/diswait.4 -> pr/diswait.5, compare) using incoming_connections() accessor for compatibility with bitcoin-core/libmultiprocess#336

Rebased 451f545 -> 9586480 (pr/diswait.5 -> pr/diswait.6, compare) onto a libmultiprocess subtree bump (master plus sockinline fixes) fixing subtree (lint job)

Added 1 commits 9586480 -> 222bf56 (pr/diswait.6 -> pr/diswait.7, compare) restoring the commit that skips the subtree lint check, which this PR still needs because it includes libmultiprocess changes (lint job)

Squashed 222bf56 -> 228ca73 (pr/diswait.7 -> pr/diswait.8, compare) moving the "ipc: use ServeStream/ConnectStream/incomingConnections in Bitcoin Core IPC code" commit after the commits adding those helpers, so every commit builds (test ancestor commits job); no changes to the final code

Rebased 228ca73 -> 01a01e3 (pr/diswait.8 -> pr/diswait.9, compare) due to conflicts with #36747 and #36682. Drops the four ConnectStream/ServeStream commits and the -Wc++23-lambda-attributes build fix, which reached master in #36747 (the ConnectStream/ServeStream commits as bitcoin-core/libmultiprocess#365).

Updated 01a01e3 -> 74730ac (pr/diswait.9 -> pr/diswait.10, compare) updating the bitcoin-core/libmultiprocess#361 and bitcoin-core/libmultiprocess#335 commits to pr/ondis.6 and pr/keepconn.9, and fixing a shutdown hang when an IPC client is still connected (reported by enochaz in bitcoin-core/libmultiprocess#336 (review)) by waiting on the trackers disconnect() now returns, with a new functional test

@ryanofsky
ryanofsky force-pushed the pr/diswait branch 2 times, most recently from 222bf56 to 228ca73 Compare October 2, 2026 04:12
@DrahtBot DrahtBot removed the CI failed label Oct 2, 2026
fanquake added a commit that referenced this pull request Nov 5, 2026
…support and fix race conditions

d5f7524 doc: Bump minimum required Cap'n Proto version to 0.9.2 (Ryan Ofsky)
4898199 build: suppress -Wc++23-lambda-attributes in warn_interface (Ryan Ofsky)
270f5db Squashed 'src/ipc/libmultiprocess/' changes from e8de5c7..acded1aafae (Ryan Ofsky)

Pull request description:

  The changes can be verified by running `test/lint/git-subtree-check.sh src/ipc/libmultiprocess` as described in [developer notes](https://github.com/bitcoin/bitcoin/blob/master/doc/developer-notes.md#subtrees) and [lint instructions](https://github.com/bitcoin/bitcoin/tree/master/test/lint#git-subtree-checksh).

  Changes since last subtree update (#35720):

  - Adds support for nonunix platforms, making API changes that are not backwards compatible ([#274](bitcoin-core/libmultiprocess#274)). Follow-ups add a `CurrentThread()` accessor matching compatibility code in [#35084](#35084) ([#323](bitcoin-core/libmultiprocess#323)) and remove code for Cap'n Proto versions before 0.9 ([#331](bitcoin-core/libmultiprocess#331)).
  - Fixes a data race between IPC calls running on worker threads and disconnects, found by Antithesis ([#349](bitcoin-core/libmultiprocess#349)).
  - Fixes a use-after-free when a socket disconnects before `ConnectStream` connects, and leaks and hangs when a client `construct()` call throws ([#298](bitcoin-core/libmultiprocess#298)).
  - Fixes a race where file descriptors from `SpawnProcess` could leak into processes forked at the same time by other threads, by clearing `FD_CLOEXEC` in the child after forking ([#311](bitcoin-core/libmultiprocess#311)).
  - Makes `SpawnProcess` report `exec` failures back to the parent and throw, reaping the child ([#312](bitcoin-core/libmultiprocess#312)).
  - Adds support for `std::chrono::time_point` fields ([#303](bitcoin-core/libmultiprocess#303)) and for serializing lists of interface objects that need to be moved from ([#304](bitcoin-core/libmultiprocess#304)), both needed by [#10102](#10102).
  - Accepts container fields and parameters with any comparator, hash, and allocator types, like Bitcoin Core's `GCSFilter::ElementSet`, needed by [#29409](#29409) ([#379](bitcoin-core/libmultiprocess#379)).
  - Finds the `capnp` tool in vcpkg and Windows builds, needed by [#32387](#32387) ([#317](bitcoin-core/libmultiprocess#317)).
  - Adds a `destroy_connection` option to `ServeStream` and `ConnectStream`, lets `ServeStream` take ownership of the init object and return the new server and its connection, and adds an `EventLoop::incomingConnections()` accessor, simplifying test setup in both repositories and needed by [#35932](#35932) ([#365](bitcoin-core/libmultiprocess#365)).
  - Replaces `EventLoop::post()` with `sync()` taking a `kj::FunctionParam`, avoiding a heap allocation per call ([#347](bitcoin-core/libmultiprocess#347)).
  - Names threads spawned by the event loop so they can be told apart in tools and logs ([#324](bitcoin-core/libmultiprocess#324)).
  - Fixes warnings that Bitcoin Core enables or plans to enable: adds `[[noreturn]]` attributes for `-Wmissing-noreturn` ([#339](bitcoin-core/libmultiprocess#339), for [#35911](#35911)), and fixes `-Wunused` ([#362](bitcoin-core/libmultiprocess#362), for [#36167](#36167)), `-Wunused-const-variable` and `-Wundef` ([#370](bitcoin-core/libmultiprocess#370)), and `-Wmissing-prototypes` ([#386](bitcoin-core/libmultiprocess#386), for [#36743](#36743)) warnings.
  - Fails at compile time with a suggested workaround when Cap'n Proto misdetects exception support (`KJ_NO_EXCEPTIONS`), as happens on NetBSD ([#364](bitcoin-core/libmultiprocess#364)).
  - Build improvements: fixes stale generated code when the `mpgen` binary changes ([#316](bitcoin-core/libmultiprocess#316)), fixes `mpgen` link order for static Cap'n Proto builds ([#367](bitcoin-core/libmultiprocess#367)), links `mpgen` against `kj-async` instead of `capnp-rpc` ([#327](bitcoin-core/libmultiprocess#327)), shows Cap'n Proto `find_package` diagnostics ([#325](bitcoin-core/libmultiprocess#325)), installs `type-unordered-set.h` and `version.h` ([#350](bitcoin-core/libmultiprocess#350)), and shows include-what-you-use errors instead of failing silently ([#371](bitcoin-core/libmultiprocess#371)).
  - Test, CI, documentation, and minor code improvements: fix for a startup race in the example program ([#315](bitcoin-core/libmultiprocess#315)), new test for immediate client disconnects in `ListenConnections` ([#310](bitcoin-core/libmultiprocess#310)), `ReadList` return value check ([#338](bitcoin-core/libmultiprocess#338)), connect test race fix ([#343](bitcoin-core/libmultiprocess#343)) and cleanups ([#344](bitcoin-core/libmultiprocess#344)), `std::ranges::copy` follow-ups ([#307](bitcoin-core/libmultiprocess#307)), trailing whitespace removal ([#345](bitcoin-core/libmultiprocess#345)), Cap'n Proto version documentation fix ([#357](bitcoin-core/libmultiprocess#357)), clang-tidy updates ([#358](bitcoin-core/libmultiprocess#358), [#360](bitcoin-core/libmultiprocess#360), [#380](bitcoin-core/libmultiprocess#380), [#389](bitcoin-core/libmultiprocess#389)), new CI job testing newer cmake and Cap'n Proto versions ([#212](bitcoin-core/libmultiprocess#212), [#359](bitcoin-core/libmultiprocess#359)), CI coverage for the minimum supported g++ ([#330](bitcoin-core/libmultiprocess#330), [#366](bitcoin-core/libmultiprocess#366)), new CI warnings ([#332](bitcoin-core/libmultiprocess#332), [#341](bitcoin-core/libmultiprocess#341)), CI parallelism ([#334](bitcoin-core/libmultiprocess#334), [#356](bitcoin-core/libmultiprocess#356)), CI diagnostics ([#351](bitcoin-core/libmultiprocess#351), [#352](bitcoin-core/libmultiprocess#352)), Nix and LLVM updates ([#296](bitcoin-core/libmultiprocess#296), [#363](bitcoin-core/libmultiprocess#363)), NetBSD and OpenBSD CI fixes ([#321](bitcoin-core/libmultiprocess#321), [#340](bitcoin-core/libmultiprocess#340), [#381](bitcoin-core/libmultiprocess#381)), building Cap'n Proto with GCC in the 32-bit CI job to avoid an ABI mismatch ([#383](bitcoin-core/libmultiprocess#383)), and GitHub Actions updates ([#387](bitcoin-core/libmultiprocess#387)).

  The second commit suppresses the clang `-Wc++23-lambda-attributes` warning, which the new `[[noreturn]]` lambda attribute in `mp/proxy-types.h` triggers in C++20 builds. Since #31507 the Windows build uses clang-cl, so the same flag covers it.

  The third commit updates the minimum Cap'n Proto version in `doc/dependencies.md` to 0.9.2 (1.0 with Clang). This update raises libmultiprocess's own minimum from 0.7 to 0.9 (bitcoin-core/libmultiprocess#331), and libmultiprocess rejects 0.9.0 and 0.9.1 for CVE-2022-46149 and, with Clang 16 or newer, every version before 1.0.

ACKs for top commit:
  fanquake:
    ACK d5f7524
  willcl-ark:
    ACK d5f7524

Tree-SHA512: 4064944f4d8bb6c1665ddc7d5fae838492235d7dfdafab88b19b687ff6892460a3f450b90a145b287866330c569b862d748c941a70c65abc7f273ef13e490fd7
…eec6

7f5dabeeec6 mpgen: Key ProxyMethod and method traits by interface type
3c74d87f301 Merge bitcoin-core/libmultiprocess#376: event-loop: replace pipe-based sync call scheduling with `kj::Executor::executeSync`
174419a5dd1 loop: replace pipe-based sync call scheduling with kj::Executor::executeSync
e244e29a288 Merge bitcoin-core/libmultiprocess#382: proxy-server: Reject `destroy()` during active calls and calls after `destroy()`
42fa11ef802 proxy: Reject destroy() during active calls and calls after destroy()
2ed6f4b3396 Merge bitcoin-core/libmultiprocess#391: ci: Bump pinned NetBSD releases
e67325661d2 Merge bitcoin-core/libmultiprocess#388: doc: Bump version 14 > 15 (merge right after bitcoin#36747)
ebf5d6c1f30 ci: Bump pinned NetBSD releases
13c600a46bb doc: Bump version 14 > 15

git-subtree-dir: src/ipc/libmultiprocess
git-subtree-split: 7f5dabeeec67a28c596c16e3fbda995b4deddad6
ryanofsky and others added 13 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/libmultiprocess#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 <[email protected]>
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/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.
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#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.
…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#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#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 <[email protected]>
This change was written with Claude Opus 5.5.
Replace manual Connection construction in protocol.cpp, ipc_tests.cpp,
and fuzz/ipc.cpp with the ServeStream/ConnectStream helpers added in
preceding commits. None of these call sites need anything the helpers
don't already provide: destroy_connection defaults to true. protocol.cpp
sets m_parent_connection from the connection ServeStream returns, and the
test and fuzz code ignore the return value.

This change was written with Claude Sonnet 5.
Fix bitcoin#35845, an assertion failure in MinerImpl::chainman()
during shutdown of an IPC-mining node.

Shutdown() calls disconnectIncoming() before node.chainman.reset().
Disconnecting cancels the KJ promise of an in-flight IPC server call, but a
C++ server method body already dispatched to a libmultiprocess worker thread
is not interrupted and runs to completion. A still-running body (an in-flight
Mining.checkBlock) could then dereference m_node.chainman after
chainman.reset() nulled it, aborting on Assert(m_node.chainman).

Make disconnectIncoming() disconnect the non-parent incoming connections,
wait off the event loop thread for their in-flight server call bodies to
finish (Connection::waitDrained), and only then destroy them and return, so
Shutdown() frees node state only once no server code is running. Log when
the wait actually blocks so a shutdown hang here is diagnosable.

No wait is needed for calls parked in waitTipChanged()/waitNext():
Interrupt() runs before Shutdown() and notifies m_tip_block_cv after setting
the shutdown signal, so those return before disconnectIncoming() runs.

Intentional limitations, to keep the fix narrow: m_impl destructors
scheduled on the async cleanup thread are not waited for, the kept-open
parent connection is not drained, and new incoming connections can still be
accepted during shutdown (preventing that needs a listener API, proposed in
bitcoin-core/libmultiprocess#269).

This change was written with Claude Fable 5.
WARNING: DO NOT MERGE — this draft PR modifies the libmultiprocess
subtree directly (intentionally, for testing purposes) which causes
the subtree link check to fail. Disabling the check here to avoid
masking unrelated lint failures while the PR is open for testing.

Restore the omitted entry before any merge attempt.

Note: removing src/ipc/libmultiprocess from get_subtrees() also removes
it from get_pathspecs_default_excludes(), so all other lint checks
(trailing newline, whitespace, etc.) now run on files in that directory
as well. This is why src/ipc/libmultiprocess/include/mp/type-unordered-set.h
needs a trailing newline added here even though it is not otherwise
modified by this PR: it has always been missing the newline, but was
previously hidden from the lint check by the subtree exclusion.

This change was written with Claude Sonnet 4.6.
Needed due to base PR, can be dropped before merge
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants