12 KiB
M-ASYNC-05 — EventBus/Observable snapshot dispatch, joined subscriptions, injected scheduling
Task ID: M-ASYNC-05 Role: sonnet-implementer Status: READY
1. Context and baseline
- Wave 11 package step A3 (after A2 M-ASYNC-04 is committed). Repo VoidLibrary, branch
feat/roadmap-p2-wave11. Isolated worktree; first fast-forward it to the HEAD stated in your prompt. - Baseline: full suite at
38436b1= 1,484 tests (1,480 ✔, 4 ⊘). - Observed source (M-ASYNC-01 characterization folded in):
include/Void/Async/EventBus.hpp(Void::EventBus): syncpublishiterates the live vector without the lock (:156-164) so subscribe/unsubscribe during dispatch is UB; Async mode starts a private thread in the constructor (:43-48); the async snapshot copiesstd::functions sounsubscribecannot retract queued copies (:167-169); a handler exception escapes the worker loop and terminates (:248-269); task queue and handler list unbounded (:272-278);:115-121);Subscription::resetdoes not join (Subscriptionholds a rawEventBus*(:137-146);:193-201).flush()returns void (include/Void/Async/Observable.hpp:Observable/Signaliterate live vectors (:74-77, :116-119); reentrant use is UB; no threading policy; on throw the value stays new (:40-42).- Existing tests:
tests/standalone/Async/{EventBus,EventBusAsync,Observable}.cpp(12/4/14). - Available from A2:
Async::ThreadExecutor(bounded,join,is_executor_thread),ManualExecutor.
- Requirements: roadmap row M-ASYNC-05 ("EventBus/Observable snapshot dispatch, joined subscriptions, injected scheduling | Reentrancy, callback throw and unsubscribe races leave no captured state in use after join"); C-03/C-05; decisions D-W11-06 (accepted with conditions), D-038, D-040 (N6, P3-8).
- MANDATORY design sources:
docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md§M-ASYNC-05,W11-PLAN-REV1-OUTPUT.mdF12 + P3 (Observable/Signal, captured-state tests),W11-CONTRACT-R2.mdN6. Precedence R2 > REV1 > PLAN.
2. Objective and deliverables
EDIT include/Void/Async/EventBus.hpp and include/Void/Async/Observable.hpp; NEW tests
tests/standalone/Async/EventBusJoin.cpp, tests/standalone/Async/ObservableReentrancy.cpp.
3. Scope and non-goals
Out: Executor/Operation/TaskScope/ThreadExecutor changes, build files, other modules.
4. Files to inspect
include/Void/Async/{EventBus,Observable,Executor,TaskScope,ThreadExecutor}.hpp, the three existing
tests, and the design sources in §1.
5. Write ownership and coordination
Write scope: include/Void/Async/EventBus.hpp, include/Void/Async/Observable.hpp,
tests/standalone/Async/EventBusJoin.cpp (NEW), tests/standalone/Async/ObservableReentrancy.cpp (NEW).
Forbidden: every other path, including the existing EventBus/Observable test files. Other implementers
work concurrently in other worktrees (IO; Runtime). No git operations except the authorized fast-forward.
6. Implementation or investigation approach
MANDATORY:
- Subscription state in shared ownership; every dispatch (all modes) iterates a snapshot of entries and checks a per-entry live flag before invoking; callbacks run outside locks.
- NEW
Mode::Injected+EventBus(Async::Executor&, BusOptions): no private thread; dispatch frames captureshared_ptr<detail::BusCore>; bounded subscriptions/admitted dispatches →overloaded; Injected and Async modes catch handler exceptions and route them toerror_sink(outside locks), countingcallback_failures; a throwingerror_sinkis caught and counted (D-W11-06 condition). Syncpublishkeeps 1.x exception propagation. Subscription::close_and_join(): suppresses admitted-but-not-started deliveries, waits for in-flight callbacks on other threads, resets the handler (releasing captured state) before returning; on its own callback thread →self_join(self-unsubscribe via legacyunsubscribe/resetstill works).- 1.x
unsubscribeinMode::Asyncstill delivers already-queued copies (pinned test). EventBus::close_and_join()/close_and_join_pumping(ManualExecutor&);flush_blocking()(self_joinon an executor thread or inside a bus callback;invalid_argumenton a ManualExecutor);flush_pumping(ManualExecutor&); legacyflush()in Injected mode callsflush_blocking()and discards the error (never deadlocks).~EventBus(N6): gates every admitted-but-not-started delivery on every thread before returning (coreclosedflag checked under the core lock before each delivery starts); waits for callbacks running on OTHER threads, excluding the current thread's own in-progress callback (thread-local dispatch depth); documented residual: destroying a bus from inside a callback that another thread's callback waits on can deadlock (caller error). On a ManualExecutor it pumps (TaskScope pattern).- Observable/Signal (REV1 P3): documented single-threaded, not thread-safe, reentrancy-safe. For
copyable
T(std::copy_constructible): nestedsetupdates the value immediately and queues(old, new)copies delivered FIFO after the current pass, bounded atkMaxPendingNotifications = 1024; overflow keeps the new value and counts a dropped notification;try_set(T)(copyable only) →overloadedwithout changing the value;dropped_notifications(). Move-onlyT: 1.x immediate recursive notification over a listener snapshot, no queue, notry_set. Unsubscribe during a pass skips that listener for the rest of the pass; subscribe during a pass is not in the current pass. On a throw: the value stays new, dispatch depth restored, that pass's queued notifications dropped and counted, exception propagates from the outermostset/emit.Signal<Args...>follows the same rule when all decayedArgsare copyable (queue ismutable).
7. Interfaces and data contracts
namespace Void::EventBus {
enum class Mode { Sync, Async, Injected }; // NEW enumerator appended
struct BusOptions { std::size_t max_subscriptions{1024}; std::size_t max_admitted_dispatches{1024};
std::function<void(std::exception_ptr)> error_sink{}; };
// EventBus additions (existing API unchanged):
explicit EventBus(Void::Async::Executor& executor, BusOptions = {});
template <class Event> [[nodiscard]] Void::Result::Result<Subscription> try_subscribe(std::function<void(const Event&)>);
template <class Event> [[nodiscard]] Void::Result::Result<void> try_publish(const Event&); // overloaded / closed
[[nodiscard]] Void::Result::Result<void> close_and_join();
[[nodiscard]] Void::Result::Result<void> close_and_join_pumping(Void::Async::ManualExecutor&);
[[nodiscard]] Void::Result::Result<void> flush_blocking();
[[nodiscard]] Void::Result::Result<void> flush_pumping(Void::Async::ManualExecutor&);
[[nodiscard]] std::uint64_t callback_failures() const noexcept;
// Subscription addition: [[nodiscard]] Void::Result::Result<void> close_and_join();
}
// Observable.hpp: inline constexpr std::size_t kMaxPendingNotifications = 1024;
// Observable<T>: Void::Result::Result<void> try_set(T) requires std::copy_constructible<T>;
// std::size_t dropped_notifications() const noexcept;
Errors use Void::Async::make_async_error codes (overloaded, closed, self_join, invalid_argument).
If EventBus.hpp currently includes no Async headers, adding Void/Async/Executor.hpp is allowed (same
module). Unchanged 1.x: every existing EventBus/Observable/Signal signature and their existing tests.
8. Dependencies and integration
Upstream: A2 (ThreadExecutor) in your base. Downstream: none in this wave. Root integrates and commits.
9. Edge cases security and performance
Reentrant subscribe/unsubscribe/publish inside callbacks (ASan); unsubscribe vs dispatch races (TSan);
callback throw in every mode; destruction on executor thread; captured-state release verified by a
sentinel shared_ptr use_count() == 1 after join; bounded queues; no user code under locks.
10. Acceptance criteria
EventBusJoin.cpp:bus_injected_no_private_thread_manual_pumping,bus_injected_subscription_limit_overloaded,bus_injected_dispatch_limit_overloaded,bus_close_and_join_waits_inflight_releases_capture_tsan,bus_unsubscribe_during_dispatch_prevents_later_admission,bus_self_unsubscribe_ok_self_join_rejected,bus_callback_throw_to_error_sink_others_run,bus_error_sink_throw_caught_and_counted,bus_legacy_async_unsubscribe_keeps_queued_copy,bus_sync_reentrant_subscribe_unsubscribe_asan,bus_publish_after_close_closed,bus_sync_unsubscribe_releases_captured_state,bus_legacy_async_unsubscribe_then_flush_releases_captured_state,bus_legacy_async_close_and_join_releases_capture_with_queued_copies,bus_destructor_gates_admitted_deliveries,bus_flush_blocking_self_join_and_manual_invalid.ObservableReentrancy.cpp:observable_nested_set_fifo,observable_unsubscribe_in_listener_skips_rest,observable_subscribe_in_listener_not_current_pass,observable_try_set_overloaded_when_pending_full,observable_listener_throw_restores_state,observable_self_unsubscribe_releases_capture,observable_move_only_immediate_notification_compat,signal_reentrant_connect_disconnect_during_emit.- Existing
EventBus,EventBusAsync,Observabletests pass unchanged; TSan 0 races; ASan+UBSan 0 errors;-Werrorsyntax checks clean.
11. Verification commands and evidence
Cwd = worktree root; dev with the sandbox disabled. Confirm the new suites appear in the output.
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async5 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async5 --parallel 8 && /tmp/void-w11-async5/tests/VoidTests --filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\." && ctest --test-dir /tmp/void-w11-async5 --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async5-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON && cmake --build /tmp/void-w11-async5-tsan --parallel 8 && /tmp/void-w11-async5-tsan/tests/VoidTests --filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\."'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async5-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON && cmake --build /tmp/void-w11-async5-asan --parallel 8 && /tmp/void-w11-async5-asan/tests/VoidTests --filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\."'
dev cpp-gcc -c bash -lc 'for f in EventBusJoin ObservableReentrancy; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/Async/$f.cpp || exit 1; done'
Also run the full Async;Testing VoidTests binary unfiltered once to catch regressions in other Async
users (Fsm is not selected; root runs the full suite at integration).
12. Constraints and stop conditions
No edits outside write scope; no weakened assertions; 1.x behavior changes limited to those recorded in MIGRATION (snapshot dispatch, nested FIFO for copyable, Async-mode exceptions counted). Stop and report BLOCKED if an existing EventBus/Observable test must change, or two repair attempts at one check fail.
13. Authorization and decisions
Root decisions D-034, D-038, D-040, D-042 under user decisions D-027/D-029/D-031. Listed files only; no commits, pushes or other side effects.
14. Return format
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance criterion; commands with cwd/results; checks not run; residual risks; worktree path. Do not spawn children.