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 · 4 suggestions

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

Findings

Link

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

Canceling an mp.Context destroy() between callback installation and its implementation-handoff sync() can deadlock the worker and event loop, hanging IPC and shutdown; no occurrence has been observed.

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

Details and suggested fix

BlockTemplate.destroy carries a Proxy.Context, so dispatch installs m_on_cancel while the worker holds cancel_mutex. Unlike ServerCall, ServerDestroy does not release that mutex around invokeDestroy(). The new implementation then blocks in EventLoop::sync() to move m_impl on the event-loop thread. If a client disconnect or shutdown cancellation runs before that callback, the event loop waits for cancel_mutex in m_on_cancel, while the worker waits for the event loop. Neither can reach cleanup. Give ServerDestroy the same unlock/relock and cancellation handling as ServerCall, and test cancellation after m_on_cancel is installed but before the handoff callback runs.


Link

[minor] · Shutdown can restart a full IPC listener and admit an undrained client

With a full -ipcbind listener and a queued client, local shutdown disconnection can restart acceptance after the drain snapshot and delay exit until that client disconnects; no current workload producing this shutdown condition was identified.

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

Details and suggested fix

When disconnectIncoming() closes a connection on a listener at its max_connections limit, the newly registered synchronous cleanup releases the slot and calls _Listen() again. A queued client's accept can complete on a later event-loop turn, outside the collected trackers. If accepted before protocol destruction releases its external loop reference, the new Connection holds an EventLoopRef and makes ~CapnpProtocol() wait until that client disconnects. At base, local destruction canceled the callback containing the slot release, so a full listener stayed stopped; listeners below capacity already had this acceptance window. Stop listener admission, including slot-release resumption, before collecting the shutdown connections. Add coverage with max_connections=1, one accepted client, and one queued client.


Optional improvements

Link

[suggestion] · The new tests do not exercise the protocol-level drain wait

The functional test stops with an idle client, while the library test waits on the tracker directly; neither checks that CapnpProtocol::disconnectIncoming() waits for a running call body.

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

Details and suggested fix

run_shutdown_with_client_connected_test() awaits echo.echo() before calling stop_node(). The library regression holds a body in flight, but calls Connection::disconnect() and ServerObjectTracker::waitDrained() itself. Removing the wait loop from CapnpProtocol::disconnectIncoming() would leave both tests' assertions unchanged. Add a deterministic protocol test with a fake Echo implementation blocked on a promise: start the call, invoke disconnectIncoming() on another thread, verify it remains blocked, then release the body and verify the drain returns. This tests the integration independently of the existing idle-connection shutdown coverage.


Link

[suggestion] · onDisconnect() documents the wrong local-disconnect behavior

The comments say disconnect() expires m_alive and suppresses handlers, but it deliberately preserves the token so handlers free the connection; only destruction expires it.

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

Details and suggested fix

onDisconnect() says its handler runs only after a remote disconnect, and its inline explanation says disconnect() expires the liveness token. addSyncCleanup() and _Serve() repeat that distinction. However, Connection::disconnect() explicitly leaves m_alive set so the handler removes the connection on a later event-loop turn, while ~Connection() resets it. Update these comments to distinguish explicit disconnection from destruction: handlers can run after either a remote disconnect or disconnect(), but must not run after destruction.


Link

[suggestion] · The onDisconnect() regression test misses the expired-token guard

The test runs the handler before deferred connection destruction, so removing the alive.expired() guard would leave its assertions unchanged.

Location: src/ipc/libmultiprocess/test/mp/test/test.cpp:919 (head).

Details and suggested fix

The first continuation queues server_conn.reset() through kj::evalLater, while the current onDisconnect() continuation calls f() directly. The handler therefore runs with a live token before destruction, as required by the test's handler_ran assertion. This catches the old deferred-handler ordering bug, but not the guard that now prevents callbacks after destruction. Add a case that destroys the Connection synchronously in an earlier continuation and asserts that the later handler is skipped. Hold an independent EventLoopRef until that observation completes so loop shutdown cannot hide a missing guard.


Link

[suggestion] · The commit messages describe a stale drain and ownership sequence

5c34fe4 describes a nonexistent Connection::waitDrained() and an explicit destruction step, obscuring the ownership dependency; 3e1518c also describes already-existing helpers as newly added.

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

Details and suggested fix

In 5c34fe4c4d06a3e05c3b8810f2d2c04adaf58399, disconnectIncoming() collects trackers inside sync() and waits on them outside it. It does not explicitly erase or destroy connections. Reword the message to name ServerObjectTracker::waitDrained() and explain that automatic removal relies on disconnect() preserving m_alive, introduced by d5453f7cf185f4a784194fbdf482b0d78b36862b. Also describe the helpers used by 3e1518c9dea7bb7ced84294e1f61c09e062c8d6b as existing upstream helpers: comparison-base protocol.cpp already calls both ServeStream() and ConnectStream(). These are message corrections only; 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

Event-loop lifetime accounting historically protected both active users and unfinished cleanup, including the final cross-thread wakeup. Shutdown was not meant to occur merely because an application client disappeared.

Libmultiprocess #129 traced broken-pipe shutdown failures to insufficient synchronization of the reference count and cleanup queue, and to extra wakeups allowing premature loop exit. At the pinned base, sync() consequently holds a temporary EventLoopRef throughout scheduling and callback completion, while done() requires zero references and an empty async-cleanup queue. This is the lifetime guarantee underlying the later scheduling replacement.

Source 1

The sync()/executeSync evolution sought cheaper cross-thread dispatch without changing the requirement that a synchronous callback finish before its caller resumes; loop lifetime ownership became an explicit caller obligation.

Libmultiprocess #347 justified borrowing a FunctionParam because sync() waits until the event-loop callback finishes, avoiding ownership requirements and a heap allocation. #376 then replaced the custom pipe scheduler with KJ's existing executor and a separate shutdown fulfiller. Its discussion explicitly required callers to keep loop() from returning until sync() returns, normally through an EventLoopRef. The pinned head reflects this: sync() no longer acquires its own temporary reference. The same discussion explains the one-shot shutdown rule: new references must arise from code already protected by a reference, so zero references plus no pending cleanup is terminal rather than a state from which the loop may be revived.

Source 1 · Source 2 · Source 3 · Source 4 · Source 5 · Source 6

Cancellation support had to accommodate asynchronous clients that do not obey the blocking C++ client's RAII sequencing. Canceling an RPC promise is distinct from completing an already-dispatched C++ call body.

Libmultiprocess #240 explicitly addressed asynchronous requests and unclean disconnects from Rust and Python clients that were difficult to trigger through the C++ interface. The later #35845 diagnosis distinguishes currently executing requests from objects whose cleanup is already queued: executing requests keep their ProxyServer alive, so a barrier on the existing cleanup queue does not wait for them. At the pinned head, cancellation records request state, avoids executing a request canceled before invocation, and safely discards canceled results; it does not forcibly interrupt application code already running.

Source 1 · Source 2 · Source 3

The drain operation's purpose is resource quiescence, not merely transport closure or an empty request queue. Counting retained server objects uses the existing call-lifetime ownership to establish that quiescence.

In libmultiprocess #335, the author explains that waitDrained waits for both calls and object release, and explicitly identifies PassField's thisCap retention as the basis for counting objects instead of calls directly. In the pinned implementation, mp.Context dispatch retains the application ProxyServer across worker execution, while Thread::post separately retains the worker capability until result delivery. Disconnect releases ordinary RPC ownership but cannot erase these call-held references. Constructors register before teardown on the event-loop thread, and destructors decrement the shared tracker only after server-wrapper cleanup. Thus, for the disconnected connections being tracked, zero means no retained application call body remains. The counter is an object count, not a call count, and its shared ownership lets it survive Connection destruction.

Source 1 · Source 2

Explicit destroy() exists to provide synchronous implementation destruction, whereas dropping a capability lets reference-counted lifetime management defer destruction until outstanding calls finish. Retaining the wrapper capability alone must not permit explicit destroy() to free an implementation underneath another call.

Libmultiprocess #382 documents why the C++ client's destructor-only use of destroy was insufficient as a server assumption: other clients can retain a capability, call after destroy, or send destroy concurrently with another request. Its resolution rejects destroy during active requests and rejects later method calls. The pinned head counts queued and executing mp.Context requests and performs the ownership transition on the event-loop thread. This is a separate protection for m_impl lifetime from the server-wrapper retention used by draining. Issue #378 frames the concern primarily as buggy external clients: a client able to access the IPC socket already has unauthenticated RPC access under the stated trust model.

Source 1 · Source 2

The parent connection is intentionally treated as a process-control channel that remains available during shutdown, rather than as an ordinary incoming client connection to be disconnected.

The proposed shutdown correction in #33387 preserved the existing explanation that a parent must be able to monitor and control the child even during shutdown. Both pinned base and head retain that exception. The head's drain therefore concerns the non-parent connections it disconnects, not every capability or call in the process.

Source 1

Ralph's inferences

The drain must leave the event loop running while waiting: worker completion itself requires event-loop service, and worker destruction may also require deferred joining.

The pinned Thread::post delivers results through sync() and defers releasing its last self-reference to a later event-loop turn because its destructor joins the worker. Blocking that loop while waiting would prevent the completion being awaited. The head accordingly disconnects inside sync(), then waits on trackers outside it. Worker and application ProxyServer references provide lifetime ownership while this completion work proceeds; Thread and ThreadMap need not themselves be included in the application-object counter.

Excluding asynchronous implementation destructors preserves a distinction between call-body quiescence and full implementation-resource teardown; it is not a claim that destructors are necessarily harmless.

Already at the pinned base, ProxyServer destruction schedules m_impl destruction off the event loop because user destructors can block or make IPC calls and otherwise deadlock the loop. The head decrements the tracker after scheduling that cleanup, not after it executes, and explicitly limits this drain to call bodies. Overall EventLoop shutdown still accounts for queued and executing async cleanup and joins the cleanup thread. The narrow drain therefore does not replace that later lifecycle barrier or establish that arbitrary destructor accesses have finished.

Continuing listener accepts and retaining the parent connection make this a connection-scoped drain, not a global shutdown admission barrier. Their exclusion is a scope boundary rather than a protocol requirement that shutdown must accept fresh work.

The head explicitly says stopping new accepts requires additional listener control, and draining the still-open parent would require pausing new calls on it. The inspected listener API returns no stop handle: it recursively posts accepts, can resume after capacity becomes available, and is ultimately canceled with the event-loop task set. Historical #269 addresses capacity management, not shutdown admission. Consequently, tracker zero describes only the selected disconnected connections; extending that statement to all future IPC work would require evidence not provided by this drain.

Source 1