Skip to content

proxy: Fix deadlocks and a data race in server methods running on worker threads - #405

Open
ryanofsky wants to merge 5 commits into
bitcoin-core:masterfrom
ryanofsky:pr/reqlock
Open

ryanofsky wants to merge 5 commits into
bitcoin-core:masterfrom
ryanofsky:pr/reqlock

Conversation

@ryanofsky

Copy link
Copy Markdown
Collaborator

Problem: A server method running on a worker thread holds its request's cancel_lock except while the method itself runs, and the event loop thread locks the same mutex in on_cancel when the request is canceled. Two places wait for the event loop thread with the lock held, so a client that disconnects at the wrong moment deadlocks the event loop thread and the worker, and the process stops handling IPC:

  • destroy() calls running on worker threads call invokeDestroy() with the lock held, and since #382 invokeDestroy() calls EventLoop::sync(). Triggering it needs a client that sends destroy() and disconnects before the server calls sync(). Bitcoin Core's BlockTemplate.destroy and Echo.destroy run this way, but Bitcoin Core's subtree does not include #382 yet, so this should be merged before the next subtree update.
  • Temporary ProxyClient objects for interface and callback parameters are destroyed after the method returns, with the lock held, and their destructors call the remote destroy() method and EventLoop::sync(). A client that receives the destroy() call and disconnects instead of responding deadlocks the server.

Separately, server methods read their parameters on the worker thread, and reading an interface or callback parameter adds a reference to its Cap'n Proto ClientHook, whose reference count is not atomic. The event loop thread updates the same count when another message refers to the capability, when it is released, and when the connection is closed, so this is a data race that could free the ClientHook while it is still in use.

Bitcoin Core interfaces do not have interface or callback parameters yet, so only the first deadlock could affect Bitcoin Core, after the next subtree update. All three were reported privately by tcp-raw (request lock deadlocks, capability parameters read on worker threads).

Solution:

  • Add a ServerInvokeContext::unlocked() helper, moved out of ServerCall, that calls a function with cancel_lock released, reacquires it, and throws InterruptException if the request was canceled meanwhile. Call invokeDestroy() and destroy parameters through it.
  • Make EventLoop::sync() assert that the calling thread does not hold the cancel_lock of a request it is executing. With it, the existing callback tests fail on every run without either deadlock fix, so this check is the test: deadlocks like these need a disconnect at a specific moment, which tests would not otherwise hit.
  • Add a GetCapability() function that reads capabilities on the event loop thread through a new virtual InvokeContext::syncUnlocked() method, which ServerInvokeContext overrides to release cancel_lock while waiting and to skip the read if the request was canceled. Use it wherever parameters are read as interfaces or callbacks, including capability lists in ReadList.

The first two commits fix the destroy() regression from #382, in case it is better to merge them separately.

Move the code that releases cancel_lock while a server method runs, and
reacquires it and checks for cancellation afterwards, from ServerCall into a
ServerInvokeContext::unlocked() method, so the next commits can run other code
the same way.

No change in behavior.

This change was written with Claude Opus 5.5.
Make ServerDestroy release cancel_lock while calling invokeDestroy(), the same
way ServerCall has released it while calling IPC methods since cancel_lock was
added in 0174450 from bitcoin-core#240. This fixes a deadlock when a client
disconnects while its destroy() call is running on a worker thread.

ServerDestroy holding the lock did not matter until 42fa11e from bitcoin-core#382
made invokeDestroy() call EventLoop::sync(). The event loop thread locks the
same mutex in on_cancel when a request is canceled, so if the client
disconnects after the worker locked cancel_lock and before sync() runs, each
thread waits for the other and the process stops handling IPC.

Triggering it requires a client that sends destroy() and disconnects without
waiting for the response, which a libmultiprocess C++ client does not do
unless its process is killed. Bitcoin Core's BlockTemplate and Echo destroy()
methods run on worker threads, but its libmultiprocess subtree does not
include bitcoin-core#382 yet.

This was reported privately by tcp-raw.

This change was written with Claude Opus 5.5.
Make PassField destroy server method parameters with cancel_lock released, the
same way ServerCall runs the method itself. This fixes a deadlock when a client
disconnects while the server is destroying an interface or callback parameter
passed to a method running on a worker thread.

The bug has been present since cancel_lock was added in 0174450 from
bitcoin-core#240. A ProxyClient object created for an interface or callback parameter is
destroyed after the method returns, after ServerCall reacquired cancel_lock,
and ~ProxyClientBase calls the remote destroy() method, if the interface has
one, and then EventLoop::sync(), both of which wait for the event loop thread.
The event loop thread locks the same mutex in on_cancel when the request is
canceled, so a client that receives the destroy() call and disconnects instead
of responding makes each thread wait for the other.

Bitcoin Core interfaces do not have parameters like this yet, but the callback
tests here do.

This was reported privately by tcp-raw.

This change was written with Claude Opus 5.5.
Make EventLoop::sync() assert that the calling thread does not hold the
cancel_lock of a request it is executing, because the event loop thread locks
the same mutex in on_cancel if the request is canceled, so waiting for the
event loop thread while holding it can deadlock.

Deadlocks like the ones fixed in the previous two commits need a disconnect
at a specific moment, so tests do not find them. With this check, the
existing callback tests fail on every run without either fix.

Keep a pointer to the lock in ThreadContext::request_lock while the request
runs, restoring the previous value afterwards, because a request can be
handled on a thread that is executing another request and waiting for a
response from the same client.

This change was written with Claude Opus 5.5.
Add a GetCapability() function that reads capabilities on the event loop
thread, and use it wherever server methods read interface or callback
parameters. This fixes a data race in server methods running on worker
threads that take parameters like these.

The race has been present since the first libmultiprocess commit: server
methods read their parameters on the worker thread, and reading a capability
from a Cap'n Proto message adds a reference to its ClientHook, whose
reference count is not atomic. The event loop thread updates the same count
when other messages refer to the capability, when it is released, and when
the connection is closed. A lost update could free the ClientHook while it is
still in use, or release it on the wrong thread.

GetCapability() calls a new virtual InvokeContext::syncUnlocked() method,
which ServerInvokeContext overrides to wait for the event loop thread with
cancel_lock released and to skip the read if the request was canceled. Client
code already reads results on the event loop thread. ReadList reads capability
lists one item at a time the same way, because iterating over the list reads
the capabilities. Bitcoin Core interfaces do not have parameters like this
yet, but the callback tests here do.

This was reported privately by tcp-raw.

This change was written with Claude Opus 5.5.
@DrahtBot

DrahtBot commented Dec 2, 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
Stale ACK nullfail

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

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #390 (proxy: Rethrow EventLoop::sync() callback exceptions in the calling thread by ryanofsky)
  • #342 (Allow request cancellation for wrapped C++ methods by nullfail)
  • #337 (proxy-types: Remove requirement for return types to be default-constructible by ryanofsky)
  • #336 (proxy-io: Reference-count Connection objects by ryanofsky)

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.

@nullfail

nullfail commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

FWIW, this diff on top of bitcoin/bitcoin#36097 (which integrates #342 for enabling request cancellation) reproduces the destroy-cancel deadlock:

diff --git a/src/ipc/libmultiprocess/include/mp/proxy-io.h b/src/ipc/libmultiprocess/include/mp/proxy-io.h
index a2ab1b5016..f78ac87a62 100644
--- a/src/ipc/libmultiprocess/include/mp/proxy-io.h
+++ b/src/ipc/libmultiprocess/include/mp/proxy-io.h
@@ -13,6 +13,7 @@
 #include <capnp/rpc-twoparty.h>
 
 #include <any>
+#include <chrono>
 #include <assert.h>
 #include <algorithm>
 #include <condition_variable>
@@ -752,6 +753,7 @@ void ProxyServerBase<Interface, Impl>::invokeDestroy()
     // Move m_impl out on the event loop thread, where serverInvoke checks it,
     // and destroy it after returning to this thread.
     std::shared_ptr<Impl> impl;
+    std::this_thread::sleep_for(std::chrono::seconds{1});
     m_context.loop->sync([&] {
         if (m_active_calls == self_count) impl = std::move(m_impl);
     });
diff --git a/test/functional/interface_ipc_mining.py b/test/functional/interface_ipc_mining.py
index 9919449906..2a658e4c5b 100755
--- a/test/functional/interface_ipc_mining.py
+++ b/test/functional/interface_ipc_mining.py
@@ -880,6 +880,16 @@ class IPCMiningTest(BitcoinTestFramework):
 
         asyncio.run(capnp.run(async_routine()))
 
+    def run_destroy_cancel_test(self):
+        async def async_routine():
+            ctx, mining = await make_mining_ctx(self)
+            template = (await mining.createNewBlock(ctx, self.default_block_create_options)).result
+            promise = template.destroy(ctx)
+            await asyncio.sleep(0.5)
+            await drop_promise(promise)
+            await mining.getTip(ctx)
+        asyncio.run(capnp.run(async_routine()))
+
     def run_test(self):
         self.miniwallet = MiniWallet(self.nodes[0])
         # Amount of time in milliseconds the test is allowed to wait or be idle before it should fail.
@@ -893,6 +903,7 @@ class IPCMiningTest(BitcoinTestFramework):
         self.default_block_wait_options = self.capnp_modules['mining'].BlockWaitOptions()
         self.default_block_wait_options.timeout = self.default_ipc_timeout_ms
         self.default_block_wait_options.feeThreshold = 1
+        self.run_destroy_cancel_test()
         self.run_mining_interface_test()
         self.run_early_startup_test()
         self.run_block_template_test()

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

Tested ACK e750955 173f4c4

The first two commits fix the destroy() regression from #382, in case it is better to merge them separately.

I'd lean toward moving the destroy() fixes into a separate PR, so they can be merged quickly and #382 is safe to include in the next subtree update. The changes are small and straightforward, and to me, they look ready to merge. I tested the fix against the diff in #405 (comment) and can confirm it works.

As for the remaining changes, my main concern with the unlocked() approach is that it has to be applied to every call site that can wait for the event loop thread (destroy(), destroying ProxyClient params, and so on), so any new one that we miss would bring the deadlock back. Both approaches below avoid this class of bugs entirely, and they would also fix the capability refcount race, since capabilities would only be accessed from the event loop thread.

Since this touches cancellation and is relevant to #342, I was wondering if there's a specific reason worker threads need access to Cap'n Proto call memory. I couldn't find one when I looked, so if there is a reason, I think it should be documented. Otherwise, I'd suggest passing just raw C++ parameters (along with their corresponding function call) to and from the worker threads, without giving them access to CallContext objects, which are owned by the event loop. This also seems consistent with what Cap'n Proto expects: "Methods of this class may only be called from within the server's event loop, not from other threads."

If that approach isn't possible, Cap'n Proto's CallContextHook interface has from() and addRef() (from() has been available since 0.10), which let a worker thread hold a reference to the call and keep its parameters and results alive. That could still let us get rid of cancel_lock, which, as far as I can tell, was introduced with request cancellation in #240 to prevent the event loop thread from freeing the parameter and result structs while a worker thread is accessing them. I have a working prototype of this against master (it relies on a Cap'n Proto version bump), which removes cancel_lock entirely and passes the tests with TSan and ASan. I'd be happy to open it as a follow-up if this sounds reasonable.

Comment thread include/mp/proxy-types.h
Comment on lines +331 to +338
if constexpr (std::is_base_of_v<::capnp::Capability::Client, std::remove_cvref_t<decltype(data[0])>>) {
// Iterating over a list of capabilities reads them, so read each
// one on the event loop thread (see GetCapability()).
for (unsigned int i = 0; i < data.size(); ++i) {
struct Item { decltype(data)& list; unsigned int index; auto get() const { return list[index]; } };
read_item(GetCapability(invoke_context, Item{data, i}));
}
} else {

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.

In commit 315040f "proxy: read capability parameters on the event loop thread"

It would be nice to add a test with a List of capabilities as a parameter. The sumBars test in my branch could be adapted for this.

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.

3 participants