Skip to content

fix(event_manager): make subscribe / unsubscribe / publish safe to run concurrently - #929

Merged
finger563 merged 2 commits into
mainfrom
fix/event-manager-concurrency
Nov 26, 2026
Merged

finger563 merged 2 commits into
mainfrom
fix/event-manager-concurrency

Conversation

@finger563

@finger563 finger563 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Description

espp::EventManager split each operation across four separate recursive mutexes, released them between steps, and kept raw pointers into its maps after unlocking. On the host, under ASan and TSan, that reproduced as:

What happens Before After
Removing a topic's last subscriber while its callback runs can hang forever in join(): the delivery loop cleared the same notified flag that signalled shutdown. The hang held tasks_mutex_, so later subscribes and last-subscriber removals blocked too returns once the callback finishes
publish() racing the removal of the last subscriber heap-use-after-free of the topic's queue (publish kept a SubscriberData* after unlocking) safe: the topic is held through a shared_ptr
Subscribers added or removed during a delivery heap-use-after-free: the thread iterated the live callback vector without the lock each delivery iterates an immutable snapshot
Subscribing to a new topic while any topic has traffic data race on the topic map: inserted under tasks_mutex_, looked up under data_mutex_ one mutex guards the registry
A callback that removes its own subscription std::terminate: the topic's Task was destroyed on its own thread works; the thread is joined later
The last subscriber leaves while another component subscribes the new subscription had no task (lost), and removing it later dereferenced a null task (segfault) add and remove are each a single locked step
A process (host / python) exiting with a live subscriber never exited: no destructor woke the topic threads the new destructor stops every topic
A callback that throws (exceptions enabled) std::terminate logged; the other callbacks still run

The public API is unchanged, apart from two additions: clear() and an explicit destructor.

How it works now

  • One std::mutex guards the registry (topics and publishers). Each topic's state (queue, condition variables, task, subscriber list) lives in a shared_ptr<Topic>, so publish() and teardown can overlap safely.
  • Deliveries take an immutable snapshot of the subscriber list. Add and remove replace the list instead of editing it, so a delivery in progress is never invalidated.
  • A removed subscriber is never called again. A removed flag makes later deliveries skip it.
  • remove_subscriber() waits for the callback it removes. Each topic tracks whose callback is running. If the removed callback is running on another thread, removal waits for it to return, but not for the topic's other callbacks. It also waits when the component is no longer registered, but its callback is still running because it removed itself or clear() removed it. So an object can unsubscribe in its destructor (as the class docs recommend) and be destroyed safely right after.
  • It never waits where that would deadlock. Called from that callback itself, or when the callback is in turn waiting for the caller, it returns without waiting. The second case is callbacks of two topics removing each other's subscribers; each topic thread records what it waits for, so the cycle is found. A topic whose own thread removed its last subscriber is joined later, by the next add, remove, publish or clear.
  • A dedicated stopping flag ends a topic's thread. If a callback removes the topic's last subscriber and then subscribes again, the topic keeps its thread.
  • Callbacks are destroyed outside the locks. A removed callback is destroyed by remove_subscriber() itself, unless it was still running. In that case it is destroyed on the topic's thread, which still counts as that topic's callback, so a destructor can unsubscribe safely. This matters for Python, whose callables take the GIL when destroyed.
  • add_subscriber() returns false for an empty callback, while clear() runs, or when the topic's task fails to start. Before, that failure was ignored.

Behaviour changes to be aware of

  • remove_subscriber() (and clear()) can now block while the callback they remove runs on another thread. The docs say not to call them while holding a lock that callback takes. They wait at the topic task's priority, which is 0 unless task_config sets one; the docs say so too.
  • add_subscriber() returns false while clear() runs. This includes a callback subscribing while clear() or the destructor waits for it.
  • Data still queued when a topic's last subscriber leaves is dropped. Before, the data was also dropped, or the thread hung.

Python

  • GIL release: remove_subscriber and clear release the GIL (added to _GIL_RELEASE_METHODS). Without that, removing a subscriber whose Python callback is running deadlocks.
  • atexit hook: EventManager is a C++ singleton that Python never owns, so the StopOnExitHolder path doesn't apply. The module's atexit hook now calls EventManager::get().clear() with the GIL released, so the topic threads stop and the Python callbacks are destroyed while the interpreter is still alive.
  • Bindings regeneration: only the generated event_manager.hpp section of pybind_espp.cpp and __init__.pyi is updated. A full regeneration with the current litgen also rewrites many unrelated sections (for example it drops BaseComponent.set_log_tag), so I left those alone.

Tests

  • pc/tests/event_manager.cpp (83 checks) is added to host_sanitizers.yml (TSan + ASan) and its path filters. It has one section per bug above, plus the guarantees above:
    • a removed callback is not running and won't be called again;
    • a second removal waits for a callback that removed itself, and so does a removal while clear() runs;
    • a callback can remove itself or a later subscriber;
    • removals that would deadlock all return:
      • two or three topics' callbacks removing each other's subscribers, running or not;
      • clear() in one topic's callback while another topic's callback removes from it;
    • a callback's destructor that unsubscribes or calls clear(), run on the topic's thread;
    • subscribing while clear() or the destructor runs;
    • a later publish() joins a topic that removed its last subscriber itself;
    • re-subscribing from the callback keeps the topic's thread;
    • a callback can publish to its own topic;
    • clear() works, including from inside a callback;
    • a callback that throws is logged and the others still run;
    • destroying the manager with a callback running completes.
  • python/event_manager_test.py (9 cases, each in a child interpreter under a timeout) is added to the wheel test-command. It covers:
    • the API and its misuse (TypeErrors; an empty callback; a raising callback);
    • removing a subscriber, or the last one, while its Python callback runs;
    • clear() while a callback runs;
    • a self-removing callback;
    • exiting, normally or with an exception, with live subscribers;
    • a callback subscribing while the exit hook's clear() waits for it.
  • The example's counters are std::atomic. They were plain ints written from four threads.

Verification

  • Host test, new code: 83/83 under ASan, under TSan (5 runs, no reports), and with g++-16 -std=c++23 -Wall -Wextra -Werror.
  • Host test, old code: run section by section against main, every section for one of the bugs above fails, with an ASan use-after-free or container-overflow, std::terminate, a failed check, or a hang. The two sections that only check behaviour that was already right fail only when the old destructor hangs.
  • The second commit's sections, against the first commit: each one fails or hangs:
    • a removal returns while the callback still runs; under ASan the callback then hits a stack-use-after-scope;
    • the cross-topic and destructor deadlocks;
    • the destructor hang;
    • a self-retired topic that a later publish() never joins;
    • a new thread for every re-subscribe.
  • Python test: 9/9 against a local build (Python 3.14, pybind11 3.0.4). With the GIL guard and the atexit hook temporarily removed, 6/8 fail: removal hangs, and exit hangs or aborts. The new exit case aborts with Fatal Python error: gilstate_tss_set against the first commit (3/3 runs). python/blocking_destructors_test.py and python/dispatcher_test.py still pass.
  • ESP32 builds: idf.py build for esp32 passes for components/event_manager/example and components/button/example (the other user).
  • cppcheck: the CI flags report nothing on the changed files.
  • Not done: I haven't run the example on hardware; no board was attached.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU

…n concurrently

The EventManager split each operation across four recursive mutexes and kept
raw pointers into its maps after unlocking, which on host (ASan / TSan)
reproduced as:

- removing a topic's last subscriber while its callback ran could hang
  forever in join(): the delivery loop cleared the same flag that signalled
  shutdown, and the hang held the tasks mutex, blocking later subscribes
- publish racing the last removal: use-after-free of the topic's queue
- subscribers added or removed during a delivery: use-after-free of the
  callback list being iterated
- subscribing to a new topic raced every publish (map insert under the wrong
  mutex)
- a callback removing its own subscription called std::terminate (the topic's
  Task was destroyed on its own thread)
- the last subscriber leaving while another component subscribed lost the
  new subscription, and removing it later dereferenced a null task
- a process (host / python) exiting with a live subscriber never exited

Now one mutex guards the registry and each topic's state is held through a
shared_ptr. Deliveries iterate an immutable snapshot of the subscribers, and a
removed subscriber is never called again. A dedicated stopping flag ends a
topic's thread. A removal from the topic's own callback hands the thread over
to be joined later. The new destructor (and new clear()) stop every topic.
remove_subscriber() now waits for that callback if it is running on another
thread, so an object can unsubscribe in its destructor and be destroyed
safely. Callbacks are destroyed outside the locks. A throwing callback is
logged instead of terminating (when exceptions are enabled). An empty callback
or a task that fails to start makes add_subscriber() return false.

Python: remove_subscriber / clear release the GIL, and the module's atexit
hook clears the EventManager so its threads stop and its python callbacks are
destroyed while the interpreter is alive. Only the generated event_manager.hpp
section of the bindings is updated.

Tests: pc/tests/event_manager.cpp (52 checks, added to the TSan / ASan
workflow) and python/event_manager_test.py (added to the wheel test command).
The example's counters are now atomic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
@github-actions

Copy link
Copy Markdown

✅Static analysis result - no issues found! ✅

…dlock waiting

A second review of this PR found four more problems, all reproduced on the
host before this change:

- remove_subscriber() returned false at once when the component was no longer
  registered, even if its callback was still running: a one-shot callback that
  had removed itself, or one a concurrent clear() had removed. An owner
  unsubscribing in its destructor could then be freed under the callback.
- Callbacks of two topics removing each other's subscribers deadlocked, each
  topic thread waiting for the other's delivery (new in this PR: main didn't
  wait).
- A removed callback destroyed on the topic's thread, when the delivery let go
  of its snapshot, no longer counted as running on that thread: an object whose
  destructor unsubscribed from the same topic deadlocked, and one that called
  clear() hit std::terminate.
- A subscriber added by a callback while clear() or the destructor waited for
  it made a topic that was later destroyed without being stopped. Joining its
  thread hung the destructor, and from python its callable outlived the
  interpreter (fatal error at exit).

Changes:
- Each topic tracks whose callback is running. remove_subscriber() waits only
  while the callback it removes runs, not for the whole delivery, then takes
  the callback out so it is destroyed by remove_subscriber(), not later on the
  topic's thread.
- When the component isn't registered, remove_subscriber() still waits for its
  callback on every topic of that name whose thread is still running, including
  topics being retired or cleared.
- Each topic thread records what it waits for. A wait that would lead back to
  the caller's own thread is skipped instead of deadlocking. Joining a stopping
  topic waits the same way, so clear() in one topic's callback while another
  topic's removes from it can't deadlock either.
- A delivery counts as running on the topic's thread until it has let go of its
  snapshot.
- add_subscriber() returns false while clear() runs, and from the destructor
  on. Topic's destructor sets stopping and wakes the thread before joining it.
- Topics that lost their last subscriber are joined from publish() too, once
  their thread is done (on ESP-IDF its stack is held until then).
- A callback that removes the topic's last subscriber and subscribes again
  keeps the topic's thread instead of starting a new one.
- The logger for callback exceptions is never destroyed, so a callback that
  throws while the program exits is still safe.
- Docs: the two cases where removal can't wait, the topic task's priority, and
  add_subscriber() during clear(). Fix the stop_registry.h and python test
  comments.

Tests: pc/tests/event_manager.cpp gains a section for each of these (83 checks,
was 52). A hang caught by returns_within() now fails the test at once, instead
of leaving the stuck thread to crash later checks. python/event_manager_test.py
gains exit_while_callback_subscribes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
@finger563
finger563 merged commit 8ce88e8 into main Nov 26, 2026
193 of 194 checks passed
@finger563
finger563 deleted the fix/event-manager-concurrency branch November 26, 2026 23:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant