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

pull ryanofsky wants to merge 13 commits into bitcoin:master from ryanofsky:pr/diswait changing 23 files +922 −254
  1. ryanofsky commented at 2:13 PM on August 7, 2026: 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, included through a src/ipc/libmultiprocess subtree update that also contains bitcoin-core/libmultiprocess#377, which this PR does not need.

    <!-- begin based-on -->

    The non-base commits are:

    Status (2026-11-13)

    This is a draft with no reviews yet. It waits on bitcoin-core/libmultiprocess#361 and bitcoin-core/libmultiprocess#335, both open, and on a subtree update that includes them. Neither has had new reviews since 2026-11-04; bitcoin-core/libmultiprocess#335 still has open review comments from before.

    • Remaining work:
      • Check whether the node may hang at exit when an IPC client is connected at shutdown, since the disconnected connections no longer appear to be destroyed (suspected from the code, not yet reproduced).
      • Add a test that stops the node with a call in progress, and update the code comment and commit message, which describe an earlier version of the change (the comment still says the connections are destroyed and names mp::Connection::waitDrained).
  2. DrahtBot added the label IPC on Aug 7, 2026
  3. DrahtBot commented at 2:13 PM on August 7, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

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

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    Reviews

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

    <!--174a7506f384e20aa4161008e828411d-->

    Conflicts

    Reviewers, this pull request conflicts with the following ones:

    • #36572 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36572.svg"></sub> (ipc: hold event loop references when using it in CapnpProtocol by xyzconstant)
    • #35916 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35916.svg"></sub> (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.

    <!--5faf32d7da4f0f540f40219e4f7537a3-->

  4. DrahtBot added the label CI failed on Aug 7, 2026
  5. DrahtBot commented at 4:14 PM on August 7, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

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

    <details><summary>Hints</summary>

    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.

    </details>

  6. ryanofsky force-pushed on Aug 12, 2026
  7. ryanofsky commented at 8:19 PM on August 12, 2026: contributor

    <!-- begin push-5 -->

    Updated b0c970e305fde426f4aacc8f8d9ea55ea6e8e210 -> 451f5455d6a139f7df2bbcd3f27b5143e9fbc65d (pr/diswait.4 -> pr/diswait.5, compare)<!-- end --> using incoming_connections() accessor for compatibility with https://github.com/bitcoin-core/libmultiprocess/pull/336

    <!-- begin push-6 -->

    Rebased 451f5455d6a139f7df2bbcd3f27b5143e9fbc65d -> 9586480415e21142e06efbc30631ed0ca39afbe2 (pr/diswait.5 -> pr/diswait.6, compare)<!-- end --> onto a libmultiprocess subtree bump (master plus sockinline fixes) fixing subtree (lint job)

    <!-- begin push-7 -->

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

    <!-- begin push-8 -->

    Squashed 222bf56d3160515fc2da9f1473b126b0c64bd384 -> 228ca73a64e14b0478b983a44cda10457f4d65b6 (pr/diswait.7 -> pr/diswait.8, compare)<!-- end --> 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

    <!-- begin push-9 -->

    Rebased 228ca73a64e14b0478b983a44cda10457f4d65b6 -> 01a01e35d9732268e09cfa524c55128389cccfd5 (pr/diswait.8 -> pr/diswait.9, compare)<!-- end --> 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).

  8. ryanofsky force-pushed on Oct 2, 2026
  9. ryanofsky force-pushed on Oct 2, 2026
  10. DrahtBot removed the label CI failed on Oct 2, 2026
  11. DrahtBot added the label Needs rebase on Oct 30, 2026
  12. fanquake referenced this in commit 93bd4e1df4 on Nov 5, 2026
  13. Squashed 'src/ipc/libmultiprocess/' changes from acded1aafae..7f5dabeeec6
    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/bitcoin#36747)
    ebf5d6c1f30 ci: Bump pinned NetBSD releases
    13c600a46bb doc: Bump version 14 > 15
    
    git-subtree-dir: src/ipc/libmultiprocess
    git-subtree-split: 7f5dabeeec67a28c596c16e3fbda995b4deddad6
    a64277877f
  14. Merge commit 'a64277877f44d832cb38147df1ce5e75cc03d609' into subtree-base 0cca27e478
  15. doc: Improve disconnect callback comments
    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).
    8a948e2bdd
  16. doc: Improve Waiter/EventLoop lock order documentation
    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.
    59f703760b
  17. proxy-io: fix listener stuck at capacity after a local disconnect
    Currently, a ListenConnections listener that reaches its max-connection limit
    stops accepting new connections permanently if one of its connections is closed
    locally instead of by a remote disconnect. Closing a connection locally (e.g.
    erasing it from m_incoming_connections) leaves the listener's active-connection
    count stuck at the limit, so it never resumes accepting.
    
    This happens because the count is decremented by a callback which only fires on
    a remote disconnects, not local disconnects. Fix by moving the decrement to
    callback which fires on both local and remote disconnects.
    
    Add a regression test that closes a connection locally and checks the listener
    resumes accepting; it fails before this change (the listener never accepts the
    waiting client) and passes after.
    
    Co-Authored-By: Enoch Azariah <enirox001@gmail.com>
    This change was written with Claude Opus 4.8 (1M context).
    98533b0201
  18. proxy-io: fix race deleting a disconnected Connection twice
    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
    https://github.com/bitcoin-core/libmultiprocess/pull/335#discussion_r3821831654
    
    Give each Connection a shared_ptr "alive" token that disconnect handlers hold
    a weak_ptr to and check before running, so a handler is skipped once its
    Connection is gone. Having this check also enables the simplifications
    described below.
    
    Previously each Connection kept its disconnect handlers in its own
    kj::TaskSet, and when the network disconnected it moved a handler onto the
    shared event loop TaskSet with kj::evalLater. Destroying the Connection
    destroyed that per-connection TaskSet, canceling a still-pending handler --
    but a handler already moved onto the shared TaskSet was no longer canceled
    and could run after the Connection was gone. (The evalLater step existed only
    to avoid a "promise callback destroyed itself" error when a handler deletes
    its own Connection, which the per-connection TaskSet made possible.)
    
    With the token doing the cancellation, neither the per-connection TaskSet nor
    the evalLater step is needed, and both are removed.
    
    Co-Authored-By: Enoch Azariah <enirox001@gmail.com>
    This change was written with Claude Fable 5.
    0b1730bad1
  19. proxy: Fix thread map teardown race causing use-after-free on disconnect
    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.
    789775cb46
  20. proxy-io: add Connection::disconnect() separating teardown from destruction
    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.
    
    Having a separate disconnect() method allows severing a connection while
    keeping the Connection object alive, which the next commits use to let
    shutdown code wait for in-flight server call bodies to finish after a
    disconnect (bitcoin/bitcoin#35845). Two details are new in the disconnect()
    method which were not present in the destructor method:
    
    - disconnect() expires the m_alive token explicitly, where previously it was
      expired implicitly by member destruction. This keeps onRemoteDisconnect able
      to distinguish a local disconnect from a remote one when a connection is
      severed without destroying the object (see the disconnect() code comment).
    
    - disconnect() explicitly releases m_thread_pool and m_thread_map so worker
      thread teardown happens at disconnect time whether or not the object is
      destroyed right away. Previously this happened implicitly during member
      destruction.
    
    This change was written with Claude Fable 5.
    580d9644a7
  21. proxy-io: add Connection::waitDrained() to wait for in-flight server calls
    Add a per-connection ServerObjectTracker counting live ProxyServer objects,
    incremented in the ProxyServerBase constructor and decremented in its
    destructor, with Connection::waitDrained() blocking until the count reaches
    zero and Connection::pendingServerObjects() exposing it 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. Counting live server objects turns Cap'n Proto's object lifetime
    rules into a usable quiescence signal: a ProxyServer object is not destroyed
    until its outstanding calls finish (the target capability is kept alive for
    the duration of a call and pinned by post()/PassField via thisCap()), so
    after disconnect() the count drains to zero exactly when no server call body
    is still executing. Waiting for that lets shutdown code avoid freeing
    application state that a still-running call body dereferences
    (bitcoin/bitcoin#35845).
    
    The tracker is held via shared_ptr by the Connection and by every
    ProxyServer object because objects kept alive by in-flight calls can outlive
    the Connection on some teardown paths (see ~ProxyServerBase), and their
    destructors must decrement state that is still valid. It must be declared
    before m_rpc_system, whose construction creates the bootstrap server object
    that registers itself with the tracker.
    
    This change was written with Claude Fable 5.
    bb588048d1
  22. test: cover draining in-flight server call after disconnect
    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 assert that Connection::waitDrained() blocks
    until the body finishes and its server object is destroyed. Also covers
    destroying an already-disconnected connection (~Connection noticing
    disconnect() has run).
    
    This change was written with Claude Fable 5.
    Co-Authored-By: Enoch Azariah <enirox001@gmail.com>
    0ad96a7fab
  23. ipc: use ServeStream/ConnectStream in Bitcoin Core IPC code
    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.
    d9ffa65529
  24. ipc: drain in-flight server calls before shutdown frees node state
    Fix bitcoin/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.
    dc293af2f4
  25. lint: Skip subtree check for src/ipc/libmultiprocess
    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.
    01a01e35d9
  26. ryanofsky force-pushed on Nov 13, 2026
  27. DrahtBot removed the label Needs rebase on Nov 13, 2026

github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-11-24 00:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me