Repository navigation
proxy-io: Fix theoretical disconnect bugs - #361
Conversation
|
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 ConflictsNo conflicts as of last run. |
There was a problem hiding this comment.
ACK bc98767
Thnaks for opening this @ryanofsky, this does address the issues i mentioned, i agree these improvements here are more conservative as they have not been seen in practice, but would be nice to have it if we want to make disconnection more robust.
Left some documentation nits
There was a problem hiding this comment.
Updated bc98767 -> 0f5c633 (pr/ondis.1 -> pr/ondis.2, compare) dropping renames because they cause problems downstream in test_bitcoin, making more documentation updates and adding a third bugfix here "thread map teardown race" that was originally in #335, since it fixes another bug that precedes #335
Updated 0f5c633 -> 040919b (pr/ondis.2 -> pr/ondis.3, compare) to fix IWYU error https://github.com/bitcoin-core/libmultiprocess/actions/runs/34640736556/job/103399475344?pr=361
Rebased 040919b -> 9783fb2 (pr/ondis.3 -> pr/ondis.4, compare) onto master to fix CI failures: the IWYU check flagged #include <list> in test.cpp, now kept with an IWYU pragma since GCC and clang disagree about it (llvm job), and the olddeps job failed downloading cmake (olddeps job)
Rebased 9783fb2 -> ee350b4 (pr/ondis.4 -> pr/ondis.5, compare) due to conflicts with #365, also dropping an unused #include <list> from listen_tests.cpp that IWYU now reports
|
I ran into this while testing sv2-tp behavior when bitcoin core disappears from under it. See the second commit in stratum-mining/sv2-tp#128. |
nullfail
left a comment
There was a problem hiding this comment.
tACK ee350b4
Can confirm each of the bugs being addressed in this PR does, in fact, exist. Tested commit by commit, with and without the fixes applied. I left some nits.
Non-blocking thought for a future cleanup: I wonder if the thread/thread-map lifetimes could be refactored (for example, consolidating ownership on one side) so the race is avoided more naturally and the code is easier to reason about.
Drop the outer `if (m_disconnect_cb)` check in ~ProxyClient<Thread>. It has been redundant since 4a269b2, which moved the removeSyncCleanup() call into loop->sync() and repeated the check inside the lambda. The outer check also read m_disconnect_cb without synchronization on the thread destroying the ProxyClient<Thread>, while the SetThread disconnect callback can reset it on the event loop thread. With the check removed, m_disconnect_cb is only accessed on the event loop thread. This should not change behavior, aside from removing that unsynchronized read. Suggested by xyzconstant in bitcoin-core#361 (comment) This change was written with Claude Opus 5.5.
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).
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.
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 <[email protected]> This change was written with Claude Opus 4.8 (1M context).
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 bitcoin-core#335 (comment) 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 <[email protected]> This change was written with Claude Fable 5.
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.
enochaz
left a comment
There was a problem hiding this comment.
re-ACK ee350b4
Looked at the changes since my last review at bc98767. The two fixes are the same, just rebased, plus the doc commits and the new thread map fix in ee350b4.
IIUC ee350b4 makes whichever side removes the map entry under the waiter mutex the one that destroys it, so the thread context destructor and the SetThread cleanup can't both destroy it. Makes sense to me
Left one small comment nit.
ryanofsky
left a comment
There was a problem hiding this comment.
Thanks for the reviews and testing! All comments should be addressed in the latest push.
Updated ee350b4 -> 260c62c (pr/ondis.5 -> pr/ondis.6, compare) rebasing onto master to include #376, adding a first commit dropping a redundant m_disconnect_cb check (suggested by xyzconstant), updating the lock order documentation for #376 and #347, naming request_threads and callback_threads in a comment, and dropping an inaccurate test comment
| // ~ProxyClient<Thread> blocks in EventLoop::sync() and the event loop | ||
| // thread locks Waiter::m_mutex itself (see the blocking rule in the | ||
| // Waiter::m_mutex documentation). | ||
| ConnThreads request, callback; | ||
| { |
There was a problem hiding this comment.
re: Sjors #361 (comment)
In commit "proxy: Fix thread map teardown race causing use-after-free on disconnect" (260c62c)
I ran into this while testing sv2-tp behavior when bitcoin core disappears from under it.
Thanks, good to know the thread-map teardown race is reachable through sv2-tp's disconnect handling, not just theoretical like I thought.
| // Clear client maps now to avoid deadlock in m_thread.join() call | ||
| // below. The maps contain Thread::Client objects that need to be | ||
| // destroyed from the event loop thread (this thread), which can't | ||
| // happen if this thread is busy calling join. | ||
| m_thread_context.request_threads.clear(); | ||
| m_thread_context.callback_threads.clear(); |
There was a problem hiding this comment.
re: #361 (review)
In commit "proxy: Fix thread map teardown race causing use-after-free on disconnect" (260c62c)
Non-blocking thought for a future cleanup: I wonder if the thread/thread-map lifetimes could be refactored (for example, consolidating ownership on one side)
Thanks for testing each fix with and without the change, that's really helpful. And I agree about the ownership: right now entries in these maps can be destroyed from three places (here, the SetThread disconnect callback, and ~ThreadContext), which is why the fix needs the "whoever removes the entry destroys it" rule. Having a single owner would be a lot easier to follow, and I'd be happy to review a follow-up along those lines.
Drop the outer `if (m_disconnect_cb)` check in ~ProxyClient<Thread>. It has been redundant since 4a269b2, which moved the removeSyncCleanup() call into loop->sync() and repeated the check inside the lambda. The outer check also read m_disconnect_cb without synchronization on the thread destroying the ProxyClient<Thread>, while the SetThread disconnect callback can reset it on the event loop thread. With the check removed, m_disconnect_cb is only accessed on the event loop thread. This should not change behavior, aside from removing that unsynchronized read. Suggested by xyzconstant in bitcoin-core/libmultiprocess#361 (comment) This change was written with Claude Opus 5.5.
enochaz
left a comment
There was a problem hiding this comment.
re-ACK 260c62c
Went through the changes since ee350b4. Besides the rebase onto master for #376, it's the new commit dropping the redundant m_disconnect_cb check, the lock order doc updates, and my nit addressed. The fixes are unchanged.
The added docs on the waiter mutex are really helpful. Spelling out that it shouldn't be held across the sync method on the EventLoop from another thread makes the mutex release in the thread context destructor and the SetThread cleanup much easier to follow.
Thanks for addressing the comments @ryanofsky
|
Post-merge ACK 260c62c. |
Two bugs in
Connection::onDisconnectwere pointed out in #335 review by enochaz:evalLatercould allow an onDisconnect handler to run after a Connection object was destroyed.A third "thread map teardown race" bug was also encountered in a new unit test introduced by #335, and Sjors hit it independently while testing sv2-tp when Bitcoin Core disappears from under it (#361 (comment)). This PR fixes each bug in a separate commit and also includes documentation commits to help make the changes more understandable.
The first two bugs are "theoretical" just in the sense that they haven't been seen in practice and were found in code review. The first ListenConnections bug can't currently happen in bitcoin core because it doesn't disconnect IPC clients except when it is shutting down, and it would not make sense to accept new connections. The second race condition bug has just existed for many years and not been seen previously.