From 7820618d6ded6e0adc7e0500f05a62480ab7f80f Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Thu, 26 Nov 2026 08:45:30 -0700 Subject: [PATCH 1/2] fix(event_manager): make subscribe / unsubscribe / publish safe to run 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 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .github/workflows/host_sanitizers.yml | 7 +- components/event_manager/README.md | 17 + .../example/main/event_manager_example.cpp | 12 +- .../event_manager/include/event_manager.hpp | 124 +++-- .../event_manager/include/event_map.hpp | 8 +- .../event_manager/src/event_manager.cpp | 421 ++++++++++------- doc/en/core/event_manager.rst | 18 + lib/README.md | 6 + lib/autogenerate_bindings.py | 2 + lib/python_bindings/espp/__init__.pyi | 52 ++- lib/python_bindings/module.cpp | 13 +- lib/python_bindings/pybind_espp.cpp | 67 ++- pc/tests/event_manager.cpp | 428 ++++++++++++++++++ pyproject.toml | 6 +- python/event_manager_test.py | 212 +++++++++ 15 files changed, 1145 insertions(+), 248 deletions(-) create mode 100644 pc/tests/event_manager.cpp create mode 100644 python/event_manager_test.py diff --git a/.github/workflows/host_sanitizers.yml b/.github/workflows/host_sanitizers.yml index 8163aaf5bd..265888d1c1 100644 --- a/.github/workflows/host_sanitizers.yml +++ b/.github/workflows/host_sanitizers.yml @@ -6,7 +6,8 @@ name: Host sanitizers (TSan / ASan) # scheduler, deferred dispatchers), and most defects found in review have been # data races, deadlocks, and use-after-frees - exactly the classes these # sanitizers detect mechanically. Runs whenever RTPS or its concurrency -# building blocks change. +# building blocks change. The EventManager test (pc/tests/event_manager.cpp) +# runs here too, for the same reasons. # Minimal token scope: build + run tests, never writes. permissions: @@ -21,10 +22,12 @@ on: - "components/task/**" - "components/timer/**" - "components/cdr/**" + - "components/event_manager/**" - "lib/espp.cmake" - "pc/tests/rtps_*" - "pc/tests/socket_reactor.cpp" - "pc/tests/thread_pool.cpp" + - "pc/tests/event_manager.cpp" - ".github/workflows/host_sanitizers.yml" workflow_dispatch: @@ -97,7 +100,7 @@ jobs: # docker matrix covers them); everything else runs standalone. The # generous per-test timeout absorbs the sanitizer's slowdown; a hang # (e.g. a deadlock TSan cannot see) still fails the job. - for t in pc/build/rtps_* pc/build/socket_reactor pc/build/thread_pool; do + for t in pc/build/rtps_* pc/build/socket_reactor pc/build/thread_pool pc/build/event_manager; do [ -x "$t" ] || continue name=$(basename "$t") case "$name" in *interop*) continue;; esac diff --git a/components/event_manager/README.md b/components/event_manager/README.md index 181ae69d89..efb4bb2e8c 100644 --- a/components/event_manager/README.md +++ b/components/event_manager/README.md @@ -14,6 +14,23 @@ EventManager. As noted in a few places, it is recommended to use a (de-)serialization library such as espp::serialization / alpaca for transforming data structures to/from `std::vector` for publishing/subscribing. +## Threads and callbacks + +Each topic's callbacks run one after another on that topic's thread, in the +order the subscribers were added, and data published on a topic is delivered +in the order it was published. One slow callback delays every other subscriber +of the same topic (but not other topics). + +Every function is thread safe and can be called from any thread, including from +inside a subscriber callback: a callback can publish, subscribe, or remove its +own subscription. When `remove_subscriber()` returns, that callback is not +running and will not be called again, so an object can call it from its +destructor and then be destroyed safely. To guarantee that, +`remove_subscriber()` (and `clear()`) wait for a callback of that topic that is +running on another thread to return, so don't call them while holding a lock +that the topic's callbacks take. Data still queued for a topic when its last +subscriber leaves is dropped. + ## Example The [example](./example) shows some basic usage for the `EventManager` which diff --git a/components/event_manager/example/main/event_manager_example.cpp b/components/event_manager/example/main/event_manager_example.cpp index 27cc38ce74..e809b93fc4 100644 --- a/components/event_manager/example/main/event_manager_example.cpp +++ b/components/event_manager/example/main/event_manager_example.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -31,8 +32,9 @@ extern "C" void app_main(void) { const std::string event1 = "battery/state"; const std::string event2 = "drive/control"; - static int num_published = 0; - static int num_received = 0; + // updated from both tasks and both topics' subscriber threads + static std::atomic num_published = 0; + static std::atomic num_received = 0; // Make a task which has a pub/sub in it. NOTE: in real code, this would // likely be within a custom class and the registration would happen in the @@ -184,10 +186,10 @@ extern "C" void app_main(void) { em.remove_subscriber(event1, "task 2"); //! [event manager example] - logger.info("Published {} times", num_published); - logger.info("Received {} times", num_received); + logger.info("Published {} times", num_published.load()); + logger.info("Received {} times", num_received.load()); - if (num_published != num_received) { + if (num_published.load() != num_received.load()) { logger.error("Mismatch between published and received!"); } else { logger.info("Published and received match!"); diff --git a/components/event_manager/include/event_manager.hpp b/components/event_manager/include/event_manager.hpp index 895e0fb66d..c80d5b7fb3 100644 --- a/components/event_manager/include/event_manager.hpp +++ b/components/event_manager/include/event_manager.hpp @@ -1,6 +1,11 @@ #pragma once +#include +#include +#include #include +#include +#include #include #include #include @@ -22,13 +27,29 @@ namespace espp { * @note In c++ objects, it's recommended to call the * add_publisher/add_subscriber functions in the class constructor and * then to call the remove_publisher/remove_subscriber functions in the - * class destructor. + * class destructor. When remove_subscriber() returns, the callback is + * not running and will not be called again, so the object can be + * destroyed safely right after it. + * + * @note Every function is thread safe and can be called from any thread, + * including from inside a subscriber callback (for example a callback + * that removes its own subscription). remove_subscriber() and clear() + * wait for a callback of that topic that is running on another thread + * to return, so don't call them while holding a lock which that + * topic's callbacks take. Called from one of the topic's own callbacks, + * they don't wait; the removed callbacks are not called again once the + * current one returns. + * + * @note Data published on a topic is queued and delivered in order on the + * topic's thread. Data still queued when the topic's last subscriber is + * removed is dropped. When C++ exceptions are enabled, an exception + * thrown by a callback is logged and the other callbacks still run. * * @note It is recommended (unless you are only interested in events and not * data or are only needing to transmit actual strings) to use a * serialization library (such as espp::serialization - which wraps - * alpaca) to serialize your data structures to string when publishing - * and then deserialize your data from string in the subscriber + * alpaca) to serialize your data structures to bytes when publishing + * and then deserialize your data from bytes in the subscriber * callbacks. * * \section event_manager_ex1 Event Manager Example @@ -57,6 +78,12 @@ class EventManager : public espp::BaseComponent { EventManager(EventManager &&) = delete; EventManager &operator=(EventManager &&) = delete; + /** + * @brief Destroy the EventManager, stopping every topic's thread (see + * clear()). + */ + ~EventManager(); + /** * @brief Register a publisher for \p component on \p topic. * @param topic Topic name for the data being published. @@ -69,15 +96,16 @@ class EventManager : public espp::BaseComponent { /** * @brief Register a subscriber for \p component on \p topic. * @param topic Topic name for the data being subscribed to. - * @param component Name of the component publishing data. - * @param callback The event_callback_fn to be called when receicing data on + * @param component Name of the component subscribing to the data. + * @param callback The event_callback_fn to be called when receiving data on * \p topic. * @param stack_size_bytes The stack size in bytes to use for the subscriber * @note The stack size is only used if a subscriber is not already registered * for that topic. If a subscriber is already registered for that topic, * the stack size is ignored. * @return True if the subscriber was added, false if it was already - * registered for that component. + * registered for that component, the callback is empty, or the + * topic's thread could not be started. */ bool add_subscriber(const std::string &topic, const std::string &component, const espp::EventManager::event_callback_fn &callback, @@ -86,15 +114,16 @@ class EventManager : public espp::BaseComponent { /** * @brief Register a subscriber for \p component on \p topic. * @param topic Topic name for the data being subscribed to. - * @param component Name of the component publishing data. - * @param callback The event_callback_fn to be called when receicing data on + * @param component Name of the component subscribing to the data. + * @param callback The event_callback_fn to be called when receiving data on * \p topic. * @param task_config The task configuration to use for the subscriber. * @note The task_config is only used if a subscriber is not already * registered for that topic. If a subscriber is already registered for * that topic, the task_config is ignored. * @return True if the subscriber was added, false if it was already - * registered for that component. + * registered for that component, the callback is empty, or the + * topic's thread could not be started. */ bool add_subscriber(const std::string &topic, const std::string &component, const espp::EventManager::event_callback_fn &callback, @@ -121,6 +150,11 @@ class EventManager : public espp::BaseComponent { /** * @brief Remove \p component's subscriber for \p topic. + * @details When it returns, the callback is not running and will not be + * called again, unless it was called from one of \p topic's own + * callbacks (then the callback is not called again once the + * current one returns). Removing the topic's last subscriber stops + * the topic's thread and drops any data still queued for it. * @param topic The topic that \p component was subscribing to. * @param component The component for which the subscriber was registered. * @return True if the subscriber was removed, false if it was not @@ -128,31 +162,63 @@ class EventManager : public espp::BaseComponent { */ bool remove_subscriber(const std::string &topic, const std::string &component); + /** + * @brief Remove every publisher and subscriber and stop every topic's + * thread. + * @details Waits for callbacks running on other threads to return. The + * EventManager can be used again afterwards. + */ + void clear(); + protected: EventManager() : espp::BaseComponent("Event Manager") {} - struct SubscriberData { - std::mutex m; - bool notified = false; // Allows cv to ignore spurious wakeups - std::condition_variable cv; - std::deque> deq; + /// One component's subscription. Shared by the topic's subscriber list and + /// by the snapshot a delivery in progress iterates, so a callback is never + /// destroyed while it runs. + struct Subscriber { + Subscriber(const std::string &component, const event_callback_fn &callback) + : component(component) + , callback(callback) {} + const std::string component; + const event_callback_fn callback; + std::atomic removed{false}; ///< Set when removed; deliveries skip it from then on. + }; + using SubscriberList = std::vector>; + + /// The state of one topic that has subscribers. Owned through a shared_ptr + /// so publish() and the removal of the last subscriber can overlap safely. + struct Topic { + explicit Topic(const std::string &name) + : name(name) {} + const std::string name; + std::mutex m; ///< Guards everything below except task. + std::condition_variable cv; ///< Wakes the topic's thread (data queued or stopping). + std::condition_variable idle_cv; ///< Signalled when a delivery finishes. + std::deque> queue; + bool stopping{false}; ///< Set once, when the topic loses its last subscriber. + bool delivering{false}; ///< True while the topic's thread is running callbacks. + uint64_t deliveries{0}; ///< Number of finished deliveries. + /// Replaced, never changed in place, with both EventManager::mutex_ and m + /// held, so holding either one is enough to read it. + std::shared_ptr subscribers; + /// Declared last so it is destroyed (joining the thread) first. + std::unique_ptr task; }; - bool subscriber_task_fn(const std::string &topic, std::mutex &m, std::condition_variable &cv, - bool &task_notified); - - std::recursive_mutex events_mutex_; - detail::EventMap events_; - - std::recursive_mutex callbacks_mutex_; - std::unordered_map>> - subscriber_callbacks_; - - std::recursive_mutex tasks_mutex_; - std::unordered_map> subscriber_tasks_; - - std::recursive_mutex data_mutex_; - std::unordered_map subscriber_data_; + static bool deliver_next(Topic &topic); + static bool is_delivering(const Topic &topic); + static void wait_for_delivery(Topic &topic); + void stop_topics(std::vector> topics); + void reap_stopped_topics(); + + std::mutex mutex_; ///< Guards the members below. + std::unordered_map> publishers_; + std::unordered_map> topics_; + /// Topics that lost their last subscriber from inside one of their own + /// callbacks: their thread exits on its own and is joined later (by + /// reap_stopped_topics(), clear(), or the destructor). + std::vector> stopping_topics_; }; } // namespace espp diff --git a/components/event_manager/include/event_map.hpp b/components/event_manager/include/event_map.hpp index 2cd79d5285..2dd0a342a6 100644 --- a/components/event_manager/include/event_map.hpp +++ b/components/event_manager/include/event_map.hpp @@ -1,9 +1,11 @@ #pragma once -#include +#include +#include +#include #include -#include #include +#include #include namespace espp { @@ -31,7 +33,7 @@ std::pair get_index_in_container(const T &value, const C &contai if (exists) { index = std::distance(container.begin(), iter); } - return {exists, index}; + return {exists, static_cast(index)}; } } // namespace detail } // namespace espp diff --git a/components/event_manager/src/event_manager.cpp b/components/event_manager/src/event_manager.cpp index 7c477489de..0c69d12e0f 100644 --- a/components/event_manager/src/event_manager.cpp +++ b/components/event_manager/src/event_manager.cpp @@ -1,15 +1,62 @@ #include "event_manager.hpp" +#include +#include +#include + using namespace espp; +namespace { +// The topic whose callbacks this thread is running right now, if any. A +// removal made from one of those callbacks must not wait for the delivery in +// progress or join the topic's thread: both are this thread. +thread_local const void *t_delivering_topic = nullptr; + +void call_subscriber(const std::string &topic, const std::string &component, + const EventManager::event_callback_fn &callback, + const std::vector &data) { +#if defined(__cpp_exceptions) && __cpp_exceptions + // A callback that throws must not end the topic's thread (an exception + // escaping it calls std::terminate): log it and go on with the next one. + static espp::Logger logger({.tag = "Event Manager", .level = espp::Logger::Verbosity::WARN}); + try { + callback(data); + } catch (const std::exception &e) { + logger.error("Exception in subscriber '{}' on topic '{}': {}", component, topic, e.what()); + } catch (...) { + logger.error("Unknown exception in subscriber '{}' on topic '{}'", component, topic); + } +#else + // C++ exceptions are disabled (the ESP-IDF default): nothing can be thrown. + callback(data); +#endif +} +} // namespace + +EventManager::~EventManager() { + clear(); + // Left over only if the EventManager is destroyed from inside a topic's + // callback (e.g. exit() called from one). That thread can't be joined from + // itself, and destroying its Task here would std::terminate, so keep the + // topic alive: its thread exits on its own once the callback returns. + std::vector> left; + { + std::lock_guard lk(mutex_); + left.swap(stopping_topics_); + } + if (!left.empty()) { + static auto &kept = *new std::vector>(); // never destroyed + kept.insert(kept.end(), std::make_move_iterator(left.begin()), + std::make_move_iterator(left.end())); + } +} + bool EventManager::add_publisher(const std::string &topic, const std::string &component) { logger_.info("Adding publisher '{}' to topic '{}'", component, topic); - std::lock_guard lk(events_mutex_); - // add to `events_` + std::lock_guard lk(mutex_); // NOTE: this will default construct this if it does not exist - auto &topic_publishers = events_.publishers[topic]; - auto [exists, index] = detail::get_index_in_container(component, topic_publishers); - if (exists) { + auto &topic_publishers = publishers_[topic]; + if (detail::get_index_in_container(component, topic_publishers).first) { // component is already registered as a publisher, so return false return false; } @@ -28,238 +75,262 @@ bool EventManager::add_subscriber(const std::string &topic, const std::string &c const event_callback_fn &callback, const Task::BaseConfig &task_config) { logger_.info("Adding subscriber '{}' to topic '{}'", component, topic); - { - std::lock_guard lk(events_mutex_); - // add to `events_` - // NOTE: this will default construct this if it does not exist - auto &topic_subscribers = events_.subscribers[topic]; - auto [exists, index] = detail::get_index_in_container(component, topic_subscribers); - if (exists) { - // component is already registered as a subscriber, so return false - return false; - } - topic_subscribers.push_back(component); + if (!callback) { + logger_.error("Cannot add subscriber '{}' to topic '{}': its callback is empty", component, + topic); + return false; } - // add to `subscriber_callbacks_` - { - std::lock_guard lk(callbacks_mutex_); - auto &callbacks = subscriber_callbacks_[topic]; - auto is_component = [&component](std::pair &e) { - return std::get<0>(e) == component; + reap_stopped_topics(); + // Declared before the lock so that whatever they hold when we return (a + // callback, a replaced subscriber list, a topic whose thread didn't start) is + // destroyed after the lock is released, never under it. + auto subscriber = std::make_shared(component, callback); + std::shared_ptr replaced; + std::shared_ptr state; + std::lock_guard lk(mutex_); + if (auto it = topics_.find(topic); it != topics_.end()) { + state = it->second; + const auto ¤t = *state->subscribers; + auto is_component = [&component](const std::shared_ptr &s) { + return s->component == component; }; - auto elem = std::find_if(std::begin(callbacks), std::end(callbacks), is_component); - if (elem != std::end(callbacks)) { + if (std::find_if(current.begin(), current.end(), is_component) != current.end()) { // callback for this component is already registered, so return false return false; } - callbacks.emplace_back(component, callback); + auto subscribers = current; + subscribers.push_back(std::move(subscriber)); + std::lock_guard topic_lk(state->m); + replaced = std::exchange(state->subscribers, + std::make_shared(std::move(subscribers))); + return true; } - // if not in `subscriber_tasks_` - { - std::lock_guard lk(tasks_mutex_); - if (!subscriber_tasks_.contains(topic)) { - // add to `subscriber_data_` - subscriber_data_[topic]; // insert default constructed data - // create new task (using bound subscriber_task_fn) and add to - // `subscriber_tasks_` - using namespace std::placeholders; - auto config = task_config; - if (config.name.empty()) { - config.name = topic + " subscriber"; - } - logger_.debug("Creating task for topic '{}'", topic); - logger_.debug(" with config: {}", config); - subscriber_tasks_[topic] = Task::make_unique( - {.callback = std::bind(&EventManager::subscriber_task_fn, this, topic, _1, _2, _3), - .task_config = config}); - // and start it - subscriber_tasks_[topic]->start(); - } + // first subscriber on this topic: create it and start its thread + state = std::make_shared(topic); + state->subscribers = std::make_shared(SubscriberList{subscriber}); + auto config = task_config; + if (config.name.empty()) { + config.name = topic + " subscriber"; } + logger_.debug("Creating task for topic '{}'", topic); + logger_.debug(" with config: {}", config); + state->task = Task::make_unique( + {.callback = Task::callback_no_params_fn{[t = state.get()]() { return deliver_next(*t); }}, + .task_config = config}); + if (!state->task->start()) { + logger_.error("Cannot add subscriber '{}' to topic '{}': could not start the topic's task", + component, topic); + return false; + } + topics_.emplace(topic, std::move(state)); return true; } bool EventManager::publish(const std::string &topic, const std::vector &data) { logger_.info("Publishing on topic '{}'", topic); - // find topic in `subscriber_data_`, push_back into the queue there and notify - // the cv. - // get the data queue - SubscriberData *sub_data; + std::shared_ptr state; { - std::lock_guard lk(data_mutex_); - // find sub_data in `subscriber_data_` - if (!subscriber_data_.contains(topic)) { + std::lock_guard lk(mutex_); + auto it = topics_.find(topic); + if (it == topics_.end()) { return false; } - sub_data = &subscriber_data_[topic]; + state = it->second; } { - // lock the data queue - std::unique_lock lk(sub_data->m); - // push the data into the queue - sub_data->deq.push_back(data); - // update the notified flag (used to ignore spurious wakeups) - sub_data->notified = true; + std::vector copy(data); // copied before taking the lock + std::lock_guard lk(state->m); + if (state->stopping) { + // its last subscriber was removed while we were looking it up + return false; + } + state->queue.push_back(std::move(copy)); } - // notify the task that there is new data in the queue - sub_data->cv.notify_all(); + state->cv.notify_one(); return true; } bool EventManager::remove_publisher(const std::string &topic, const std::string &component) { logger_.info("Removing publisher '{}' on topic '{}'", component, topic); - // remove from `events_` - std::lock_guard lk(events_mutex_); - if (!events_.publishers.contains(topic)) { + std::lock_guard lk(mutex_); + auto it = publishers_.find(topic); + if (it == publishers_.end()) { // there is no publisher for this topic return false; } - // We know the container contains a value for [topic] - auto &topic_publishers = events_.publishers[topic]; - auto elem = std::find(std::begin(topic_publishers), std::end(topic_publishers), component); - bool exists = elem != std::end(topic_publishers); - if (!exists) { + auto &topic_publishers = it->second; + auto elem = std::find(topic_publishers.begin(), topic_publishers.end(), component); + if (elem == topic_publishers.end()) { // component is not registered as a publisher, so return false return false; } - // we found it, so remove it from the list topic_publishers.erase(elem); + if (topic_publishers.empty()) { + publishers_.erase(it); + } return true; } bool EventManager::remove_subscriber(const std::string &topic, const std::string &component) { logger_.info("Removing subscriber '{}' on topic '{}'", component, topic); - bool was_last_subscriber{false}; - // remove from `events_` + // Destroyed after the lock is released (see add_subscriber). + std::shared_ptr removed; + std::shared_ptr replaced; + std::shared_ptr state; + bool was_last_subscriber = false; { - std::lock_guard lk(events_mutex_); - if (!events_.subscribers.contains(topic)) { + std::lock_guard lk(mutex_); + auto it = topics_.find(topic); + if (it == topics_.end()) { logger_.warn("Cannot remove subscriber, there are no subscribers for topic '{}'", topic); - // there is no publisher for this topic return false; } - // We know the container contains a value for [topic] - auto &topic_subscribers = events_.subscribers[topic]; - auto elem = std::find(std::begin(topic_subscribers), std::end(topic_subscribers), component); - bool exists = elem != std::end(topic_subscribers); - if (!exists) { + state = it->second; + auto subscribers = *state->subscribers; + auto elem = std::find_if( + subscribers.begin(), subscribers.end(), + [&component](const std::shared_ptr &s) { return s->component == component; }); + if (elem == subscribers.end()) { logger_.warn( "Cannot remove subscriber, '{}' is not registered as a subscriber for topic '{}'", component, topic); - // component is not registered as a subscriber, so return false return false; } - // we found it, so remove it from the list - topic_subscribers.erase(elem); - was_last_subscriber = topic_subscribers.size() == 0; - } - // remove from `subscriber_callbacks_` - { - std::lock_guard lk(callbacks_mutex_); - auto &callbacks = subscriber_callbacks_[topic]; - - auto is_component = [&component](std::pair &e) { - return std::get<0>(e) == component; - }; - auto elem = std::find_if(std::begin(callbacks), std::end(callbacks), is_component); - if (elem != std::end(callbacks)) { - callbacks.erase(elem); + removed = *elem; + // a delivery in progress skips it from now on + removed->removed = true; + subscribers.erase(elem); + was_last_subscriber = subscribers.empty(); + if (was_last_subscriber) { + topics_.erase(it); } + std::lock_guard topic_lk(state->m); + replaced = std::exchange(state->subscribers, + std::make_shared(std::move(subscribers))); if (was_last_subscriber) { - // remove the key from the map - subscriber_callbacks_.erase(topic); + state->stopping = true; } } - // if this was the last subscriber if (was_last_subscriber) { - logger_.info("It was the last subscriber for '{}', cleaning up tasks", topic); - // notify the data (so the subscriber task function can stop waiting on the data cv) - { - std::lock_guard lk(data_mutex_); - { - std::unique_lock data_lk(subscriber_data_[topic].m); - subscriber_data_[topic].notified = true; - } - subscriber_data_[topic].cv.notify_all(); + logger_.info("It was the last subscriber for '{}', stopping its task", topic); + std::vector> stopped; + stopped.push_back(std::move(state)); + stop_topics(std::move(stopped)); + } else if (!is_delivering(*state)) { + // the callback may be running right now on the topic's thread + wait_for_delivery(*state); + } + reap_stopped_topics(); + return true; +} + +void EventManager::clear() { + logger_.info("Removing every publisher and subscriber"); + std::vector> topics; + std::vector> replaced; + { + std::lock_guard lk(mutex_); + publishers_.clear(); + for (auto &[name, state] : topics_) { + topics.push_back(std::move(state)); } - { - std::lock_guard lk(tasks_mutex_); - // stop the task - subscriber_tasks_[topic]->stop(); - // remove from `subscriber_tasks_` - subscriber_tasks_.erase(topic); + topics_.clear(); + topics.insert(topics.end(), std::make_move_iterator(stopping_topics_.begin()), + std::make_move_iterator(stopping_topics_.end())); + stopping_topics_.clear(); + for (const auto &state : topics) { + std::lock_guard topic_lk(state->m); + for (const auto &subscriber : *state->subscribers) { + subscriber->removed = true; + } + replaced.push_back( + std::exchange(state->subscribers, std::make_shared())); + state->stopping = true; } - { - std::lock_guard lk(data_mutex_); - // remove from `subscriber_data_` - subscriber_data_.erase(topic); + } + stop_topics(std::move(topics)); + // destroy the callbacks now that every lock is released and every thread + // is stopped (a callback still running belongs to the thread calling us) + replaced.clear(); +} + +void EventManager::stop_topics(std::vector> topics) { + // every topic here is already marked stopping + for (const auto &state : topics) { + state->cv.notify_all(); + } + for (auto &state : topics) { + if (is_delivering(*state)) { + // Removed from one of its own callbacks: this is the topic's thread, so + // it can't be joined here. It exits once the callback returns. + std::lock_guard lk(mutex_); + stopping_topics_.push_back(std::move(state)); + continue; } + // waits for a callback in progress to return, then joins the thread + state->task->stop(); } - return true; } -bool EventManager::subscriber_task_fn(const std::string &topic, std::mutex &m, - std::condition_variable &cv, bool &task_notified) { - // get the data queue - SubscriberData *sub_data; +void EventManager::reap_stopped_topics() { + std::vector> finished; { - std::lock_guard lk(data_mutex_); - // find sub_data in `subscriber_data_` - if (!subscriber_data_.contains(topic)) { - // stop the task, we don't have valid subscriber data - return true; - } - sub_data = &subscriber_data_[topic]; + std::lock_guard lk(mutex_); + auto still_running = [](const std::shared_ptr &state) { + return state->task->is_started(); + }; + auto first_finished = + std::stable_partition(stopping_topics_.begin(), stopping_topics_.end(), still_running); + finished.insert(finished.end(), std::make_move_iterator(first_finished), + std::make_move_iterator(stopping_topics_.end())); + stopping_topics_.erase(first_finished, stopping_topics_.end()); } - // get the data - logger_.debug("Waiting on data for topic '{}'", topic); + // destroying them (without the lock) joins threads which have already returned + finished.clear(); +} + +bool EventManager::is_delivering(const Topic &topic) { return t_delivering_topic == &topic; } + +void EventManager::wait_for_delivery(Topic &topic) { + std::unique_lock lk(topic.m); + if (!topic.delivering) { + return; + } + const auto in_progress = topic.deliveries + 1; + topic.idle_cv.wait(lk, [&topic, in_progress] { return topic.deliveries >= in_progress; }); +} + +bool EventManager::deliver_next(Topic &topic) { + std::vector data; + std::shared_ptr subscribers; { - // wait on sub_data's mutex/cv - std::unique_lock lk(sub_data->m); - sub_data->cv.wait(lk, [&sub_data] { return sub_data->notified; }); - if (sub_data->deq.empty()) { - // stop the task, we were notified, but there was no data available. + std::unique_lock lk(topic.m); + topic.cv.wait(lk, [&topic] { return topic.stopping || !topic.queue.empty(); }); + if (topic.stopping) { + // stop the task; anything still queued is dropped with the topic return true; } + data = std::move(topic.queue.front()); + topic.queue.pop_front(); + subscribers = topic.subscribers; + topic.delivering = true; } - // we were woken up - that means there must be >= 1 element in the queue, - // so let's loop until we get all the data - while (true) { - logger_.debug("Getting data for topic '{}'", topic); - std::vector data; - { - std::unique_lock lk(sub_data->m); - if (sub_data->deq.empty()) { - // reset the notified flag - sub_data->notified = false; - // we've gotten all the data, so break out of the loop - break; - } - // set data to sub_data's deque front - data = sub_data->deq.front(); - // and pop the front data off - sub_data->deq.pop_front(); - } - // get all the callbacks - logger_.debug("Finding callbacks for topic '{}'", topic); - std::vector> *callbacks; - { - std::lock_guard lk(callbacks_mutex_); - if (!subscriber_callbacks_.contains(topic)) { - // stop the task, we don't have any callbacks anymore. - return true; - } - // copy here so that we don't hold this lock the whole time we're calling - // callbacks - callbacks = &subscriber_callbacks_[topic]; - } - // call all the callbacks - logger_.debug("Calling {} callbacks for topic '{}'", callbacks->size(), topic); - for (auto [comp, callback] : *callbacks) { - logger_.debug("Callback for '{}'", comp); - callback(data); + t_delivering_topic = &topic; + for (const auto &subscriber : *subscribers) { + if (!subscriber->removed) { + call_subscriber(topic.name, subscriber->component, subscriber->callback, data); } } - // we don't want to stop the task... + t_delivering_topic = nullptr; + // Let go of the snapshot before reporting the delivery finished: a removed + // subscriber's callback is then destroyed here, not after its remover has + // returned. + subscribers.reset(); + { + std::lock_guard lk(topic.m); + topic.delivering = false; + ++topic.deliveries; + } + topic.idle_cv.notify_all(); return false; } diff --git a/doc/en/core/event_manager.rst b/doc/en/core/event_manager.rst index a560b4025a..24a290c673 100644 --- a/doc/en/core/event_manager.rst +++ b/doc/en/core/event_manager.rst @@ -13,6 +13,24 @@ EventManager. As noted in a few places, it is recommended to use a (de-)serialization library such as espp::serialization / alpaca for transforming data structures to/from `std::vector` for publishing/subscribing. +Threads and callbacks +--------------------- + +Each topic's callbacks run one after another on that topic's thread, in the +order the subscribers were added, and data published on a topic is delivered +in the order it was published. One slow callback delays every other subscriber +of the same topic (but not other topics). + +Every function is thread safe and can be called from any thread, including from +inside a subscriber callback: a callback can publish, subscribe, or remove its +own subscription. When ``remove_subscriber()`` returns, that callback is not +running and will not be called again, so an object can call it from its +destructor and then be destroyed safely. To guarantee that, +``remove_subscriber()`` (and ``clear()``) wait for a callback of that topic that is +running on another thread to return, so don't call them while holding a lock +that the topic's callbacks take. Data still queued for a topic when its last +subscriber leaves is dropped. + .. ------------------------------- Example ------------------------------------- .. toctree:: diff --git a/lib/README.md b/lib/README.md index 3ea2ee1d18..9bc905f934 100644 --- a/lib/README.md +++ b/lib/README.md @@ -223,6 +223,12 @@ by hand: finalises, when a thread could no longer re-acquire the GIL at all. `python/blocking_destructors_test.py` covers delete-while-running and exit-while-running for each class (it is part of the wheel test command). +- `espp::EventManager` is a C++ singleton python never owns, so it has no + holder: its `remove_subscriber` / `clear` (which wait for a callback running + on the topic's thread) release the GIL, and the module's `atexit` hook calls + `EventManager::get().clear()` so its threads stop and its python callbacks + are destroyed while the interpreter is still alive + (`python/event_manager_test.py`, also in the wheel test command). The litgen dependency is unpinned and recent versions (0.20–0.22) regressed nested-scope/template generation, which is why this automation is needed. diff --git a/lib/autogenerate_bindings.py b/lib/autogenerate_bindings.py index 4bc36db682..2bd1077114 100644 --- a/lib/autogenerate_bindings.py +++ b/lib/autogenerate_bindings.py @@ -250,6 +250,8 @@ def _fix_rtsp_qualifications(code: str) -> str: "espp::RtspServer": ["start", "stop", "send_frame"], "espp::RtspSession": ["send_rtp_packet", "send_rtcp_packet"], "espp::ThreadPool": ["start", "stop", "submit"], + # wait for a callback running on the topic's thread (and join that thread) + "espp::EventManager": ["remove_subscriber", "clear"], } _GIL_GUARD = "py::call_guard()" diff --git a/lib/python_bindings/espp/__init__.pyi b/lib/python_bindings/espp/__init__.pyi index e2c538917f..7046913eb9 100644 --- a/lib/python_bindings/espp/__init__.pyi +++ b/lib/python_bindings/espp/__init__.pyi @@ -534,13 +534,29 @@ class EventManager: * @note In c++ objects, it's recommended to call the * add_publisher/add_subscriber functions in the class constructor and * then to call the remove_publisher/remove_subscriber functions in the - * class destructor. + * class destructor. When remove_subscriber() returns, the callback is + * not running and will not be called again, so the object can be + * destroyed safely right after it. + * + * @note Every function is thread safe and can be called from any thread, + * including from inside a subscriber callback (for example a callback + * that removes its own subscription). remove_subscriber() and clear() + * wait for a callback of that topic that is running on another thread + * to return, so don't call them while holding a lock which that + * topic's callbacks take. Called from one of the topic's own callbacks, + * they don't wait; the removed callbacks are not called again once the + * current one returns. + * + * @note Data published on a topic is queued and delivered in order on the + * topic's thread. Data still queued when the topic's last subscriber is + * removed is dropped. When C++ exceptions are enabled, an exception + * thrown by a callback is logged and the other callbacks still run. * * @note It is recommended (unless you are only interested in events and not * data or are only needing to transmit actual strings) to use a * serialization library (such as espp::serialization - which wraps - * alpaca) to serialize your data structures to string when publishing - * and then deserialize your data from string in the subscriber + * alpaca) to serialize your data structures to bytes when publishing + * and then deserialize your data from bytes in the subscriber * callbacks. * * \section event_manager_ex1 Event Manager Example @@ -558,6 +574,7 @@ class EventManager: pass + def add_publisher(self, topic: str, component: str) -> bool: """* * @brief Register a publisher for \p component on \p topic. @@ -580,15 +597,16 @@ class EventManager: """* * @brief Register a subscriber for \p component on \p topic. * @param topic Topic name for the data being subscribed to. - * @param component Name of the component publishing data. - * @param callback The event_callback_fn to be called when receicing data on + * @param component Name of the component subscribing to the data. + * @param callback The event_callback_fn to be called when receiving data on * \p topic. * @param stack_size_bytes The stack size in bytes to use for the subscriber * @note The stack size is only used if a subscriber is not already registered * for that topic. If a subscriber is already registered for that topic, * the stack size is ignored. * @return True if the subscriber was added, False if it was already - * registered for that component. + * registered for that component, the callback is empty, or the + * topic's thread could not be started. """ pass @@ -603,15 +621,16 @@ class EventManager: """* * @brief Register a subscriber for \p component on \p topic. * @param topic Topic name for the data being subscribed to. - * @param component Name of the component publishing data. - * @param callback The event_callback_fn to be called when receicing data on + * @param component Name of the component subscribing to the data. + * @param callback The event_callback_fn to be called when receiving data on * \p topic. * @param task_config The task configuration to use for the subscriber. * @note The task_config is only used if a subscriber is not already * registered for that topic. If a subscriber is already registered for * that topic, the task_config is ignored. * @return True if the subscriber was added, False if it was already - * registered for that component. + * registered for that component, the callback is empty, or the + * topic's thread could not be started. """ pass @@ -643,6 +662,11 @@ class EventManager: def remove_subscriber(self, topic: str, component: str) -> bool: """* * @brief Remove \p component's subscriber for \p topic. + * @details When it returns, the callback is not running and will not be + * called again, unless it was called from one of \p topic's own + * callbacks (then the callback is not called again once the + * current one returns). Removing the topic's last subscriber stops + * the topic's thread and drops any data still queued for it. * @param topic The topic that \p component was subscribing to. * @param component The component for which the subscriber was registered. * @return True if the subscriber was removed, False if it was not @@ -651,6 +675,16 @@ class EventManager: """ pass + def clear(self) -> None: + """* + * @brief Remove every publisher and subscriber and stop every topic's + * thread. + * @details Waits for callbacks running on other threads to return. The + * EventManager can be used again afterwards. + + """ + pass + #################### #################### diff --git a/lib/python_bindings/module.cpp b/lib/python_bindings/module.cpp index 7088d0d526..7e1f391e28 100644 --- a/lib/python_bindings/module.cpp +++ b/lib/python_bindings/module.cpp @@ -1,5 +1,6 @@ #include +#include "event_manager.hpp" #include "stop_registry.h" #define STRINGIFY(x) #x @@ -49,6 +50,14 @@ PYBIND11_MODULE(_espp, m) { // Stop the threads of every live Task / Timer / TrajectoryPlanner / ... before the interpreter // finalises (see stop_registry.h): their destructors run during finalisation, when a thread // waiting for the GIL to run its python callback could never get it, so the join would hang. - py::module_::import("atexit").attr("register")( - py::cpp_function([]() { espp::py_detail::StopRegistry::instance().stop_all(); })); + // + // The EventManager is a C++ singleton that python never owns, so it is not in the registry; its + // topic threads run python callbacks and it holds python callables. Stop the threads and drop the + // callables now, with the GIL released so a callback in progress can finish, instead of in its + // destructor at C++ static destruction, after the interpreter is gone. + py::module_::import("atexit").attr("register")(py::cpp_function([]() { + espp::py_detail::StopRegistry::instance().stop_all(); + py::gil_scoped_release release; + espp::EventManager::get().clear(); + })); } diff --git a/lib/python_bindings/pybind_espp.cpp b/lib/python_bindings/pybind_espp.cpp index 801a62240a..d68a6eddb5 100644 --- a/lib/python_bindings/pybind_espp.cpp +++ b/lib/python_bindings/pybind_espp.cpp @@ -279,13 +279,25 @@ void py_init_module_espp(py::module &m) { "new data is published.\n *\n * @note In c++ objects, it's recommended to call the\n * " " add_publisher/add_subscriber functions in the class constructor and\n * then " "to call the remove_publisher/remove_subscriber functions in the\n * class " - "destructor.\n *\n * @note It is recommended (unless you are only interested in events " - "and not\n * data or are only needing to transmit actual strings) to use a\n * " - " serialization library (such as espp::serialization - which wraps\n * alpaca) to " - "serialize your data structures to string when publishing\n * and then deserialize " - "your data from string in the subscriber\n * callbacks.\n *\n * \\section " - "event_manager_ex1 Event Manager Example\n * \\snippet event_manager_example.cpp event " - "manager example\n") + "destructor. When remove_subscriber() returns, the callback is\n * not running and " + "will not be called again, so the object can be\n * destroyed safely right after " + "it.\n *\n * @note Every function is thread safe and can be called from any thread,\n * " + " including from inside a subscriber callback (for example a callback\n * that " + "removes its own subscription). remove_subscriber() and clear()\n * wait for a " + "callback of that topic that is running on another thread\n * to return, so don't " + "call them while holding a lock which that\n * topic's callbacks take. Called from " + "one of the topic's own callbacks,\n * they don't wait; the removed callbacks are " + "not called again once the\n * current one returns.\n *\n * @note Data published " + "on a topic is queued and delivered in order on the\n * topic's thread. Data still " + "queued when the topic's last subscriber is\n * removed is dropped. When C++ " + "exceptions are enabled, an exception\n * thrown by a callback is logged and the " + "other callbacks still run.\n *\n * @note It is recommended (unless you are only " + "interested in events and not\n * data or are only needing to transmit actual " + "strings) to use a\n * serialization library (such as espp::serialization - which " + "wraps\n * alpaca) to serialize your data structures to bytes when publishing\n * " + " and then deserialize your data from bytes in the subscriber\n * callbacks.\n " + "*\n * \\section event_manager_ex1 Event Manager Example\n * \\snippet " + "event_manager_example.cpp event manager example\n") .def_static("get", &espp::EventManager::get, "*\n * @brief Get the singleton instance of the EventManager.\n * " "@return A reference to the EventManager singleton.\n", @@ -304,13 +316,14 @@ void py_init_module_espp(py::module &m) { py::arg("stack_size_bytes") = 8192, "*\n * @brief Register a subscriber for \\p component on \\p topic.\n * @param " "topic Topic name for the data being subscribed to.\n * @param component Name of " - "the component publishing data.\n * @param callback The event_callback_fn to be " - "called when receicing data on\n * \\p topic.\n * @param " + "the component subscribing to the data.\n * @param callback The event_callback_fn " + "to be called when receiving data on\n * \\p topic.\n * @param " "stack_size_bytes The stack size in bytes to use for the subscriber\n * @note The " "stack size is only used if a subscriber is not already registered\n * for " "that topic. If a subscriber is already registered for that topic,\n * the " "stack size is ignored.\n * @return True if the subscriber was added, False if it " - "was already\n * registered for that component.\n") + "was already\n * registered for that component, the callback is empty, or " + "the\n * topic's thread could not be started.\n") .def("add_subscriber", py::overload_cast()) + .def("clear", &espp::EventManager::clear, + "*\n * @brief Remove every publisher and subscriber and stop every topic's\n * " + " thread.\n * @details Waits for callbacks running on other threads to " + "return. The\n * EventManager can be used again afterwards.\n", + py::call_guard()); //////////////////// //////////////////// //////////////////// //////////////////// diff --git a/pc/tests/event_manager.cpp b/pc/tests/event_manager.cpp new file mode 100644 index 0000000000..7913c78a7a --- /dev/null +++ b/pc/tests/event_manager.cpp @@ -0,0 +1,428 @@ +// Host test for espp::EventManager: the pub/sub API plus the concurrency cases +// that used to hang, crash, or corrupt memory (removing the last subscriber +// while its callback ran, a callback removing itself, subscribers added or +// removed during a delivery, publish racing the last removal, a re-subscribe +// racing the last removal, new topics racing publish, destruction with live +// subscribers). Runs under TSan and ASan in host_sanitizers.yml. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "event_manager.hpp" +#include "logger.hpp" + +using namespace std::chrono_literals; + +namespace { +// The constructor is protected (EventManager is a singleton); a derived class +// gives each case a fresh instance, and lets a case destroy one. +struct TestEventManager : public espp::EventManager { + TestEventManager() { set_log_level(espp::Logger::Verbosity::ERROR); } +}; + +using Data = std::vector; + +struct Latch { + std::mutex m; + std::condition_variable cv; + bool open = false; + void release() { + { + std::lock_guard lk(m); + open = true; + } + cv.notify_all(); + } + bool wait(std::chrono::milliseconds timeout = 10s) { + std::unique_lock lk(m); + return cv.wait_for(lk, timeout, [this] { return open; }); + } +}; + +template +bool wait_until(Predicate &&pred, std::chrono::milliseconds timeout = 10s) { + auto deadline = std::chrono::steady_clock::now() + timeout; + while (std::chrono::steady_clock::now() < deadline) { + if (pred()) { + return true; + } + std::this_thread::sleep_for(1ms); + } + return pred(); +} + +// A subscriber callback that always throws. +void throw_expected(const Data &) { throw std::runtime_error("expected: a callback that throws"); } + +// Run fn on another thread; false if it hasn't returned within the timeout (the +// thread is then left running and the test fails). +template bool returns_within(Fn &&fn, std::chrono::milliseconds timeout) { + auto done = std::make_shared>(false); + std::thread([fn = std::forward(fn), done]() mutable { + fn(); + *done = true; + }).detach(); + return wait_until([&] { return done->load(); }, timeout); +} +} // namespace + +int main() { + espp::Logger logger({.tag = "EventManager Test", .level = espp::Logger::Verbosity::INFO}); + int total_passed = 0; + int total_tests = 0; + auto check = [&](bool condition, const std::string &desc) -> bool { + ++total_tests; + if (condition) { + ++total_passed; + logger.info(" PASS: {}", desc); + } else { + logger.error(" FAIL: {}", desc); + } + return condition; + }; + + // A hang (the old remove_subscriber join) fails the test instead of hanging CI. + std::thread([] { + std::this_thread::sleep_for(240s); + std::fprintf(stderr, "FAIL: event_manager test did not finish within 240 s\n"); + std::_Exit(1); + }).detach(); + + logger.info("--- registration and delivery ---"); + { + TestEventManager em; + const Data payload{1, 2, 3}; + check(!em.publish("t", payload), "publish without subscribers returns false"); + std::mutex m; + std::vector calls; + auto record = [&](const std::string &who) { + return [&, who](const Data &data) { + std::lock_guard lk(m); + calls.push_back(who + ":" + std::to_string(data.size())); + }; + }; + check(em.add_subscriber("t", "a", record("a")), "add_subscriber"); + check(!em.add_subscriber("t", "a", record("a")), "duplicate add_subscriber returns false"); + check(!em.add_subscriber("t", "empty", espp::EventManager::event_callback_fn{}), + "add_subscriber with an empty callback returns false"); + check(em.add_subscriber("t", "b", record("b"), + espp::Task::BaseConfig{.name = "t sub", .stack_size_bytes = 8192}), + "add_subscriber with a task config"); + check(em.publish("t", payload), "publish with subscribers returns true"); + check(em.publish("t", Data{9}), "second publish"); + check(wait_until([&] { + std::lock_guard lk(m); + return calls.size() == 4; + }), + "both events delivered to both subscribers"); + { + std::lock_guard lk(m); + check(calls == std::vector{"a:3", "b:3", "a:1", "b:1"}, + "delivered in publish order, subscribers in registration order"); + } + check(!em.remove_subscriber("t", "nobody"), "remove_subscriber of an unknown component"); + check(!em.remove_subscriber("nowhere", "a"), "remove_subscriber of an unknown topic"); + check(em.add_publisher("t", "p"), "add_publisher"); + check(!em.add_publisher("t", "p"), "duplicate add_publisher returns false"); + check(em.remove_publisher("t", "p"), "remove_publisher"); + check(!em.remove_publisher("t", "p"), "remove_publisher twice returns false"); + check(em.remove_subscriber("t", "a") && em.remove_subscriber("t", "b"), + "remove both subscribers"); + check(!em.publish("t", payload), "publish after the last subscriber left returns false"); + } + + logger.info("--- a callback removes its own subscription ---"); + { + TestEventManager em; + std::atomic calls{0}; + std::atomic removed{false}; + em.add_subscriber("once", "one-shot", [&](const Data &) { + calls++; + removed = em.remove_subscriber("once", "one-shot"); + }); + em.publish("once", Data{1}); + check(wait_until([&] { return removed.load(); }), + "remove_subscriber from its own callback returns true (used to std::terminate)"); + check(!em.publish("once", Data{2}), "the topic is gone afterwards"); + std::atomic again{0}; + check(em.add_subscriber("once", "again", [&](const Data &) { again++; }), + "the topic can be subscribed to again"); + em.publish("once", Data{3}); + check(wait_until([&] { return again == 1; }), "and delivers to the new subscriber"); + check(calls == 1, "the one-shot callback ran exactly once"); + } + + logger.info("--- a callback removes its own subscription, others remain ---"); + { + TestEventManager em; + std::atomic a_calls{0}, b_calls{0}; + em.add_subscriber("t", "a", [&](const Data &) { + a_calls++; + em.remove_subscriber("t", "a"); + }); + em.add_subscriber("t", "b", [&](const Data &) { b_calls++; }); + for (int i = 0; i < 5; ++i) { + em.publish("t", Data{1}); + } + check(wait_until([&] { return b_calls == 5; }), "the other subscriber gets every event"); + check(a_calls == 1, "the removed callback ran once"); + } + + logger.info("--- a callback removes a later subscriber of the same delivery ---"); + { + TestEventManager em; + std::atomic b_calls{0}, c_calls{0}; + em.add_subscriber("t", "a", [&](const Data &) { em.remove_subscriber("t", "b"); }); + em.add_subscriber("t", "b", [&](const Data &) { b_calls++; }); + em.add_subscriber("t", "c", [&](const Data &) { c_calls++; }); + em.publish("t", Data{1}); + check(wait_until([&] { return c_calls == 1; }), "the delivery continues past it"); + check(b_calls == 0, "the removed subscriber is skipped in that same delivery"); + } + + logger.info("--- subscribers added during a delivery ---"); + { + TestEventManager em; + Latch in_a, finish_a; + std::atomic b_calls{0}, late_calls{0}; + em.add_subscriber("t", "a", [&](const Data &) { + in_a.release(); + finish_a.wait(); + }); + em.add_subscriber("t", "b", [&](const Data &) { b_calls++; }); + em.publish("t", Data{1}); + check(in_a.wait(), "first callback running"); + for (int i = 0; i < 16; ++i) { // grows the list the delivery iterates (used to be a UAF) + em.add_subscriber("t", "late " + std::to_string(i), [&](const Data &) { late_calls++; }); + } + finish_a.release(); + check(wait_until([&] { return b_calls == 1; }), "the delivery in progress finishes"); + em.publish("t", Data{2}); + check(wait_until([&] { return late_calls == 16 && b_calls == 2; }), + "the added subscribers get the next event"); + } + + logger.info("--- remove_subscriber waits for that callback to return ---"); + { + TestEventManager em; + Latch in_a, finish_a; + std::atomic a_running{false}; + std::atomic a_calls{0}, b_calls{0}; + em.add_subscriber("t", "a", [&](const Data &) { + a_calls++; + a_running = true; + in_a.release(); + finish_a.wait(); + a_running = false; + }); + em.add_subscriber("t", "b", [&](const Data &) { b_calls++; }); + em.publish("t", Data{1}); + check(in_a.wait(), "callback a running"); + std::atomic removed{false}; + std::atomic running_when_removed{true}; + std::thread remover([&] { + em.remove_subscriber("t", "a"); + running_when_removed = a_running.load(); + removed = true; + }); + std::this_thread::sleep_for(100ms); + check(!removed, "remove_subscriber is still waiting while the callback runs"); + finish_a.release(); + remover.join(); + check(!running_when_removed, "the callback had returned when remove_subscriber returned"); + em.publish("t", Data{2}); + check(wait_until([&] { return b_calls == 2; }), "the remaining subscriber keeps receiving"); + check(a_calls == 1, "the removed callback is not called again"); + } + + logger.info("--- removing the last subscriber while its callback runs ---"); + { + // The old code could leave the topic thread waiting forever and hang this + // removal in join(); also checks the callback is done when it returns. + TestEventManager em; + bool ok = true; + for (int round = 0; round < 200 && ok; ++round) { + std::atomic running{false}; + std::atomic calls{0}; + em.add_subscriber("t", "s", [&](const Data &) { + running = true; + calls++; + std::this_thread::sleep_for(std::chrono::microseconds(50)); + running = false; + }); + for (int i = 0; i < 4; ++i) { + em.publish("t", Data{1}); + } + std::this_thread::sleep_for(std::chrono::microseconds(round % 5 * 40)); + ok = returns_within([&] { em.remove_subscriber("t", "s"); }, 5s); + int calls_at_removal = calls; + ok = ok && !running; + std::this_thread::sleep_for(1ms); + ok = ok && calls == calls_at_removal; + } + check(ok, "200 removals returned, with the callback finished and never called again"); + } + + logger.info("--- publish racing the last removal ---"); + { + TestEventManager em; + std::atomic stop{false}; + std::thread publisher([&] { + while (!stop) { + em.publish("t", Data{1, 2, 3}); + } + }); + for (int i = 0; i < 1000; ++i) { + em.add_subscriber("t", "s", [](const Data &) {}); + em.remove_subscriber("t", "s"); + } + stop = true; + publisher.join(); + check(true, "1000 subscribe / unsubscribe cycles while publishing (used to be a UAF)"); + } + + logger.info("--- re-subscribing while the last subscriber leaves ---"); + { + TestEventManager em; + int lost = 0; + for (int round = 0; round < 300; ++round) { + std::atomic got{false}; + em.add_subscriber("t", "old", [](const Data &) {}); + std::thread a([&] { em.remove_subscriber("t", "old"); }); + std::thread b([&] { em.add_subscriber("t", "new", [&](const Data &) { got = true; }); }); + a.join(); + b.join(); + em.publish("t", Data{1}); + if (!wait_until([&] { return got.load(); }, 2s)) { + ++lost; + } + em.remove_subscriber("t", "new"); + } + check(lost == 0, "the new subscriber received data in every one of 300 rounds (lost " + + std::to_string(lost) + ")"); + } + + logger.info("--- new topics while another topic is busy ---"); + { + TestEventManager em; + std::atomic got{0}; + em.add_subscriber("busy", "rx", [&](const Data &) { got++; }); + std::atomic stop{false}; + std::thread publisher([&] { + while (!stop) { + em.publish("busy", Data{1}); + } + }); + for (int i = 0; i < 200; ++i) { + auto topic = "new " + std::to_string(i); + em.add_subscriber(topic, "x", [](const Data &) {}); + em.publish(topic, Data{2}); + em.remove_subscriber(topic, "x"); + } + stop = true; + publisher.join(); + check(got > 0, "200 topics created and removed while publishing (used to race the map)"); + } + + logger.info("--- a callback publishing on its own topic ---"); + { + TestEventManager em; + std::atomic calls{0}; + em.add_subscriber("t", "echo", [&](const Data &data) { + calls++; + if (data[0] < 5) { + em.publish("t", Data{static_cast(data[0] + 1)}); + } + }); + em.publish("t", Data{1}); + check(wait_until([&] { return calls == 5; }), "each event queues the next one"); + } + + logger.info("--- a callback removing a subscriber of another topic ---"); + { + TestEventManager em; + std::atomic other_calls{0}; + std::atomic removed{false}; + em.add_subscriber("other", "o", [&](const Data &) { other_calls++; }); + em.add_subscriber("other", "o2", [](const Data &) {}); + em.add_subscriber("t", "s", + [&](const Data &) { removed = em.remove_subscriber("other", "o"); }); + em.publish("other", Data{1}); + check(wait_until([&] { return other_calls == 1; }), "other topic delivered"); + em.publish("t", Data{1}); + check(wait_until([&] { return removed.load(); }), "removed from a callback of another topic"); + em.publish("other", Data{2}); + std::this_thread::sleep_for(20ms); + check(other_calls == 1, "and it is not called again"); + } + + logger.info("--- a callback that throws ---"); + { + TestEventManager em; + std::atomic after{0}; + em.add_subscriber("t", "thrower", throw_expected); + em.add_subscriber("t", "after", [&](const Data &) { after++; }); + em.publish("t", Data{1}); + em.publish("t", Data{2}); + check(wait_until([&] { return after == 2; }), + "the other callbacks and later events still run (used to std::terminate)"); + } + + logger.info("--- clear() ---"); + { + TestEventManager em; + std::atomic calls{0}; + em.add_publisher("t", "p"); + em.add_subscriber("t", "a", [&](const Data &) { calls++; }); + em.add_subscriber("u", "b", [&](const Data &) { calls++; }); + em.clear(); + check(!em.publish("t", Data{1}) && !em.publish("u", Data{1}), "nothing to publish to"); + check(!em.remove_publisher("t", "p"), "publishers are gone too"); + check(em.add_subscriber("t", "a", [&](const Data &) { calls++; }), "usable afterwards"); + em.publish("t", Data{1}); + check(wait_until([&] { return calls == 1; }), "and delivers"); + std::atomic cleared{false}; + em.add_subscriber("c", "clearer", [&](const Data &) { + em.clear(); + cleared = true; + }); + em.publish("c", Data{1}); + check(wait_until([&] { return cleared.load(); }), "clear() from inside a callback returns"); + check(!em.publish("t", Data{1}), "and removed everything"); + } + + logger.info("--- destroying it with live subscribers ---"); + { + auto em = std::make_unique(); + Latch in_callback; + std::atomic finished{false}; + em->add_subscriber("idle", "i", [](const Data &) {}); + em->add_subscriber("busy", "b", [&](const Data &) { + in_callback.release(); + std::this_thread::sleep_for(100ms); + finished = true; + }); + em->publish("busy", Data{1}); + check(in_callback.wait(), "a callback is running"); + auto *raw = em.release(); + check(returns_within([raw] { delete raw; }, 5s), + "the destructor returns (used to hang joining an idle topic thread)"); + check(finished, "after the running callback returned"); + } + + logger.info("{} / {} checks passed", total_passed, total_tests); + if (total_passed != total_tests) { + logger.error("FAILED"); + return 1; + } + logger.info("ALL PASS"); + return 0; +} diff --git a/pyproject.toml b/pyproject.toml index d56bf84c5c..20bf5b388f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -132,8 +132,10 @@ skip = ["*-musllinux_*", "*_i686", "*-win32"] # start(), stop ordering), and run the # self-contained stream_frame / Dispatcher binding test, the blocking-destructor test # (deleting / exiting with a running Task / Timer / TrajectoryPlanner must not deadlock), -# and the pure-python persistent_data codec test (byte-checked against C++ vectors). -test-command = "python \"{project}/python/rtps_bindings_smoke.py\" && python \"{project}/python/rtps_bindings_misuse_test.py\" && python \"{project}/python/dispatcher_test.py\" && python \"{project}/python/blocking_destructors_test.py\" && python \"{project}/python/persistent_data_test.py\"" +# the pure-python persistent_data codec test (byte-checked against C++ vectors), and the +# EventManager test (removing / clearing while a python callback runs, exiting with live +# subscribers). +test-command = "python \"{project}/python/rtps_bindings_smoke.py\" && python \"{project}/python/rtps_bindings_misuse_test.py\" && python \"{project}/python/dispatcher_test.py\" && python \"{project}/python/blocking_destructors_test.py\" && python \"{project}/python/persistent_data_test.py\" && python \"{project}/python/event_manager_test.py\"" [tool.cibuildwheel.linux] # The repo is mounted at /project inside the manylinux container; git must diff --git a/python/event_manager_test.py b/python/event_manager_test.py new file mode 100644 index 0000000000..e3e2da9adb --- /dev/null +++ b/python/event_manager_test.py @@ -0,0 +1,212 @@ +"""EventManager test for the espp python bindings. + +Covers the pub/sub API and its misuse, plus the cases that need the GIL +handled right: remove_subscriber() / clear() wait for a callback running on +the topic's thread (so they release the GIL, or a python callback could never +finish), a callback that removes its own subscription, and exiting the +interpreter with live subscribers (the module's atexit hook clears the +EventManager while python can still run and destroy the callbacks). + +Each case runs in a child interpreter under a timeout, so a regression shows +up as a failed case rather than a hung test. + +Exit code 0 on full pass, 1 on any failure. +""" + +import os +import subprocess +import sys +import time + +TIMEOUT_S = 15.0 + +# Shared by the cases: wait for a condition without hanging the case. +PRELUDE = """ +import threading, time, espp +em = espp.EventManager.get() +def wait_for(pred, timeout=5.0): + deadline = time.time() + timeout + while time.time() < deadline: + if pred(): + return True + time.sleep(0.001) + return pred() +""" + +CASES = { + "basics": """ +assert em.publish("t", [1, 2, 3]) is False # no subscribers yet +got = [] +assert em.add_subscriber("t", "a", lambda data: got.append(("a", list(data)))) is True +assert em.add_subscriber("t", "a", lambda data: None) is False # already subscribed +assert em.add_subscriber("t", "none", None) is False # empty callback +cfg = espp.Task.BaseConfig("t subscriber", stack_size_bytes=8192) +assert em.add_subscriber("t", "b", lambda data: got.append(("b", list(data))), cfg) is True +assert em.add_subscriber("u", "c", lambda data: got.append(("c", list(data))), stack_size_bytes=8192) +assert em.publish("t", [1, 2, 3]) is True +assert em.publish("t", [9]) is True +assert em.publish("u", []) is True +assert wait_for(lambda: len(got) == 5), got +t_events = [g for g in got if g[0] != "c"] +assert t_events == [("a", [1, 2, 3]), ("b", [1, 2, 3]), ("a", [9]), ("b", [9])], t_events +assert ("c", []) in got +assert em.remove_subscriber("t", "nobody") is False +assert em.remove_subscriber("nowhere", "a") is False +assert em.add_publisher("t", "p") is True +assert em.add_publisher("t", "p") is False +assert em.remove_publisher("t", "p") is True +assert em.remove_publisher("t", "p") is False +assert em.remove_subscriber("t", "a") is True +assert em.remove_subscriber("t", "b") is True +assert em.publish("t", [1]) is False # last subscriber gone +assert em.remove_subscriber("u", "c") is True +print("basics ok") +""", + "misuse": """ +def raises_type_error(fn): + try: + fn() + except TypeError: + return True + return False +assert raises_type_error(lambda: em.publish("t", "not a list of ints")) +assert raises_type_error(lambda: em.publish("t", [1, 2, 300])) # not a byte +assert raises_type_error(lambda: em.publish("t")) +assert raises_type_error(lambda: em.add_subscriber("t", "c", 5)) # not callable +assert raises_type_error(lambda: em.add_subscriber("t", "c")) +assert raises_type_error(lambda: em.remove_subscriber(1, 2)) +assert raises_type_error(lambda: espp.EventManager()) # singleton: get() only +assert em is espp.EventManager.get() +# a callback that raises: the error is reported by python, the subscriber thread keeps going +calls = [0] +def flaky(data): + calls[0] += 1 + if calls[0] == 1: + raise ValueError("expected: first delivery raises") +assert em.add_subscriber("t", "flaky", flaky) +em.publish("t", [1]) +em.publish("t", [2]) +assert wait_for(lambda: calls[0] == 2), calls +print("misuse ok") +""", + # remove_subscriber() from the main thread while the python callback runs: it waits for + # the callback, which needs the GIL to finish, so the binding must release the GIL. + "remove_while_callback_runs": """ +started = threading.Event(); state = {"done": False, "calls": 0} +def slow(data): + state["calls"] += 1 + started.set() + time.sleep(0.3) + state["done"] = sum(range(1000)) > 0 # python work after the sleep needs the GIL +assert em.add_subscriber("t", "slow", slow) +assert em.add_subscriber("t", "other", lambda data: None) +em.publish("t", [1]) +assert started.wait(5) +t0 = time.time() +assert em.remove_subscriber("t", "slow") is True +dt = time.time() - t0 +assert state["done"], "remove_subscriber returned while the callback was still running" +em.publish("t", [2]) +time.sleep(0.1) +assert state["calls"] == 1, state +print("remove_while_callback_runs ok", round(dt, 3)) +""", + "remove_last_while_callback_runs": """ +started = threading.Event(); state = {"done": False} +def slow(data): + started.set() + time.sleep(0.3) + state["done"] = True +assert em.add_subscriber("t", "slow", slow) +em.publish("t", [1]) +assert started.wait(5) +assert em.remove_subscriber("t", "slow") is True +assert state["done"] +assert em.publish("t", [2]) is False +print("remove_last_while_callback_runs ok") +""", + "clear_while_callback_runs": """ +started = threading.Event(); state = {"done": False} +def slow(data): + started.set() + time.sleep(0.3) + state["done"] = True +assert em.add_subscriber("t", "slow", slow) +assert em.add_subscriber("u", "idle", lambda data: None) +em.add_publisher("t", "p") +em.publish("t", [1]) +assert started.wait(5) +em.clear() +assert state["done"] +assert em.publish("t", [1]) is False and em.publish("u", [1]) is False +assert em.remove_publisher("t", "p") is False +got = [] +assert em.add_subscriber("t", "again", lambda data: got.append(list(data))) +em.publish("t", [7]) +assert wait_for(lambda: got == [[7]]), got +print("clear_while_callback_runs ok") +""", + "callback_removes_itself": """ +state = {"calls": 0, "removed": None} +def once(data): + state["calls"] += 1 + state["removed"] = em.remove_subscriber("t", "once") +assert em.add_subscriber("t", "once", once) +em.publish("t", [1]) +assert wait_for(lambda: state["removed"] is not None) +assert state["removed"] is True +assert em.publish("t", [2]) is False +assert state["calls"] == 1 +print("callback_removes_itself ok") +""", + # leave subscribers registered at exit, one of them idle and one mid-callback + "exit_with_live_subscribers": """ +started = threading.Event() +def slow(data): + started.set() + time.sleep(0.2) +assert em.add_subscriber("idle", "i", lambda data: None) +assert em.add_subscriber("busy", "b", slow) +em.publish("idle", [1]) +em.publish("busy", [1]) +assert started.wait(5) +print("exit_with_live_subscribers ok") +""", + # an unhandled exception with live subscribers must still exit (with status 1) + "exception_with_live_subscribers": """ +assert em.add_subscriber("t", "s", lambda data: time.sleep(0.01)) +for i in range(10): + em.publish("t", [i]) +raise RuntimeError("expected: unhandled exception with live subscribers") +""", +} +EXPECTED_EXIT = {"exception_with_live_subscribers": 1} + + +def run_case(name: str, code: str) -> bool: + t0 = time.time() + try: + proc = subprocess.run([sys.executable, "-u", "-c", PRELUDE + code], capture_output=True, + text=True, timeout=TIMEOUT_S, env=os.environ.copy()) + except subprocess.TimeoutExpired as e: + print(f"FAIL {name}: timed out after {TIMEOUT_S:.0f} s (hang)\n{(e.stdout or b'')}") + return False + dt = time.time() - t0 + expected = EXPECTED_EXIT.get(name, 0) + if proc.returncode != expected: + sig = f" (signal {-proc.returncode})" if proc.returncode < 0 else "" + print(f"FAIL {name}: exit {proc.returncode}{sig}, expected {expected}\n{proc.stdout}{proc.stderr}") + return False + print(f"PASS {name} ({dt:.2f} s): {proc.stdout.strip().splitlines()[-1] if proc.stdout.strip() else ''}") + return True + + +def main() -> int: + results = [run_case(name, code) for name, code in CASES.items()] + passed = sum(results) + print(f"{passed}/{len(results)} cases passed") + return 0 if all(results) else 1 + + +if __name__ == "__main__": + sys.exit(main()) From 0c0650c38dc67e5c61eb139a3eebcec66a832862 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Thu, 26 Nov 2026 13:49:14 -0700 Subject: [PATCH 2/2] fix(event_manager): wait only for the removed callback, and never deadlock 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 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/event_manager/README.md | 13 +- .../event_manager/include/event_manager.hpp | 113 +++-- .../event_manager/src/event_manager.cpp | 370 ++++++++++++----- doc/en/core/event_manager.rst | 15 +- lib/python_bindings/espp/__init__.pyi | 57 +-- lib/python_bindings/pybind_espp.cpp | 81 ++-- lib/python_bindings/stop_registry.h | 5 +- pc/tests/event_manager.cpp | 389 +++++++++++++++++- python/event_manager_test.py | 18 +- 9 files changed, 841 insertions(+), 220 deletions(-) diff --git a/components/event_manager/README.md b/components/event_manager/README.md index efb4bb2e8c..5af6933d09 100644 --- a/components/event_manager/README.md +++ b/components/event_manager/README.md @@ -26,9 +26,16 @@ inside a subscriber callback: a callback can publish, subscribe, or remove its own subscription. When `remove_subscriber()` returns, that callback is not running and will not be called again, so an object can call it from its destructor and then be destroyed safely. To guarantee that, -`remove_subscriber()` (and `clear()`) wait for a callback of that topic that is -running on another thread to return, so don't call them while holding a lock -that the topic's callbacks take. Data still queued for a topic when its last +`remove_subscriber()` (and `clear()`) wait for the callback they remove if it is +running on another thread, so don't call them while holding a lock that the +callback takes. They can't wait in two cases, which would deadlock: when called +from that callback itself, and when that callback is waiting in turn for the +caller (callbacks of two topics removing each other's subscribers). + +The wait runs at the topic task's priority, which is 0 unless the +`task_config` passed to `add_subscriber()` sets one, so a high priority task +removing a subscriber can be held up by a low priority topic. `add_subscriber()` +returns false while `clear()` runs. Data still queued for a topic when its last subscriber leaves is dropped. ## Example diff --git a/components/event_manager/include/event_manager.hpp b/components/event_manager/include/event_manager.hpp index c80d5b7fb3..f59b583832 100644 --- a/components/event_manager/include/event_manager.hpp +++ b/components/event_manager/include/event_manager.hpp @@ -1,6 +1,5 @@ #pragma once -#include #include #include #include @@ -29,16 +28,18 @@ namespace espp { * then to call the remove_publisher/remove_subscriber functions in the * class destructor. When remove_subscriber() returns, the callback is * not running and will not be called again, so the object can be - * destroyed safely right after it. + * destroyed safely right after it (see remove_subscriber() for the two + * cases where it can't wait). * * @note Every function is thread safe and can be called from any thread, * including from inside a subscriber callback (for example a callback * that removes its own subscription). remove_subscriber() and clear() - * wait for a callback of that topic that is running on another thread - * to return, so don't call them while holding a lock which that - * topic's callbacks take. Called from one of the topic's own callbacks, - * they don't wait; the removed callbacks are not called again once the - * current one returns. + * wait for a callback they remove that is running on another thread to + * return, so don't call them while holding a lock which that callback + * takes. They wait at the topic task's priority: a high priority caller + * can be held up by a topic whose task has a low priority + * (Task::BaseConfig::priority, 0 by default), so give the topic's + * task_config a priority that suits the code removing its subscribers. * * @note Data published on a topic is queued and delivered in order on the * topic's thread. Data still queued when the topic's last subscriber is @@ -100,12 +101,13 @@ class EventManager : public espp::BaseComponent { * @param callback The event_callback_fn to be called when receiving data on * \p topic. * @param stack_size_bytes The stack size in bytes to use for the subscriber - * @note The stack size is only used if a subscriber is not already registered - * for that topic. If a subscriber is already registered for that topic, - * the stack size is ignored. + * @note The stack size is only used when the topic's thread is created. If + * a subscriber is already registered for that topic (or the topic's + * thread is still finishing a delivery after its last subscriber was + * removed, and is reused), the stack size is ignored. * @return True if the subscriber was added, false if it was already - * registered for that component, the callback is empty, or the - * topic's thread could not be started. + * registered for that component, the callback is empty, clear() is + * running, or the topic's thread could not be started. */ bool add_subscriber(const std::string &topic, const std::string &component, const espp::EventManager::event_callback_fn &callback, @@ -118,12 +120,13 @@ class EventManager : public espp::BaseComponent { * @param callback The event_callback_fn to be called when receiving data on * \p topic. * @param task_config The task configuration to use for the subscriber. - * @note The task_config is only used if a subscriber is not already - * registered for that topic. If a subscriber is already registered for - * that topic, the task_config is ignored. + * @note The task_config is only used when the topic's thread is created. If + * a subscriber is already registered for that topic (or the topic's + * thread is still finishing a delivery after its last subscriber was + * removed, and is reused), the task_config is ignored. * @return True if the subscriber was added, false if it was already - * registered for that component, the callback is empty, or the - * topic's thread could not be started. + * registered for that component, the callback is empty, clear() is + * running, or the topic's thread could not be started. */ bool add_subscriber(const std::string &topic, const std::string &component, const espp::EventManager::event_callback_fn &callback, @@ -151,22 +154,29 @@ class EventManager : public espp::BaseComponent { /** * @brief Remove \p component's subscriber for \p topic. * @details When it returns, the callback is not running and will not be - * called again, unless it was called from one of \p topic's own - * callbacks (then the callback is not called again once the - * current one returns). Removing the topic's last subscriber stops - * the topic's thread and drops any data still queued for it. + * called again, and it has been destroyed unless it was still + * running (it is then destroyed on the topic's thread once it + * returns). It can't wait for the callback in two cases, which + * would deadlock: when called from that callback itself, and when + * the callback is waiting in turn for the calling thread (callbacks + * of two topics removing each other's subscribers). Removing the + * topic's last subscriber stops the topic's thread and drops any + * data still queued for it. * @param topic The topic that \p component was subscribing to. * @param component The component for which the subscriber was registered. * @return True if the subscriber was removed, false if it was not - * registered. + * registered. It waits for the callback in both cases: one that + * removed itself (or that clear() removed) can still be running. */ bool remove_subscriber(const std::string &topic, const std::string &component); /** * @brief Remove every publisher and subscriber and stop every topic's * thread. - * @details Waits for callbacks running on other threads to return. The - * EventManager can be used again afterwards. + * @details Waits for callbacks running on other threads to return (except + * in the two cases described in remove_subscriber()). + * add_subscriber() returns false while it runs. The EventManager + * can be used again afterwards. */ void clear(); @@ -182,8 +192,11 @@ class EventManager : public espp::BaseComponent { : component(component) , callback(callback) {} const std::string component; - const event_callback_fn callback; - std::atomic removed{false}; ///< Set when removed; deliveries skip it from then on. + /// Called by the topic's thread only while Topic::calling points at this + /// subscriber. Once it is removed and not running, its remover takes it + /// out, so that it is destroyed by remove_subscriber(). + event_callback_fn callback; + bool removed{false}; ///< Guarded by Topic::m. Set when removed; never called from then on. }; using SubscriberList = std::vector>; @@ -192,33 +205,53 @@ class EventManager : public espp::BaseComponent { struct Topic { explicit Topic(const std::string &name) : name(name) {} + /// Stops the topic's thread and joins it. + ~Topic(); const std::string name; - std::mutex m; ///< Guards everything below except task. - std::condition_variable cv; ///< Wakes the topic's thread (data queued or stopping). - std::condition_variable idle_cv; ///< Signalled when a delivery finishes. + std::mutex m; ///< Guards the members below, up to subscribers. + std::condition_variable cv; ///< Wakes the topic's thread (data queued or stopping). + /// Signalled when a callback or a delivery finishes, or the topic is reused. + std::condition_variable idle_cv; std::deque> queue; - bool stopping{false}; ///< Set once, when the topic loses its last subscriber. - bool delivering{false}; ///< True while the topic's thread is running callbacks. - uint64_t deliveries{0}; ///< Number of finished deliveries. + /// Set when the topic loses its last subscriber. Cleared again if a new + /// subscriber reuses the topic before its thread has exited. + bool stopping{false}; + bool exited{false}; ///< Set by the topic's thread when it sees stopping and exits. + /// True while the topic's thread delivers an event: from taking the + /// subscriber snapshot until it has let go of it again. + bool busy{false}; + const Subscriber *calling{nullptr}; ///< The subscriber whose callback is running. /// Replaced, never changed in place, with both EventManager::mutex_ and m /// held, so holding either one is enough to read it. std::shared_ptr subscribers; - /// Declared last so it is destroyed (joining the thread) first. + /// What the topic's thread is waiting for while it is blocked in + /// remove_subscriber() or clear(): a callback of *waiting_for on + /// waiting_on, or (waiting_for null) the end of waiting_on's last + /// delivery. Guarded by the wait-graph mutex; used to skip a wait that + /// would deadlock. + Topic *waiting_on{nullptr}; + const std::string *waiting_for{nullptr}; std::unique_ptr task; }; static bool deliver_next(Topic &topic); + static Topic *delivering_topic(); static bool is_delivering(const Topic &topic); - static void wait_for_delivery(Topic &topic); - void stop_topics(std::vector> topics); - void reap_stopped_topics(); + static bool is_running(const Topic &topic, const std::string *component); + static bool waits_for(const Topic &from, const Topic &self); + static bool wait_while_running(Topic &topic, const std::string *component); + static void retire(Topic &topic); + static bool revive(Topic &topic, const std::shared_ptr &subscriber, + std::shared_ptr &replaced); + void take_finished_topics(std::vector> &finished); std::mutex mutex_; ///< Guards the members below. std::unordered_map> publishers_; std::unordered_map> topics_; - /// Topics that lost their last subscriber from inside one of their own - /// callbacks: their thread exits on its own and is joined later (by - /// reap_stopped_topics(), clear(), or the destructor). - std::vector> stopping_topics_; + /// Topics that lost their last subscriber and whose thread hasn't been + /// joined yet. One is joined once its thread is no longer delivering, by + /// whichever call notices first. + std::vector> retiring_; + int clearing_{0}; ///< Number of clear() calls running (plus one once the destructor runs). }; } // namespace espp diff --git a/components/event_manager/src/event_manager.cpp b/components/event_manager/src/event_manager.cpp index 0c69d12e0f..04cb96a44e 100644 --- a/components/event_manager/src/event_manager.cpp +++ b/components/event_manager/src/event_manager.cpp @@ -7,10 +7,18 @@ using namespace espp; namespace { -// The topic whose callbacks this thread is running right now, if any. A -// removal made from one of those callbacks must not wait for the delivery in -// progress or join the topic's thread: both are this thread. -thread_local const void *t_delivering_topic = nullptr; +// The topic whose event this thread is delivering right now, if any: set while +// its callbacks run and while the delivery lets go of its subscriber snapshot +// (which can destroy removed callbacks). A call made from that thread never +// waits for that topic's thread or joins it: both are this thread. +thread_local void *t_delivering_topic = nullptr; + +// Guards every Topic's waiting_on / waiting_for. Never destroyed, so that a +// wait during static destruction can still use it. +std::mutex &wait_graph_mutex() { + static auto *m = new std::mutex(); + return *m; +} void call_subscriber(const std::string &topic, const std::string &component, const EventManager::event_callback_fn &callback, @@ -18,7 +26,10 @@ void call_subscriber(const std::string &topic, const std::string &component, #if defined(__cpp_exceptions) && __cpp_exceptions // A callback that throws must not end the topic's thread (an exception // escaping it calls std::terminate): log it and go on with the next one. - static espp::Logger logger({.tag = "Event Manager", .level = espp::Logger::Verbosity::WARN}); + // Never destroyed, so that it still works for callbacks that run while the + // program exits. + static auto &logger = + *new espp::Logger({.tag = "Event Manager", .level = espp::Logger::Verbosity::WARN}); try { callback(data); } catch (const std::exception &e) { @@ -33,17 +44,35 @@ void call_subscriber(const std::string &topic, const std::string &component, } } // namespace +EventManager::Topic::~Topic() { + // Wake the thread so that destroying its task can join it: Task::stop() + // only signals the Task's own condition variable, not cv. + { + std::lock_guard lk(m); + stopping = true; + } + cv.notify_all(); + task.reset(); +} + EventManager::~EventManager() { + { + std::lock_guard lk(mutex_); + ++clearing_; // refuse new subscribers for good, also once clear() returns + } clear(); - // Left over only if the EventManager is destroyed from inside a topic's - // callback (e.g. exit() called from one). That thread can't be joined from - // itself, and destroying its Task here would std::terminate, so keep the - // topic alive: its thread exits on its own once the callback returns. + // Left over only if the EventManager is destroyed on one of its topics' + // threads (e.g. exit() called from a callback). That thread can't be joined + // from itself, and destroying its Task here would std::terminate, so keep + // the topic alive: its thread exits on its own once the callback returns. + std::vector> finished; std::vector> left; { std::lock_guard lk(mutex_); - left.swap(stopping_topics_); + take_finished_topics(finished); + left.swap(retiring_); } + finished.clear(); if (!left.empty()) { static auto &kept = *new std::vector>(); // never destroyed kept.insert(kept.end(), std::make_move_iterator(left.begin()), @@ -80,14 +109,20 @@ bool EventManager::add_subscriber(const std::string &topic, const std::string &c topic); return false; } - reap_stopped_topics(); // Declared before the lock so that whatever they hold when we return (a - // callback, a replaced subscriber list, a topic whose thread didn't start) is - // destroyed after the lock is released, never under it. + // callback, a replaced subscriber list, topics whose thread is to be joined, + // a topic whose thread didn't start) is destroyed after the lock is + // released, never under it. + std::vector> finished; auto subscriber = std::make_shared(component, callback); std::shared_ptr replaced; std::shared_ptr state; std::lock_guard lk(mutex_); + if (clearing_ > 0) { + logger_.warn("Cannot add subscriber '{}' to topic '{}' while clear() runs", component, topic); + return false; + } + take_finished_topics(finished); if (auto it = topics_.find(topic); it != topics_.end()) { state = it->second; const auto ¤t = *state->subscribers; @@ -105,6 +140,17 @@ bool EventManager::add_subscriber(const std::string &topic, const std::string &c std::make_shared(std::move(subscribers))); return true; } + // The topic just lost its last subscriber but its thread hasn't exited yet + // (e.g. a callback that removed itself subscribes again): keep using that + // thread rather than starting a second one for the same topic. + for (auto it = retiring_.rbegin(); it != retiring_.rend(); ++it) { + if ((*it)->name == topic && revive(**it, subscriber, replaced)) { + state = *it; + retiring_.erase(std::next(it).base()); + topics_.emplace(topic, std::move(state)); + return true; + } + } // first subscriber on this topic: create it and start its thread state = std::make_shared(topic); state->subscribers = std::make_shared(SubscriberList{subscriber}); @@ -130,7 +176,9 @@ bool EventManager::publish(const std::string &topic, const std::vector logger_.info("Publishing on topic '{}'", topic); std::shared_ptr state; { + std::vector> finished; // joined after the lock is released std::lock_guard lk(mutex_); + take_finished_topics(finished); auto it = topics_.find(topic); if (it == topics_.end()) { return false; @@ -173,131 +221,244 @@ bool EventManager::remove_publisher(const std::string &topic, const std::string bool EventManager::remove_subscriber(const std::string &topic, const std::string &component) { logger_.info("Removing subscriber '{}' on topic '{}'", component, topic); - // Destroyed after the lock is released (see add_subscriber). + // Destroyed after the locks are released (see add_subscriber). + std::vector> finished; + event_callback_fn callback; std::shared_ptr removed; std::shared_ptr replaced; std::shared_ptr state; + // Other topics of this name, each of which can still be running the + // component's callback although it is no longer registered there: the + // callback removed itself, or clear() removed it. + std::vector> others; + bool topic_found = false; bool was_last_subscriber = false; { std::lock_guard lk(mutex_); - auto it = topics_.find(topic); - if (it == topics_.end()) { - logger_.warn("Cannot remove subscriber, there are no subscribers for topic '{}'", topic); - return false; + take_finished_topics(finished); + std::copy_if(retiring_.begin(), retiring_.end(), std::back_inserter(others), + [&topic](const std::shared_ptr &t) { return t->name == topic; }); + if (auto it = topics_.find(topic); it != topics_.end()) { + topic_found = true; + auto subscribers = *it->second->subscribers; + auto elem = std::find_if( + subscribers.begin(), subscribers.end(), + [&component](const std::shared_ptr &s) { return s->component == component; }); + if (elem == subscribers.end()) { + others.push_back(it->second); + } else { + state = it->second; + removed = *elem; + subscribers.erase(elem); + was_last_subscriber = subscribers.empty(); + if (was_last_subscriber) { + topics_.erase(it); + retiring_.push_back(state); + } + std::lock_guard topic_lk(state->m); + // a delivery in progress skips it from now on + removed->removed = true; + replaced = std::exchange(state->subscribers, + std::make_shared(std::move(subscribers))); + if (was_last_subscriber) { + retire(*state); + } + } } - state = it->second; - auto subscribers = *state->subscribers; - auto elem = std::find_if( - subscribers.begin(), subscribers.end(), - [&component](const std::shared_ptr &s) { return s->component == component; }); - if (elem == subscribers.end()) { + } + for (const auto &other : others) { + wait_while_running(*other, &component); + } + if (!state) { + if (!topic_found) { + logger_.warn("Cannot remove subscriber, there are no subscribers for topic '{}'", topic); + } else { logger_.warn( "Cannot remove subscriber, '{}' is not registered as a subscriber for topic '{}'", component, topic); - return false; - } - removed = *elem; - // a delivery in progress skips it from now on - removed->removed = true; - subscribers.erase(elem); - was_last_subscriber = subscribers.empty(); - if (was_last_subscriber) { - topics_.erase(it); - } - std::lock_guard topic_lk(state->m); - replaced = std::exchange(state->subscribers, - std::make_shared(std::move(subscribers))); - if (was_last_subscriber) { - state->stopping = true; } + return false; } if (was_last_subscriber) { logger_.info("It was the last subscriber for '{}', stopping its task", topic); - std::vector> stopped; - stopped.push_back(std::move(state)); - stop_topics(std::move(stopped)); - } else if (!is_delivering(*state)) { - // the callback may be running right now on the topic's thread - wait_for_delivery(*state); - } - reap_stopped_topics(); + state->cv.notify_all(); + } + // the callback may be running right now on the topic's thread + wait_while_running(*state, &component); + { + std::lock_guard topic_lk(state->m); + if (state->calling != removed.get()) { + // Not running, and never called again: destroy it here, once the locks + // are released, rather than later on the topic's thread. + std::swap(callback, removed->callback); + } + } + if (was_last_subscriber && wait_while_running(*state, nullptr)) { + // join its thread now rather than when the next call notices it finished + std::lock_guard lk(mutex_); + take_finished_topics(finished); + } return true; } void EventManager::clear() { logger_.info("Removing every publisher and subscriber"); + // Destroyed after the locks are released (see add_subscriber). std::vector> topics; std::vector> replaced; { std::lock_guard lk(mutex_); + ++clearing_; // refuse new subscribers until every topic is stopped publishers_.clear(); for (auto &[name, state] : topics_) { - topics.push_back(std::move(state)); + retiring_.push_back(std::move(state)); } topics_.clear(); - topics.insert(topics.end(), std::make_move_iterator(stopping_topics_.begin()), - std::make_move_iterator(stopping_topics_.end())); - stopping_topics_.clear(); - for (const auto &state : topics) { + for (const auto &state : retiring_) { std::lock_guard topic_lk(state->m); for (const auto &subscriber : *state->subscribers) { subscriber->removed = true; } replaced.push_back( std::exchange(state->subscribers, std::make_shared())); - state->stopping = true; + retire(*state); } + topics = retiring_; + } + for (const auto &state : topics) { + state->cv.notify_all(); } - stop_topics(std::move(topics)); + for (const auto &state : topics) { + wait_while_running(*state, nullptr); + } + { + std::vector> finished; // joined after the lock is released + std::lock_guard lk(mutex_); + take_finished_topics(finished); + --clearing_; + } + topics.clear(); // destroy the callbacks now that every lock is released and every thread - // is stopped (a callback still running belongs to the thread calling us) + // is stopped (one still running belongs to a thread that we can't wait for) replaced.clear(); } -void EventManager::stop_topics(std::vector> topics) { - // every topic here is already marked stopping - for (const auto &state : topics) { - state->cv.notify_all(); - } - for (auto &state : topics) { - if (is_delivering(*state)) { - // Removed from one of its own callbacks: this is the topic's thread, so - // it can't be joined here. It exits once the callback returns. - std::lock_guard lk(mutex_); - stopping_topics_.push_back(std::move(state)); - continue; - } - // waits for a callback in progress to return, then joins the thread - state->task->stop(); +void EventManager::take_finished_topics(std::vector> &finished) { + // mutex_ is held. A retiring topic that is no longer delivering won't run a + // callback again: its thread is exiting, so joining it doesn't block. + if (retiring_.empty()) { + return; } + auto still_delivering = [](const std::shared_ptr &state) { + std::lock_guard lk(state->m); + return state->busy; + }; + auto first_finished = std::stable_partition(retiring_.begin(), retiring_.end(), still_delivering); + finished.insert(finished.end(), std::make_move_iterator(first_finished), + std::make_move_iterator(retiring_.end())); + retiring_.erase(first_finished, retiring_.end()); } -void EventManager::reap_stopped_topics() { - std::vector> finished; +void EventManager::retire(Topic &topic) { + // topic.m is held + topic.stopping = true; + topic.queue.clear(); +} + +bool EventManager::revive(Topic &topic, const std::shared_ptr &subscriber, + std::shared_ptr &replaced) { { - std::lock_guard lk(mutex_); - auto still_running = [](const std::shared_ptr &state) { - return state->task->is_started(); - }; - auto first_finished = - std::stable_partition(stopping_topics_.begin(), stopping_topics_.end(), still_running); - finished.insert(finished.end(), std::make_move_iterator(first_finished), - std::make_move_iterator(stopping_topics_.end())); - stopping_topics_.erase(first_finished, stopping_topics_.end()); + std::lock_guard lk(topic.m); + if (topic.exited) { + return false; + } + // the thread hasn't seen stopping yet, and won't now + topic.stopping = false; + replaced = std::exchange(topic.subscribers, + std::make_shared(SubscriberList{subscriber})); } - // destroying them (without the lock) joins threads which have already returned - finished.clear(); + // a remover waiting to join the topic's thread stops waiting + topic.idle_cv.notify_all(); + return true; +} + +EventManager::Topic *EventManager::delivering_topic() { + return static_cast(t_delivering_topic); } bool EventManager::is_delivering(const Topic &topic) { return t_delivering_topic == &topic; } -void EventManager::wait_for_delivery(Topic &topic) { - std::unique_lock lk(topic.m); - if (!topic.delivering) { - return; +bool EventManager::is_running(const Topic &topic, const std::string *component) { + // topic.m is held + if (component) { + return topic.calling && topic.calling->component == *component; } - const auto in_progress = topic.deliveries + 1; - topic.idle_cv.wait(lk, [&topic, in_progress] { return topic.deliveries >= in_progress; }); + return topic.busy && topic.stopping; +} + +bool EventManager::waits_for(const Topic &from, const Topic &self) { + // The wait-graph mutex is held. Follow what each topic's thread is waiting + // for, starting at from's: true if that leads back to self's thread. An + // edge only counts while what it waits for is still running; otherwise that + // thread is about to stop waiting. + const Topic *t = &from; + // a chain is never longer than the number of topic threads; the bound only + // guards against a bug turning this into an endless loop + for (int hops = 0; hops < 1024; ++hops) { + Topic *next = t->waiting_on; + if (!next) { + return false; + } + bool live = false; + { + std::lock_guard lk(next->m); + live = is_running(*next, t->waiting_for); + } + if (!live) { + return false; + } + if (next == &self) { + return true; + } + t = next; + } + return true; +} + +bool EventManager::wait_while_running(Topic &topic, const std::string *component) { + // Waits until no callback of *component runs on topic (component null: + // until a stopping topic's thread has finished its last delivery). Returns + // false, without waiting, if that would deadlock: on the topic's own + // thread, or when the topic's thread is itself waiting, directly or through + // other topics, for this thread. + if (is_delivering(topic)) { + return false; + } + { + std::lock_guard lk(topic.m); + if (!is_running(topic, component)) { + return true; + } + } + Topic *self = delivering_topic(); + if (self) { + std::lock_guard lk(wait_graph_mutex()); + if (waits_for(topic, *self)) { + return false; + } + self->waiting_on = &topic; + self->waiting_for = component; + } + { + std::unique_lock lk(topic.m); + topic.idle_cv.wait(lk, [&topic, component] { return !is_running(topic, component); }); + } + if (self) { + std::lock_guard lk(wait_graph_mutex()); + self->waiting_on = nullptr; + self->waiting_for = nullptr; + } + return true; } bool EventManager::deliver_next(Topic &topic) { @@ -307,29 +468,40 @@ bool EventManager::deliver_next(Topic &topic) { std::unique_lock lk(topic.m); topic.cv.wait(lk, [&topic] { return topic.stopping || !topic.queue.empty(); }); if (topic.stopping) { - // stop the task; anything still queued is dropped with the topic + // stop the task + topic.exited = true; return true; } data = std::move(topic.queue.front()); topic.queue.pop_front(); subscribers = topic.subscribers; - topic.delivering = true; + topic.busy = true; } t_delivering_topic = &topic; for (const auto &subscriber : *subscribers) { - if (!subscriber->removed) { - call_subscriber(topic.name, subscriber->component, subscriber->callback, data); + { + std::lock_guard lk(topic.m); + if (subscriber->removed) { + continue; + } + topic.calling = subscriber.get(); } + call_subscriber(topic.name, subscriber->component, subscriber->callback, data); + { + std::lock_guard lk(topic.m); + topic.calling = nullptr; + } + topic.idle_cv.notify_all(); } - t_delivering_topic = nullptr; - // Let go of the snapshot before reporting the delivery finished: a removed - // subscriber's callback is then destroyed here, not after its remover has - // returned. + // Letting go of the snapshot destroys the callbacks that were removed while + // they ran (their remover couldn't take them). Still part of the delivery, + // so a destructor that calls back into the EventManager is treated like one + // of this topic's callbacks. subscribers.reset(); + t_delivering_topic = nullptr; { std::lock_guard lk(topic.m); - topic.delivering = false; - ++topic.deliveries; + topic.busy = false; } topic.idle_cv.notify_all(); return false; diff --git a/doc/en/core/event_manager.rst b/doc/en/core/event_manager.rst index 24a290c673..90dba35c37 100644 --- a/doc/en/core/event_manager.rst +++ b/doc/en/core/event_manager.rst @@ -26,10 +26,17 @@ inside a subscriber callback: a callback can publish, subscribe, or remove its own subscription. When ``remove_subscriber()`` returns, that callback is not running and will not be called again, so an object can call it from its destructor and then be destroyed safely. To guarantee that, -``remove_subscriber()`` (and ``clear()``) wait for a callback of that topic that is -running on another thread to return, so don't call them while holding a lock -that the topic's callbacks take. Data still queued for a topic when its last -subscriber leaves is dropped. +``remove_subscriber()`` (and ``clear()``) wait for the callback they remove if it +is running on another thread, so don't call them while holding a lock that the +callback takes. They can't wait in two cases, which would deadlock: when called +from that callback itself, and when that callback is waiting in turn for the +caller (callbacks of two topics removing each other's subscribers). + +The wait runs at the topic task's priority, which is 0 unless the +``task_config`` passed to ``add_subscriber()`` sets one, so a high priority task +removing a subscriber can be held up by a low priority topic. +``add_subscriber()`` returns false while ``clear()`` runs. Data still queued for +a topic when its last subscriber leaves is dropped. .. ------------------------------- Example ------------------------------------- diff --git a/lib/python_bindings/espp/__init__.pyi b/lib/python_bindings/espp/__init__.pyi index 7046913eb9..60ce851db7 100644 --- a/lib/python_bindings/espp/__init__.pyi +++ b/lib/python_bindings/espp/__init__.pyi @@ -536,16 +536,18 @@ class EventManager: * then to call the remove_publisher/remove_subscriber functions in the * class destructor. When remove_subscriber() returns, the callback is * not running and will not be called again, so the object can be - * destroyed safely right after it. + * destroyed safely right after it (see remove_subscriber() for the two + * cases where it can't wait). * * @note Every function is thread safe and can be called from any thread, * including from inside a subscriber callback (for example a callback * that removes its own subscription). remove_subscriber() and clear() - * wait for a callback of that topic that is running on another thread - * to return, so don't call them while holding a lock which that - * topic's callbacks take. Called from one of the topic's own callbacks, - * they don't wait; the removed callbacks are not called again once the - * current one returns. + * wait for a callback they remove that is running on another thread to + * return, so don't call them while holding a lock which that callback + * takes. They wait at the topic task's priority: a high priority caller + * can be held up by a topic whose task has a low priority + * (Task::BaseConfig::priority, 0 by default), so give the topic's + * task_config a priority that suits the code removing its subscribers. * * @note Data published on a topic is queued and delivered in order on the * topic's thread. Data still queued when the topic's last subscriber is @@ -601,12 +603,13 @@ class EventManager: * @param callback The event_callback_fn to be called when receiving data on * \p topic. * @param stack_size_bytes The stack size in bytes to use for the subscriber - * @note The stack size is only used if a subscriber is not already registered - * for that topic. If a subscriber is already registered for that topic, - * the stack size is ignored. + * @note The stack size is only used when the topic's thread is created. If + * a subscriber is already registered for that topic (or the topic's + * thread is still finishing a delivery after its last subscriber was + * removed, and is reused), the stack size is ignored. * @return True if the subscriber was added, False if it was already - * registered for that component, the callback is empty, or the - * topic's thread could not be started. + * registered for that component, the callback is empty, clear() is + * running, or the topic's thread could not be started. """ pass @@ -625,12 +628,13 @@ class EventManager: * @param callback The event_callback_fn to be called when receiving data on * \p topic. * @param task_config The task configuration to use for the subscriber. - * @note The task_config is only used if a subscriber is not already - * registered for that topic. If a subscriber is already registered for - * that topic, the task_config is ignored. + * @note The task_config is only used when the topic's thread is created. If + * a subscriber is already registered for that topic (or the topic's + * thread is still finishing a delivery after its last subscriber was + * removed, and is reused), the task_config is ignored. * @return True if the subscriber was added, False if it was already - * registered for that component, the callback is empty, or the - * topic's thread could not be started. + * registered for that component, the callback is empty, clear() is + * running, or the topic's thread could not be started. """ pass @@ -663,14 +667,19 @@ class EventManager: """* * @brief Remove \p component's subscriber for \p topic. * @details When it returns, the callback is not running and will not be - * called again, unless it was called from one of \p topic's own - * callbacks (then the callback is not called again once the - * current one returns). Removing the topic's last subscriber stops - * the topic's thread and drops any data still queued for it. + * called again, and it has been destroyed unless it was still + * running (it is then destroyed on the topic's thread once it + * returns). It can't wait for the callback in two cases, which + * would deadlock: when called from that callback itself, and when + * the callback is waiting in turn for the calling thread (callbacks + * of two topics removing each other's subscribers). Removing the + * topic's last subscriber stops the topic's thread and drops any + * data still queued for it. * @param topic The topic that \p component was subscribing to. * @param component The component for which the subscriber was registered. * @return True if the subscriber was removed, False if it was not - * registered. + * registered. It waits for the callback in both cases: one that + * removed itself (or that clear() removed) can still be running. """ pass @@ -679,8 +688,10 @@ class EventManager: """* * @brief Remove every publisher and subscriber and stop every topic's * thread. - * @details Waits for callbacks running on other threads to return. The - * EventManager can be used again afterwards. + * @details Waits for callbacks running on other threads to return (except + * in the two cases described in remove_subscriber()). + * add_subscriber() returns False while it runs. The EventManager + * can be used again afterwards. """ pass diff --git a/lib/python_bindings/pybind_espp.cpp b/lib/python_bindings/pybind_espp.cpp index d68a6eddb5..48a0f1294a 100644 --- a/lib/python_bindings/pybind_espp.cpp +++ b/lib/python_bindings/pybind_espp.cpp @@ -281,23 +281,25 @@ void py_init_module_espp(py::module &m) { "to call the remove_publisher/remove_subscriber functions in the\n * class " "destructor. When remove_subscriber() returns, the callback is\n * not running and " "will not be called again, so the object can be\n * destroyed safely right after " - "it.\n *\n * @note Every function is thread safe and can be called from any thread,\n * " - " including from inside a subscriber callback (for example a callback\n * that " + "it (see remove_subscriber() for the two\n * cases where it can't wait).\n *\n * " + "@note Every function is thread safe and can be called from any thread,\n * " + "including from inside a subscriber callback (for example a callback\n * that " "removes its own subscription). remove_subscriber() and clear()\n * wait for a " - "callback of that topic that is running on another thread\n * to return, so don't " - "call them while holding a lock which that\n * topic's callbacks take. Called from " - "one of the topic's own callbacks,\n * they don't wait; the removed callbacks are " - "not called again once the\n * current one returns.\n *\n * @note Data published " - "on a topic is queued and delivered in order on the\n * topic's thread. Data still " - "queued when the topic's last subscriber is\n * removed is dropped. When C++ " - "exceptions are enabled, an exception\n * thrown by a callback is logged and the " - "other callbacks still run.\n *\n * @note It is recommended (unless you are only " - "interested in events and not\n * data or are only needing to transmit actual " - "strings) to use a\n * serialization library (such as espp::serialization - which " - "wraps\n * alpaca) to serialize your data structures to bytes when publishing\n * " - " and then deserialize your data from bytes in the subscriber\n * callbacks.\n " - "*\n * \\section event_manager_ex1 Event Manager Example\n * \\snippet " - "event_manager_example.cpp event manager example\n") + "callback they remove that is running on another thread to\n * return, so don't " + "call them while holding a lock which that callback\n * takes. They wait at the " + "topic task's priority: a high priority caller\n * can be held up by a topic whose " + "task has a low priority\n * (Task::BaseConfig::priority, 0 by default), so give " + "the topic's\n * task_config a priority that suits the code removing its " + "subscribers.\n *\n * @note Data published on a topic is queued and delivered in order " + "on the\n * topic's thread. Data still queued when the topic's last subscriber " + "is\n * removed is dropped. When C++ exceptions are enabled, an exception\n * " + " thrown by a callback is logged and the other callbacks still run.\n *\n * @note It is " + "recommended (unless you are only interested in events and not\n * data or are " + "only needing to transmit actual strings) to use a\n * serialization library (such " + "as espp::serialization - which wraps\n * alpaca) to serialize your data " + "structures to bytes when publishing\n * and then deserialize your data from bytes " + "in the subscriber\n * callbacks.\n *\n * \\section event_manager_ex1 Event " + "Manager Example\n * \\snippet event_manager_example.cpp event manager example\n") .def_static("get", &espp::EventManager::get, "*\n * @brief Get the singleton instance of the EventManager.\n * " "@return A reference to the EventManager singleton.\n", @@ -319,11 +321,13 @@ void py_init_module_espp(py::module &m) { "the component subscribing to the data.\n * @param callback The event_callback_fn " "to be called when receiving data on\n * \\p topic.\n * @param " "stack_size_bytes The stack size in bytes to use for the subscriber\n * @note The " - "stack size is only used if a subscriber is not already registered\n * for " - "that topic. If a subscriber is already registered for that topic,\n * the " - "stack size is ignored.\n * @return True if the subscriber was added, False if it " - "was already\n * registered for that component, the callback is empty, or " - "the\n * topic's thread could not be started.\n") + "stack size is only used when the topic's thread is created. If\n * a " + "subscriber is already registered for that topic (or the topic's\n * thread " + "is still finishing a delivery after its last subscriber was\n * removed, " + "and is reused), the stack size is ignored.\n * @return True if the subscriber " + "was added, False if it was already\n * registered for that component, " + "the callback is empty, clear() is\n * running, or the topic's thread " + "could not be started.\n") .def("add_subscriber", py::overload_cast()) .def("clear", &espp::EventManager::clear, "*\n * @brief Remove every publisher and subscriber and stop every topic's\n * " " thread.\n * @details Waits for callbacks running on other threads to " - "return. The\n * EventManager can be used again afterwards.\n", + "return (except\n * in the two cases described in " + "remove_subscriber()).\n * add_subscriber() returns False while it runs. " + "The EventManager\n * can be used again afterwards.\n", py::call_guard()); //////////////////// //////////////////// diff --git a/lib/python_bindings/stop_registry.h b/lib/python_bindings/stop_registry.h index ac7c5e759c..e95e89d8fc 100644 --- a/lib/python_bindings/stop_registry.h +++ b/lib/python_bindings/stop_registry.h @@ -16,8 +16,9 @@ // while python threads can still run, so the later destructors find nothing // left to join. // -// Standard library + pybind11 only (no espp headers), so module.cpp can -// register the atexit hook without pulling in the whole library. +// Standard library + pybind11 only (no espp headers), so including it doesn't +// pull in the library: module.cpp includes just the espp headers its atexit +// hook uses. #include #include diff --git a/pc/tests/event_manager.cpp b/pc/tests/event_manager.cpp index 7913c78a7a..c834d51f4c 100644 --- a/pc/tests/event_manager.cpp +++ b/pc/tests/event_manager.cpp @@ -3,12 +3,17 @@ // while its callback ran, a callback removing itself, subscribers added or // removed during a delivery, publish racing the last removal, a re-subscribe // racing the last removal, new topics racing publish, destruction with live -// subscribers). Runs under TSan and ASan in host_sanitizers.yml. +// subscribers), and the cases where remove_subscriber() must still wait, or +// must not wait because it would deadlock (a callback that removed itself, +// clear() running, callbacks of several topics removing each other's, a +// callback's destructor calling back in, subscribing during clear()). Runs +// under TSan and ASan in host_sanitizers.yml. #include #include #include #include #include +#include #include #include #include @@ -23,9 +28,25 @@ using namespace std::chrono_literals; namespace { // The constructor is protected (EventManager is a singleton); a derived class -// gives each case a fresh instance, and lets a case destroy one. +// gives each case a fresh instance, lets a case destroy one, and shows a little +// of its state. struct TestEventManager : public espp::EventManager { TestEventManager() { set_log_level(espp::Logger::Verbosity::ERROR); } + ~TestEventManager() { + if (on_destroy) { + on_destroy(); + } + } + // topics whose last subscriber was removed and whose thread is not joined yet + size_t retiring() { + std::lock_guard lk(mutex_); + return retiring_.size(); + } + bool clearing() { + std::lock_guard lk(mutex_); + return clearing_ > 0; + } + std::function on_destroy; }; using Data = std::vector; @@ -62,16 +83,44 @@ bool wait_until(Predicate &&pred, std::chrono::milliseconds timeout = 10s) { // A subscriber callback that always throws. void throw_expected(const Data &) { throw std::runtime_error("expected: a callback that throws"); } -// Run fn on another thread; false if it hasn't returned within the timeout (the -// thread is then left running and the test fails). -template bool returns_within(Fn &&fn, std::chrono::milliseconds timeout) { +// Run fn on another thread and return true once it has returned. If it hasn't +// within the timeout, fail the whole test right away: the stuck thread still +// uses the case's state, so carrying on would only crash later checks. +template +bool returns_within(Fn &&fn, std::chrono::milliseconds timeout, const char *what) { auto done = std::make_shared>(false); std::thread([fn = std::forward(fn), done]() mutable { fn(); *done = true; }).detach(); - return wait_until([&] { return done->load(); }, timeout); + if (!wait_until([&] { return done->load(); }, timeout)) { + std::fprintf(stderr, "FAIL: %s: did not return within %lld ms (hang)\n", what, + static_cast(timeout.count())); + std::_Exit(1); + } + return true; } + +// Lets n threads continue only once all of them have arrived. +struct Rendezvous { + explicit Rendezvous(int parties) + : parties(parties) {} + bool arrive_and_wait() { + arrived++; + return wait_until([this] { return arrived >= parties; }, 5s); + } + const int parties; + std::atomic arrived{0}; +}; + +// Something a subscriber callback owns, which calls back into the +// EventManager when destroyed (RAII unsubscribe). +struct Owner { + explicit Owner(std::function on_destroy) + : on_destroy(std::move(on_destroy)) {} + ~Owner() { on_destroy(); } + std::function on_destroy; +}; } // namespace int main() { @@ -205,6 +254,7 @@ int main() { } finish_a.release(); check(wait_until([&] { return b_calls == 1; }), "the delivery in progress finishes"); + check(late_calls == 0, "without calling the subscribers added during it"); em.publish("t", Data{2}); check(wait_until([&] { return late_calls == 16 && b_calls == 2; }), "the added subscribers get the next event"); @@ -228,11 +278,14 @@ int main() { check(in_a.wait(), "callback a running"); std::atomic removed{false}; std::atomic running_when_removed{true}; + Latch removing; std::thread remover([&] { + removing.release(); em.remove_subscriber("t", "a"); running_when_removed = a_running.load(); removed = true; }); + removing.wait(); std::this_thread::sleep_for(100ms); check(!removed, "remove_subscriber is still waiting while the callback runs"); finish_a.release(); @@ -262,9 +315,10 @@ int main() { em.publish("t", Data{1}); } std::this_thread::sleep_for(std::chrono::microseconds(round % 5 * 40)); - ok = returns_within([&] { em.remove_subscriber("t", "s"); }, 5s); + returns_within([&] { em.remove_subscriber("t", "s"); }, 5s, + "removing the last subscriber while its callback runs"); int calls_at_removal = calls; - ok = ok && !running; + ok = !running; std::this_thread::sleep_for(1ms); ok = ok && calls == calls_at_removal; } @@ -349,10 +403,10 @@ int main() { logger.info("--- a callback removing a subscriber of another topic ---"); { TestEventManager em; - std::atomic other_calls{0}; + std::atomic other_calls{0}, o2_calls{0}; std::atomic removed{false}; em.add_subscriber("other", "o", [&](const Data &) { other_calls++; }); - em.add_subscriber("other", "o2", [](const Data &) {}); + em.add_subscriber("other", "o2", [&](const Data &) { o2_calls++; }); em.add_subscriber("t", "s", [&](const Data &) { removed = em.remove_subscriber("other", "o"); }); em.publish("other", Data{1}); @@ -360,8 +414,317 @@ int main() { em.publish("t", Data{1}); check(wait_until([&] { return removed.load(); }), "removed from a callback of another topic"); em.publish("other", Data{2}); - std::this_thread::sleep_for(20ms); - check(other_calls == 1, "and it is not called again"); + // o2 is called after o, so once o2 has the event o would have had it too + check(wait_until([&] { return o2_calls == 2; }) && other_calls == 1, + "and it is not called again"); + } + + logger.info("--- remove_subscriber waits for a callback that removed itself ---"); + { + // e.g. a one-shot callback that unsubscribes first and then keeps using + // its object, whose destructor calls remove_subscriber() as well + TestEventManager em; + for (bool last : {false, true}) { + const std::string which = last ? " (it was the topic's last subscriber)" : ""; + Latch removed_itself, finish; + std::atomic running{false}; + em.add_subscriber("t", "one-shot", [&](const Data &) { + running = true; + em.remove_subscriber("t", "one-shot"); + removed_itself.release(); + finish.wait(); + running = false; + }); + if (!last) { + em.add_subscriber("t", "keep", [](const Data &) {}); + } + em.publish("t", Data{1}); + check(removed_itself.wait(), "the callback removed itself and keeps running" + which); + std::atomic returned{false}, result{true}, running_at_return{true}; + Latch removing; + std::thread owner([&] { + removing.release(); + result = em.remove_subscriber("t", "one-shot"); + running_at_return = running.load(); + returned = true; + }); + removing.wait(); + std::this_thread::sleep_for(50ms); + check(!returned, "a second remove_subscriber waits for it" + which); + finish.release(); + owner.join(); + check(!result && !running_at_return, + "and returns false once the callback has returned (used to return at once)" + which); + if (!last) { + em.remove_subscriber("t", "keep"); + } + } + } + + logger.info("--- remove_subscriber while clear() runs ---"); + { + TestEventManager em; + Latch in_a, finish_a; + std::atomic running{false}; + em.add_subscriber("t", "a", [&](const Data &) { + running = true; + in_a.release(); + finish_a.wait(); + running = false; + }); + em.publish("t", Data{1}); + check(in_a.wait(), "callback running"); + std::thread clearer([&] { em.clear(); }); + check(wait_until([&] { return em.clearing(); }), "clear() removed it and waits for it"); + std::atomic returned{false}, running_at_return{true}; + std::thread remover([&] { + em.remove_subscriber("t", "a"); + running_at_return = running.load(); + returned = true; + }); + std::this_thread::sleep_for(50ms); + check(!returned, "remove_subscriber waits for the callback too"); + finish_a.release(); + remover.join(); + clearer.join(); + check(!running_at_return, "and returns once it has returned (used to return at once)"); + } + + logger.info("--- callbacks of two topics removing each other's subscribers ---"); + { + // used to deadlock: each topic's thread waited for the other's delivery + TestEventManager em; + Rendezvous meet(2); + std::atomic done{0}; + em.add_subscriber("A", "a1", [&](const Data &) { + meet.arrive_and_wait(); + em.remove_subscriber("B", "b2"); + done++; + }); + em.add_subscriber("A", "a2", [](const Data &) {}); + em.add_subscriber("B", "b1", [&](const Data &) { + meet.arrive_and_wait(); + em.remove_subscriber("A", "a2"); + done++; + }); + em.add_subscriber("B", "b2", [](const Data &) {}); + em.publish("A", Data{1}); + em.publish("B", Data{1}); + check(wait_until([&] { return done == 2; }, 5s), + "both removals of a subscriber that isn't running return (used to deadlock)"); + } + { + // each removes the callback the other topic is running: one of them can't + // wait (that would deadlock), the other waits for it + TestEventManager em; + Rendezvous meet(2); + std::atomic done{0}, a1_calls{0}, b1_calls{0}, a2_calls{0}, b2_calls{0}; + std::atomic removed_a1{false}, removed_b1{false}; + em.add_subscriber("A", "a1", [&](const Data &) { + a1_calls++; + meet.arrive_and_wait(); + removed_b1 = em.remove_subscriber("B", "b1"); + done++; + }); + em.add_subscriber("A", "a2", [&](const Data &) { a2_calls++; }); + em.add_subscriber("B", "b1", [&](const Data &) { + b1_calls++; + meet.arrive_and_wait(); + removed_a1 = em.remove_subscriber("A", "a1"); + done++; + }); + em.add_subscriber("B", "b2", [&](const Data &) { b2_calls++; }); + em.publish("A", Data{1}); + em.publish("B", Data{1}); + check(wait_until([&] { return done == 2; }, 5s), + "both removals of the other topic's running callback return"); + check(removed_a1 && removed_b1, "and both removed it"); + em.publish("A", Data{2}); + em.publish("B", Data{2}); + check(wait_until([&] { return a2_calls == 2 && b2_calls == 2; }) && a1_calls == 1 && + b1_calls == 1, + "neither removed callback is called again"); + } + { + // the same around three topics: X waits for Y, Y for Z, Z would wait for X + TestEventManager em; + Rendezvous meet(3); + std::atomic done{0}; + const std::vector names{"X", "Y", "Z"}; + for (size_t i = 0; i < names.size(); ++i) { + const auto next = names[(i + 1) % names.size()]; + em.add_subscriber(names[i], "running", [&, next](const Data &) { + meet.arrive_and_wait(); + em.remove_subscriber(next, "running"); + done++; + }); + em.add_subscriber(names[i], "other", [](const Data &) {}); + } + for (const auto &name : names) { + em.publish(name, Data{1}); + } + check(wait_until([&] { return done == 3; }, 5s), + "a ring of three topics removing the next one's running callback returns"); + } + { + // clear() from a callback of A while a callback of B removes A's + TestEventManager em; + Rendezvous meet(2); + std::atomic done{0}; + em.add_subscriber("A", "a1", [&](const Data &) { + meet.arrive_and_wait(); + em.clear(); + done++; + }); + em.add_subscriber("A", "a2", [](const Data &) {}); + em.add_subscriber("B", "b1", [&](const Data &) { + meet.arrive_and_wait(); + em.remove_subscriber("A", "a1"); + done++; + }); + em.publish("A", Data{1}); + em.publish("B", Data{1}); + check(wait_until([&] { return done == 2; }, 5s), + "clear() in one topic's callback while another topic's removes its callback returns"); + check(!em.publish("A", Data{1}) && !em.publish("B", Data{1}), "and everything was removed"); + } + + logger.info("--- a callback's destructor calls back into the EventManager ---"); + for (int mode = 0; mode < 2; ++mode) { + // A one-shot callback that owns the last reference to an object removes + // itself, so the object is destroyed on the topic's thread when that + // delivery lets go of the callback; its destructor then removes another + // subscriber of the same topic (mode 0), or clears everything (mode 1). + TestEventManager em; + std::atomic destroyed{false}; + { + auto owner = std::make_shared([&em, &destroyed, mode] { + if (mode == 0) { + em.remove_subscriber("t", "extra"); + } else { + em.clear(); + } + destroyed = true; + }); + em.add_subscriber("t", "owner", + [&em, owner](const Data &) { em.remove_subscriber("t", "owner"); }); + em.add_subscriber("t", "extra", [](const Data &) {}); + em.add_subscriber("t", "other", [](const Data &) {}); + } + em.publish("t", Data{1}); + check(wait_until([&] { return destroyed.load(); }, 5s), + mode == 0 ? "destructor removing another subscriber returns (used to deadlock)" + : "destructor calling clear() returns (used to std::terminate)"); + } + { + // Removed from another thread while not running: the callback (and what it + // owns) is destroyed by remove_subscriber(), on the caller's thread. + TestEventManager em; + std::atomic destroyed{false}; + std::thread::id destroyed_on; + { + auto owner = std::make_shared([&] { + destroyed_on = std::this_thread::get_id(); + destroyed = true; + }); + em.add_subscriber("t", "owner", [owner](const Data &) {}); + em.add_subscriber("t", "other", [](const Data &) {}); + } + em.publish("t", Data{1}); + em.remove_subscriber("t", "owner"); + check(destroyed && destroyed_on == std::this_thread::get_id(), + "a removed callback is destroyed before remove_subscriber() returns"); + } + + logger.info("--- subscribing while clear() or the destructor runs ---"); + { + TestEventManager em; + Latch in_a; + std::atomic added{true}, finished{false}; + em.add_subscriber("t", "a", [&](const Data &) { + in_a.release(); + wait_until([&] { return em.clearing(); }); // clear() is waiting for us + added = em.add_subscriber("late", "x", [](const Data &) {}); + finished = true; + }); + em.publish("t", Data{1}); + check(in_a.wait(), "callback running"); + em.clear(); + check(finished && !added, "add_subscriber() from a callback that clear() waits for fails"); + check(!em.publish("late", Data{1}), "and nothing is left subscribed"); + } + { + // the destructor clears too; a subscriber added then used to be destroyed + // without being stopped, and joining its thread hung the destructor + auto em = std::make_unique(); + Latch in_a; + std::atomic destroying{false}; + em->on_destroy = [&] { destroying = true; }; + espp::EventManager *base = em.get(); + em->add_subscriber("t", "a", [&, base](const Data &) { + in_a.release(); + wait_until([&] { return destroying.load(); }); + std::this_thread::sleep_for(20ms); // let ~EventManager start waiting for us + base->add_subscriber("late", "x", [](const Data &) {}); + }); + em->publish("t", Data{1}); + check(in_a.wait(), "callback running"); + auto *raw = em.release(); + check(returns_within([raw] { delete raw; }, 5s, "destructor while a callback subscribes"), + "the destructor returns while a callback it waits for subscribes (used to hang)"); + } + + logger.info("--- a topic that removed its last subscriber itself is joined later ---"); + { + TestEventManager em; + std::atomic done{false}; + em.add_subscriber("t", "once", [&](const Data &) { + em.remove_subscriber("t", "once"); + done = true; + }); + em.add_subscriber("other", "o", [](const Data &) {}); + em.publish("t", Data{1}); + check(wait_until([&] { return done.load(); }), "the callback removed itself"); + check(em.retiring() == 1, "its thread can't be joined from itself, so it waits"); + check(wait_until([&] { + em.publish("other", Data{1}); + return em.retiring() == 0; + }), + "a later publish() joins it (on ESP-IDF that frees its stack)"); + } + + logger.info("--- a callback that removes the last subscriber and subscribes again ---"); + { + TestEventManager em; + std::mutex m; + std::vector threads; + std::atomic calls{0}; + std::function rearm = [&](const Data &) { + { + std::lock_guard lk(m); + threads.push_back(std::this_thread::get_id()); + } + em.remove_subscriber("t", "rearm"); + em.add_subscriber("t", "rearm", rearm); + calls++; + }; + em.add_subscriber("t", "rearm", rearm); + bool delivered = true; + for (int i = 1; i <= 5 && delivered; ++i) { + em.publish("t", Data{1}); + delivered = wait_until([&] { return calls == i; }); + } + check(delivered, "every event is delivered to the re-added subscriber"); + { + std::lock_guard lk(m); + bool one_thread = threads.size() == 5; + for (const auto &id : threads) { + one_thread = one_thread && id == threads.front(); + } + check(one_thread && em.retiring() == 0, + "on the topic's one thread (used to start a new thread every time)"); + } + em.remove_subscriber("t", "rearm"); } logger.info("--- a callback that throws ---"); @@ -413,7 +776,7 @@ int main() { em->publish("busy", Data{1}); check(in_callback.wait(), "a callback is running"); auto *raw = em.release(); - check(returns_within([raw] { delete raw; }, 5s), + check(returns_within([raw] { delete raw; }, 5s, "destructor with live subscribers"), "the destructor returns (used to hang joining an idle topic thread)"); check(finished, "after the running callback returned"); } diff --git a/python/event_manager_test.py b/python/event_manager_test.py index e3e2da9adb..12e55feb11 100644 --- a/python/event_manager_test.py +++ b/python/event_manager_test.py @@ -5,7 +5,8 @@ the topic's thread (so they release the GIL, or a python callback could never finish), a callback that removes its own subscription, and exiting the interpreter with live subscribers (the module's atexit hook clears the -EventManager while python can still run and destroy the callbacks). +EventManager while python can still run and destroy the callbacks, and a +callback still running then can't subscribe again). Each case runs in a child interpreter under a timeout, so a regression shows up as a failed case rather than a hung test. @@ -77,7 +78,7 @@ def raises_type_error(fn): assert raises_type_error(lambda: em.remove_subscriber(1, 2)) assert raises_type_error(lambda: espp.EventManager()) # singleton: get() only assert em is espp.EventManager.get() -# a callback that raises: the error is reported by python, the subscriber thread keeps going +# a callback that raises: the EventManager logs the error and the subscriber thread keeps going calls = [0] def flaky(data): calls[0] += 1 @@ -171,6 +172,19 @@ def slow(data): em.publish("busy", [1]) assert started.wait(5) print("exit_with_live_subscribers ok") +""", + # a callback still running at exit subscribes while the atexit hook's clear() waits for it: + # that subscription (and the python callable it holds) must not outlive the interpreter + "exit_while_callback_subscribes": """ +started = threading.Event() +def slow(data): + started.set() + time.sleep(0.3) + em.add_subscriber("late", "x", lambda data: None) +assert em.add_subscriber("t", "slow", slow) +em.publish("t", [1]) +assert started.wait(5) +print("exit_while_callback_subscribes ok") """, # an unhandled exception with live subscribers must still exit (with status 1) "exception_with_live_subscribers": """