Repository navigation
Conversation
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.
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
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. |
|
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
left a comment
There was a problem hiding this comment.
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.
| 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 { |
Problem: A server method running on a worker thread holds its request's
cancel_lockexcept while the method itself runs, and the event loop thread locks the same mutex inon_cancelwhen 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 callinvokeDestroy()with the lock held, and since #382invokeDestroy()callsEventLoop::sync(). Triggering it needs a client that sendsdestroy()and disconnects before the server callssync(). Bitcoin Core'sBlockTemplate.destroyandEcho.destroyrun this way, but Bitcoin Core's subtree does not include #382 yet, so this should be merged before the next subtree update.ProxyClientobjects for interface and callback parameters are destroyed after the method returns, with the lock held, and their destructors call the remotedestroy()method andEventLoop::sync(). A client that receives thedestroy()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 theClientHookwhile 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:
ServerInvokeContext::unlocked()helper, moved out ofServerCall, that calls a function withcancel_lockreleased, reacquires it, and throwsInterruptExceptionif the request was canceled meanwhile. CallinvokeDestroy()and destroy parameters through it.EventLoop::sync()assert that the calling thread does not hold thecancel_lockof 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.GetCapability()function that reads capabilities on the event loop thread through a new virtualInvokeContext::syncUnlocked()method, whichServerInvokeContextoverrides to releasecancel_lockwhile waiting and to skip the read if the request was canceled. Use it wherever parameters are read as interfaces or callbacks, including capability lists inReadList.The first two commits fix the
destroy()regression from #382, in case it is better to merge them separately.