Repository navigation
fix(event_manager): make subscribe / unsubscribe / publish safe to run concurrently - #929
Merged
Merged
Conversation
…n concurrently The EventManager split each operation across four recursive mutexes and kept raw pointers into its maps after unlocking, which on host (ASan / TSan) reproduced as: - removing a topic's last subscriber while its callback ran could hang forever in join(): the delivery loop cleared the same flag that signalled shutdown, and the hang held the tasks mutex, blocking later subscribes - publish racing the last removal: use-after-free of the topic's queue - subscribers added or removed during a delivery: use-after-free of the callback list being iterated - subscribing to a new topic raced every publish (map insert under the wrong mutex) - a callback removing its own subscription called std::terminate (the topic's Task was destroyed on its own thread) - the last subscriber leaving while another component subscribed lost the new subscription, and removing it later dereferenced a null task - a process (host / python) exiting with a live subscriber never exited Now one mutex guards the registry and each topic's state is held through a shared_ptr. Deliveries iterate an immutable snapshot of the subscribers, and a removed subscriber is never called again. A dedicated stopping flag ends a topic's thread. A removal from the topic's own callback hands the thread over to be joined later. The new destructor (and new clear()) stop every topic. remove_subscriber() now waits for that callback if it is running on another thread, so an object can unsubscribe in its destructor and be destroyed safely. Callbacks are destroyed outside the locks. A throwing callback is logged instead of terminating (when exceptions are enabled). An empty callback or a task that fails to start makes add_subscriber() return false. Python: remove_subscriber / clear release the GIL, and the module's atexit hook clears the EventManager so its threads stop and its python callbacks are destroyed while the interpreter is alive. Only the generated event_manager.hpp section of the bindings is updated. Tests: pc/tests/event_manager.cpp (52 checks, added to the TSan / ASan workflow) and python/event_manager_test.py (added to the wheel test command). The example's counters are now atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
|
✅Static analysis result - no issues found! ✅ |
…dlock waiting A second review of this PR found four more problems, all reproduced on the host before this change: - remove_subscriber() returned false at once when the component was no longer registered, even if its callback was still running: a one-shot callback that had removed itself, or one a concurrent clear() had removed. An owner unsubscribing in its destructor could then be freed under the callback. - Callbacks of two topics removing each other's subscribers deadlocked, each topic thread waiting for the other's delivery (new in this PR: main didn't wait). - A removed callback destroyed on the topic's thread, when the delivery let go of its snapshot, no longer counted as running on that thread: an object whose destructor unsubscribed from the same topic deadlocked, and one that called clear() hit std::terminate. - A subscriber added by a callback while clear() or the destructor waited for it made a topic that was later destroyed without being stopped. Joining its thread hung the destructor, and from python its callable outlived the interpreter (fatal error at exit). Changes: - Each topic tracks whose callback is running. remove_subscriber() waits only while the callback it removes runs, not for the whole delivery, then takes the callback out so it is destroyed by remove_subscriber(), not later on the topic's thread. - When the component isn't registered, remove_subscriber() still waits for its callback on every topic of that name whose thread is still running, including topics being retired or cleared. - Each topic thread records what it waits for. A wait that would lead back to the caller's own thread is skipped instead of deadlocking. Joining a stopping topic waits the same way, so clear() in one topic's callback while another topic's removes from it can't deadlock either. - A delivery counts as running on the topic's thread until it has let go of its snapshot. - add_subscriber() returns false while clear() runs, and from the destructor on. Topic's destructor sets stopping and wakes the thread before joining it. - Topics that lost their last subscriber are joined from publish() too, once their thread is done (on ESP-IDF its stack is held until then). - A callback that removes the topic's last subscriber and subscribes again keeps the topic's thread instead of starting a new one. - The logger for callback exceptions is never destroyed, so a callback that throws while the program exits is still safe. - Docs: the two cases where removal can't wait, the topic task's priority, and add_subscriber() during clear(). Fix the stop_registry.h and python test comments. Tests: pc/tests/event_manager.cpp gains a section for each of these (83 checks, was 52). A hang caught by returns_within() now fails the test at once, instead of leaving the stuck thread to crash later checks. python/event_manager_test.py gains exit_while_callback_subscribes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
espp::EventManagersplit each operation across four separate recursive mutexes, released them between steps, and kept raw pointers into its maps after unlocking. On the host, under ASan and TSan, that reproduced as:join(): the delivery loop cleared the samenotifiedflag that signalled shutdown. The hang heldtasks_mutex_, so later subscribes and last-subscriber removals blocked toopublish()racing the removal of the last subscriberpublishkept aSubscriberData*after unlocking)shared_ptrtasks_mutex_, looked up underdata_mutex_std::terminate: the topic'sTaskwas destroyed on its own threadstd::terminateThe public API is unchanged, apart from two additions:
clear()and an explicit destructor.How it works now
std::mutexguards the registry (topics and publishers). Each topic's state (queue, condition variables, task, subscriber list) lives in ashared_ptr<Topic>, sopublish()and teardown can overlap safely.removedflag makes later deliveries skip it.remove_subscriber()waits for the callback it removes. Each topic tracks whose callback is running. If the removed callback is running on another thread, removal waits for it to return, but not for the topic's other callbacks. It also waits when the component is no longer registered, but its callback is still running because it removed itself orclear()removed it. So an object can unsubscribe in its destructor (as the class docs recommend) and be destroyed safely right after.stoppingflag ends a topic's thread. If a callback removes the topic's last subscriber and then subscribes again, the topic keeps its thread.remove_subscriber()itself, unless it was still running. In that case it is destroyed on the topic's thread, which still counts as that topic's callback, so a destructor can unsubscribe safely. This matters for Python, whose callables take the GIL when destroyed.add_subscriber()returns false for an empty callback, whileclear()runs, or when the topic's task fails to start. Before, that failure was ignored.Behaviour changes to be aware of
remove_subscriber()(andclear()) can now block while the callback they remove runs on another thread. The docs say not to call them while holding a lock that callback takes. They wait at the topic task's priority, which is 0 unlesstask_configsets one; the docs say so too.add_subscriber()returns false whileclear()runs. This includes a callback subscribing whileclear()or the destructor waits for it.Python
remove_subscriberandclearrelease the GIL (added to_GIL_RELEASE_METHODS). Without that, removing a subscriber whose Python callback is running deadlocks.EventManageris a C++ singleton that Python never owns, so theStopOnExitHolderpath doesn't apply. The module'satexithook now callsEventManager::get().clear()with the GIL released, so the topic threads stop and the Python callbacks are destroyed while the interpreter is still alive.event_manager.hppsection ofpybind_espp.cppand__init__.pyiis updated. A full regeneration with the current litgen also rewrites many unrelated sections (for example it dropsBaseComponent.set_log_tag), so I left those alone.Tests
pc/tests/event_manager.cpp(83 checks) is added tohost_sanitizers.yml(TSan + ASan) and its path filters. It has one section per bug above, plus the guarantees above:clear()runs;clear()in one topic's callback while another topic's callback removes from it;clear(), run on the topic's thread;clear()or the destructor runs;publish()joins a topic that removed its last subscriber itself;clear()works, including from inside a callback;python/event_manager_test.py(9 cases, each in a child interpreter under a timeout) is added to the wheeltest-command. It covers:TypeErrors; an empty callback; a raising callback);clear()while a callback runs;clear()waits for it.std::atomic. They were plainints written from four threads.Verification
g++-16 -std=c++23 -Wall -Wextra -Werror.main, every section for one of the bugs above fails, with an ASan use-after-free or container-overflow,std::terminate, a failed check, or a hang. The two sections that only check behaviour that was already right fail only when the old destructor hangs.publish()never joins;Fatal Python error: gilstate_tss_setagainst the first commit (3/3 runs).python/blocking_destructors_test.pyandpython/dispatcher_test.pystill pass.idf.py buildfor esp32 passes forcomponents/event_manager/exampleandcomponents/button/example(the other user).🤖 Generated with Claude Code
https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU