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

bitcoin/bitcoin: PR #35932

Provider refusals

write_verifier: Provider declined the request because of a cybersecurity restriction. Experiments remain incomplete; static verification can continue.

1 major finding · 1 minor finding · 3 suggestions

Earlier concerns neither republished nor resolved: 1 minor finding. See the Run archive for their assessments.

Findings

Link

[major] · Canceling an executing destroy() can deadlock the IPC event loop

Disconnecting during a Context-bearing destroy() can deadlock the worker and event loop, stalling IPC and preventing shutdown; no occurrence has been observed.

Location: src/ipc/libmultiprocess/include/mp/proxy-io.h:904 (head).

Details and suggested fix

For a BlockTemplate.destroy carrying an mp.Context, PassField holds cancel_mutex and installs an m_on_cancel callback that acquires the same mutex on the event-loop thread. Unlike ServerCall, ServerDestroy does not release this lock around invocation. The new invokeDestroy() calls loop->sync() while still holding it. If shutdown or a peer disconnect cancels the request after the callback is installed but before that synchronous call is serviced, the event loop waits for the mutex while the worker waits for the event loop. Neither can reach its cleanup, and every connection on that loop stalls. Give ServerDestroy the same unlock, finally-based relock, and request_canceled check as ServerCall. Add a deterministic test that disconnects between callback installation and servicing the destroy’s synchronous call.


Link

[minor] · Shutdown now re-arms full IPC listeners outside the drain

With a full -ipcbind listener, shutdown now resumes acceptance and can admit an undrained replacement client; a reconnect in this window has not been observed.

Location: src/ipc/capnp/protocol.cpp:138 (head).

Details and suggested fix

With max-connections=1 and one connected client, disconnecting that client during shutdown now runs the listener’s counter decrement through addSyncCleanup, which posts another accept(). Previously, directly erasing the connection canceled its onDisconnect handler and left the full listener disarmed. Connections accepted after the disconnectIncoming() snapshot are not drained, while m_loop_ref keeps the event loop operational. A trusted replacement client can obtain Mining and call getTip() after Shutdown() resets block_template_manager, reaching its null-pointer assertion; retaining the connection can also prevent loop exit. Acceptance below capacity was already possible before this PR. Stop listener acceptance before taking the drain snapshot so the capacity fix cannot admit replacement connections during teardown.


Optional improvements

Link

[suggestion] · The functional shutdown test has no outstanding mining wait

The new functional test covers idle-client exit, but not the shutdown interruption that must release a long-running mining wait before draining can finish.

Location: test/functional/interface_ipc.py:196 (head).

Details and suggested fix

run_shutdown_with_client_connected_test awaits echo.echo(...) before stop_node(), so it does not test shutdown with an outstanding method body. The library drain test releases its synthetic body manually, while the existing mining interruption test calls Mining.interrupt() explicitly. Add a case that starts a long-timeout waitTipChanged or BlockTemplate.waitNext, confirms the request was posted using the existing debug-log pattern, and stops the node without interrupting the object. Require clean process exit within the normal shutdown timeout. Do not require the drain’s waiting log message, since shutdown interruption can finish the body before the connection snapshot.


Link

[suggestion] · onDisconnect comments describe the wrong local-disconnect contract

The comments say explicit disconnect() suppresses onDisconnect, but the shutdown implementation relies on that handler running afterward to free the connection.

Location: src/ipc/libmultiprocess/include/mp/proxy-io.h:637 (head).

Details and suggested fix

The onDisconnect implementation comment says disconnect() expires m_alive, and the surrounding addSyncCleanup and _Serve comments describe the handler as remote-only. Only ~Connection actually resets the token. Explicit disconnect() deliberately preserves it so the handler can later erase or delete the connection, as the new drain test also asserts. Update these comments to distinguish explicit disconnection from direct destruction: the handler runs after a remote disconnect or explicit disconnect(), but is suppressed once the Connection is being destroyed.


Link

[suggestion] · The drain commit message describes obsolete connection ownership

The message names Connection::waitDrained and destruction after waiting, but the commit waits on independent trackers while libmultiprocess frees the connections.

Location: src/ipc/capnp/protocol.cpp:158 at 5c34fe4c4d06 (commit) (commit).

Details and suggested fix

The message for 5c34fe4c4d06a3e05c3b8810f2d2c04adaf58399 says the code waits through Connection::waitDrained and only then destroys the connections. At that commit, with parent selection null, disconnectIncoming() instead collects the trackers returned by disconnect() and calls tracker->waitDrained(). The preceding API commit, e150855d39b6b5c7db1f51a5e9f770dc4dced36a, returns an independent tracker precisely because libmultiprocess may free the connection before draining finishes. Reword the message to describe that ownership and ordering. No code or commit-order change is needed.


Coverage details

Earlier concerns

Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.

Background

Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.

Documented decisions

Disconnecting an IPC connection is not a worker-completion barrier. Historical reports distinguish cancellation of a request’s promise from completion of an already executing C++ body; the server capability may remain alive after its Connection is gone.

The base disconnectIncoming() closes connections without waiting. The affected behavior therefore concerns application-resource lifetime after transport teardown, not merely delivering cancellation to the client. The #35845 discussion specifically explains why waiting for an already queued asynchronous cleanup does not cover executing calls: their ProxyServer destructors have not run and their cleanups have not been queued.

Source 1 · Source 2

The upstream drain API was motivated by a generic resource-release boundary: wait until server objects are no longer in use, rather than requiring each application interface to implement its own shutdown synchronization. Its tracker has a lifetime independent of the Connection.

This explains both the use of live server objects as the drain signal and why disconnectIncoming() retains trackers instead of Connection pointers. The upstream explanation explicitly ties object counting to PassField’s thisCap() pinning and describes the purpose as determining when connection-associated resources may be freed.

Source 1 · Source 2

sync() exists to let threads without an event loop perform event-loop-affine work. Event-loop shutdown ownership must remain with live references: callers must keep the loop running until sync() returns, and new references must descend from an existing live reference rather than resurrecting a stopped loop.

Worker completion and capability release synchronize back to the event loop, so the drain must leave that loop operational. The executor conversion made the caller’s lifetime obligation explicit. The historical discussion also explains why a one-shot shutdown promise is sufficient: with the reference rule, the done condition cannot become false again, including through asynchronous cleanup.

Source 1 · Source 2 · Source 3 · Source 4

The parent connection is deliberately exempt from ordinary incoming-client shutdown because a supervising parent must retain the ability to monitor and control its child during shutdown.

This exception predates the drain and remains in the head implementation. It is a supervisory-liveness requirement, not a promise that all application state remains available to arbitrary parent calls. Draining that still-callable connection would require a distinct rule for stopping new calls.

Source 1

Long-running mining waits rely on cooperative application interruption and condition-variable notification, not on RPC cancellation forcibly interrupting C++ execution. Shutdown notification was extended to Ctrl-C and SIGTERM specifically to avoid waiting for original RPC and IPC timeouts.

The pinned Interrupt() notifies the tip condition variable. waitTipChanged() and waitNext() reach waits whose predicates observe the chainman interrupt flag or explicit per-object interruption. These are the application-level mechanisms expected to let mining waits terminate during shutdown while the drain waits for actual body completion.

Source 1

Explicit destroy is a synchronous implementation-release operation distinct from dropping a capability. Compatibility must account for non-libmultiprocess clients retaining capabilities, issuing later requests, or sending destroy concurrently with other calls; the C++ proxy’s destructor-only usage cannot be assumed for all clients.

The included destroy handling rejects destruction while other requests are queued or executing and rejects later calls. Historical reports identify Python and Rust clients as able to exercise these sequences. The stated threat model is primarily buggy-client robustness: access to the IPC socket already grants powerful unauthenticated RPC access. Ordinary capability release instead follows reference-counted lifetime, including outstanding-call pins.

Source 1 · Source 2

Inherited-method dispatch must be keyed by the wrapped interface handling a call, not solely by the parameter type belonging to the interface that declared it. Cap’n Proto inheritance need not correspond to an equivalent wrapped C++ base-class hierarchy.

The upstream motivation was the stable/unstable Chain interface split, requiring wrapped derived interfaces to inherit from unwrapped bases. The included generator change supplies an interface key and generates mappings for inherited methods. The documented compatibility boundary is a potentially breaking C++ traits-specialization API change, but no wire-protocol change; the upstream proposal states Bitcoin Core master had no affected specializations.

Source 1

Ralph's inferences

The completion ordering comes from layered lifetime protection, not cancellation itself: the stated Cap’n Proto contract retains the target during a call, while libmultiprocess additionally captures thisCap() across worker execution and releases that pin on the event loop after invocation finishes. Consequently, destruction of the counted application ProxyServer implies its worker body has finished, even when cancellation happened earlier.

The pin already exists in the comparison base. The head adds accounting around that lifetime and shares the tracker with server objects that can outlive their Connection. This supports interpreting zero live objects after disconnect as a call-body quiescence signal, without interpreting it as successful response delivery to the disconnected client.

Source 1

The mutex acquisition order and the blocking rule address different deadlock cycles. Waiter::m_mutex precedes EventLoop::m_mutex because clearing thread maps can release event-loop references. Separately, a non-event-loop thread must release the waiter mutex before sync(), because the event loop may need that same mutex before it can service the synchronous request.

These rules explain why teardown extracts or swaps map entries under the waiter lock but destroys their ProxyClient objects after unlocking. They also explain why waiting for drained calls cannot occupy the event-loop thread: worker completion needs to synchronize back to it. The inspected history confirms that earlier lock-order comments had been reversed.

Source 1

The application drain is intentionally narrower than complete IPC shutdown. ProxyServer destruction can schedule implementation destruction on a separate cleanup thread to avoid blocking or deadlocking the event loop, especially if a destructor makes IPC calls. Listener acceptance is also separate from disconnecting the currently enumerated connections.

The tracker reaches zero after ProxyServer destruction, not after deferred m_impl destruction. Event-loop lifetime rules separately retain the loop for pending or executing cleanup. Likewise, the head drain takes trackers for existing non-parent connections but does not stop the listener. Its comments identify these as scope exclusions, so the resulting boundary is call-body completion on selected connections—not completion of every destructor or cessation of every possible incoming call.

Source 1 · Source 2