From c6de7842f7325c8a10ea4f2d921c099af534ba6c Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Tue, 1 Dec 2026 22:03:35 +0300 Subject: [PATCH] fix(wave11): resolve adversarial review findings in EventBus, IO, and Runtime --- include/Void/Async/EventBus.hpp | 72 +++---- include/Void/IO/Driver.hpp | 20 +- include/Void/IO/Pump.hpp | 18 +- include/Void/Runtime/Detail/HostCore.hpp | 203 +++++++++++++++--- src/IO/EpollDriver.cpp | 125 ++++++------ tests/standalone/Async/EventBusJoin.cpp | 169 +++++++++++++++ tests/standalone/IO/IoPump.cpp | 24 +++ tests/standalone/IO/IoShutdown.cpp | 204 +++++++++++++++++++ tests/standalone/Runtime/RuntimeShutdown.cpp | 91 +++++++++ tests/standalone/Runtime/RuntimeStart.cpp | 79 +++++++ 10 files changed, 871 insertions(+), 134 deletions(-) diff --git a/include/Void/Async/EventBus.hpp b/include/Void/Async/EventBus.hpp index cd78e77..3770ef6 100644 --- a/include/Void/Async/EventBus.hpp +++ b/include/Void/Async/EventBus.hpp @@ -240,6 +240,27 @@ struct BusCore : std::enable_shared_from_this { } } + void finish_entry_dispatch(const std::shared_ptr& entry) noexcept + { + for (;;) { + std::function cleanup_fn; + { + std::lock_guard lk{mu}; + if (!entry->active && entry->in_flight == 1 && entry->handler) { + cleanup_fn = std::move(entry->handler); + } else { + --entry->in_flight; + --total_in_flight; + break; + } + } + // Destroy captured state outside mu while in_flight >= 1 so + // join_entry / close_and_join / ~EventBus cannot return early. + cleanup_fn = {}; + } + done_cv.notify_all(); + } + [[nodiscard]] Void::Result::Result join_entry( const std::shared_ptr& entry) { @@ -298,10 +319,11 @@ struct BusCore : std::enable_shared_from_this { const void* ev_raw = item.event.get(); for (auto& rec : item.recipients) { std::function fn; + std::function discarded_legacy; { std::lock_guard lk{mu}; if (closed || rec.entry->purged) { - rec.legacy_fn = {}; + discarded_legacy = std::move(rec.legacy_fn); continue; } if (!rec.legacy_fn && !rec.entry->active) { @@ -326,18 +348,7 @@ struct BusCore : std::enable_shared_from_this { } fn = {}; - std::function cleanup_fn; - { - std::lock_guard lk{mu}; - --rec.entry->in_flight; - --total_in_flight; - if (!rec.entry->active && rec.entry->in_flight == 0 && - rec.entry->handler) { - cleanup_fn = std::move(rec.entry->handler); - } - } - done_cv.notify_all(); - cleanup_fn = {}; + finish_entry_dispatch(rec.entry); } // Destroy event payload and recipient handles before completion notify. @@ -460,17 +471,7 @@ inline DispatchCoroutine make_injected_dispatch( } fn = {}; - std::function cleanup_fn; - { - std::lock_guard lk{core->mu}; - --entry->in_flight; - --core->total_in_flight; - if (!entry->active && entry->in_flight == 0 && entry->handler) { - cleanup_fn = std::move(entry->handler); - } - } - core->done_cv.notify_all(); - cleanup_fn = {}; + core->finish_entry_dispatch(entry); } snapshot.clear(); @@ -709,18 +710,7 @@ public: ~EntryExitGuard() { fn_ref = {}; - std::function cleanup; - { - std::lock_guard lk{core->mu}; - --entry->in_flight; - --core->total_in_flight; - if (!entry->active && entry->in_flight == 0 && - entry->handler) { - cleanup = std::move(entry->handler); - } - } - core->done_cv.notify_all(); - cleanup = {}; + core->finish_entry_dispatch(entry); } } exit_guard{core, entry, fn}; @@ -933,6 +923,11 @@ public: Void::Async::AsyncErrorCode::invalid_argument, "EventBus::flush_pumping requires a matching ManualExecutor")}; } + if (detail::is_on_bus_callback(core_.get())) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::self_join, + "EventBus::flush_pumping cannot be called from inside a callback")}; + } std::uint64_t target = 0; { std::lock_guard lk{core_->mu}; @@ -1036,6 +1031,11 @@ public: Void::Async::AsyncErrorCode::invalid_argument, "EventBus::close_and_join_pumping requires a matching ManualExecutor")}; } + if (detail::is_on_bus_callback(core_.get())) { + return std::unexpected{Void::Async::make_async_error( + Void::Async::AsyncErrorCode::self_join, + "EventBus::close_and_join_pumping cannot be called from inside a callback")}; + } std::vector> to_drop; { diff --git a/include/Void/IO/Driver.hpp b/include/Void/IO/Driver.hpp index d9c58d9..ccd8007 100644 --- a/include/Void/IO/Driver.hpp +++ b/include/Void/IO/Driver.hpp @@ -187,12 +187,16 @@ public: }; std::size_t total = 0; + std::size_t consecutive_fast_zero = 0; while (!stop.stop_requested() && !shutdown_complete()) { + const auto poll_start = std::chrono::steady_clock::now(); auto res = poll_once(max_wait); + const auto poll_elapsed = std::chrono::steady_clock::now() - poll_start; if (!res.has_value()) { if (res.error().code().domain == Void::Result::kIoErrorDomain && res.error().code().value == static_cast(IoErrorCode::busy)) { + consecutive_fast_zero = 0; const auto busy_slice = max_wait > std::chrono::nanoseconds{0} ? std::min(max_wait, @@ -206,9 +210,19 @@ public: return std::unexpected{std::move(res.error())}; } total += *res; - if (*res == 0 && active_backend() == BackendPreference::mock && - max_wait > std::chrono::nanoseconds{0}) { - wait_stop_aware(max_wait); + if (*res == 0 && max_wait > std::chrono::nanoseconds{0} && + poll_elapsed < max_wait) { + const auto remain = std::chrono::duration_cast( + max_wait - poll_elapsed); + if (active_backend() == BackendPreference::mock) { + wait_stop_aware(remain); + } else if (++consecutive_fast_zero >= 2) { + wait_stop_aware(std::min( + remain, + std::chrono::nanoseconds{std::chrono::milliseconds{1}})); + } + } else { + consecutive_fast_zero = 0; } } return total; diff --git a/include/Void/IO/Pump.hpp b/include/Void/IO/Pump.hpp index ba27838..db0e076 100644 --- a/include/Void/IO/Pump.hpp +++ b/include/Void/IO/Pump.hpp @@ -102,7 +102,9 @@ template wait = std::chrono::nanoseconds{0}; } + const auto poll_start = std::chrono::steady_clock::now(); auto poll_res = driver.poll_once(wait); + const auto poll_elapsed = std::chrono::steady_clock::now() - poll_start; if (!poll_res.has_value()) { if (poll_res.error().code().domain == Void::Result::kIoErrorDomain && poll_res.error().code().value == @@ -119,12 +121,13 @@ template } return std::unexpected{std::move(poll_res.error())}; } - total_work += *poll_res; + std::size_t turn_work = *poll_res; if (options.timers != nullptr) { - total_work += options.timers->poll_expired(); + turn_work += options.timers->poll_expired(); } - total_work += manual.drain(); + turn_work += manual.drain(); + total_work += turn_work; if (done()) { return total_work; @@ -132,6 +135,15 @@ template if (driver.shutdown_complete()) { return total_work; } + if (turn_work == 0 && manual.empty() && + wait > std::chrono::nanoseconds{0} && poll_elapsed < wait) { + const auto remain = std::chrono::duration_cast( + wait - poll_elapsed); + const auto slice = std::min( + remain, + std::chrono::nanoseconds{std::chrono::milliseconds{1}}); + wait_stop_aware(slice); + } } } diff --git a/include/Void/Runtime/Detail/HostCore.hpp b/include/Void/Runtime/Detail/HostCore.hpp index 7fe5792..3d94569 100644 --- a/include/Void/Runtime/Detail/HostCore.hpp +++ b/include/Void/Runtime/Detail/HostCore.hpp @@ -183,6 +183,7 @@ struct HostCore { std::vector started_component_ids{}; ShutdownPhase phase{ShutdownPhase::not_started}; + bool start_running{false}; bool shutdown_running{false}; bool begin_shutdown_called{false}; bool failed_start_incomplete{false}; @@ -255,6 +256,23 @@ struct HostCore { break; } } + } else if (embedded.executor != nullptr && + embedded.executor->has_background_workers()) { + for (;;) { + auto r = shutdown_blocking_impl( + Async::OperationOptions{.deadline = TimePoint::max()}, + /*unbounded=*/true); + if (!r.has_value()) { + std::fputs( + "Void::Runtime::Host (embedded background-worker executor) " + "destructor could not complete shutdown; terminating\n", + stderr); + std::terminate(); + } + if (r->complete) { + break; + } + } } else { std::fputs( "Void::Runtime::Host (embedded non-ManualExecutor) destroyed before " @@ -370,12 +388,24 @@ struct HostCore { if (tl_reactor_host() == this) { return true; } - if (!options.embedded_mode && owned_executor && - owned_executor->is_executor_thread()) { + if (options.embedded_mode) { + if (embedded.executor != nullptr && + embedded.executor->is_executor_thread()) { + return true; + } + return false; + } + Async::ThreadExecutor* exec = nullptr; + bool has_drv = false; + { + std::lock_guard lk{mu}; + exec = owned_executor.get(); + has_drv = (owned_driver != nullptr); + } + if (exec != nullptr && exec->is_executor_thread()) { return true; } - if (!options.embedded_mode && owned_driver && - IO::is_io_worker_thread()) { + if (has_drv && IO::is_io_worker_thread()) { return true; } return false; @@ -513,7 +543,11 @@ struct HostCore { return true; } } - IO::Driver* drv = get_io(); + IO::Driver* drv = nullptr; + { + std::lock_guard lk{mu}; + drv = get_io(); + } if (drv == nullptr) { return pred(); } @@ -524,8 +558,25 @@ struct HostCore { opts.operation.deadline = deadline; } opts.timers = timers; - (void)IO::pump_until(*drv, manual, pred, opts); - return pred(); + for (;;) { + auto r = IO::pump_until(*drv, manual, pred, opts); + if (pred()) { + return true; + } + if (single_drain_if_poll || stop.stop_requested()) { + return false; + } + if (deadline != TimePoint::max() && active_clock().now() >= deadline) { + return pred(); + } + if (!r.has_value() && + r.error().code().domain == Void::Result::kIoErrorDomain && + r.error().code().value == + static_cast(IO::IoErrorCode::exhausted)) { + continue; + } + return pred(); + } } void run_reactor_loop() @@ -560,12 +611,16 @@ struct HostCore { } }; + std::size_t consecutive_fast_zero = 0; while (!stop.stop_requested() && !owned_driver->shutdown_complete()) { + const auto poll_start = std::chrono::steady_clock::now(); auto r = owned_driver->poll_once(kMaxWait); + const auto poll_elapsed = std::chrono::steady_clock::now() - poll_start; if (!r.has_value()) { if (r.error().code().domain == Void::Result::kIoErrorDomain && r.error().code().value == static_cast(IO::IoErrorCode::busy)) { + consecutive_fast_zero = 0; wait_stop_aware(std::chrono::milliseconds{1}); continue; } @@ -573,9 +628,18 @@ struct HostCore { } reactor_turns.fetch_add(1, std::memory_order_release); cv.notify_all(); - if (*r == 0 && - owned_driver->active_backend() == IO::BackendPreference::mock) { - wait_stop_aware(kMaxWait); + if (*r == 0 && poll_elapsed < kMaxWait) { + const auto remain = std::chrono::duration_cast( + kMaxWait - poll_elapsed); + if (owned_driver->active_backend() == IO::BackendPreference::mock) { + wait_stop_aware(remain); + } else if (++consecutive_fast_zero >= 2) { + wait_stop_aware(std::min( + remain, + std::chrono::nanoseconds{std::chrono::milliseconds{1}})); + } + } else { + consecutive_fast_zero = 0; } } } @@ -676,9 +740,12 @@ struct HostCore { auto io_rep = owned_driver->shutdown( Async::OperationOptions{.deadline = cleanup_dl}); if (!io_rep.has_value() || !io_rep->complete) { + const std::size_t file_workers_alive = + owned_driver->telemetry().file_workers_running; std::lock_guard lk{mu}; started_workers = - owned_executor ? options.cpu_workers : 0; + (owned_executor ? options.cpu_workers : 0) + + file_workers_alive; failed_start_incomplete = true; last_report = build_report_locked(false); return; @@ -752,12 +819,23 @@ struct HostCore { "Host::start requires HostState::constructed")}; } state = HostState::starting; + start_running = true; owner_thread = std::this_thread::get_id(); start_options = std::move(opts); signal_gate = start_options.signal_gate; on_phase = start_options.on_phase; } + struct StartGuard { + HostCore& self; + ~StartGuard() + { + std::lock_guard lk{self.mu}; + self.start_running = false; + self.cv.notify_all(); + } + } start_guard{*this}; + const auto fail_at = [&](StartStep step, Void::Result::Error err) -> Void::Result::Result { { @@ -815,17 +893,28 @@ struct HostCore { if (!exec_res.has_value()) { return fail_at(StartStep::cpu_executor, std::move(exec_res.error())); } - owned_executor = std::move(*exec_res); - if (auto st = owned_executor->start(); !st.has_value()) { + Async::ThreadExecutor* exec_raw = exec_res->get(); + { + std::lock_guard lk{mu}; + owned_executor = std::move(*exec_res); + } + if (auto st = exec_raw->start(); !st.has_value()) { return fail_at(StartStep::cpu_executor, std::move(st.error())); } - business_scope = std::make_unique( - *owned_executor, + auto scope_local = std::make_unique( + *exec_raw, Async::TaskScopeOptions{ .max_tasks = options.limits.max_cpu_tasks, .stop_on_first_error = false, }, active_clock()); + { + std::lock_guard lk{mu}; + business_scope = std::move(scope_local); + if (admission_closed) { + business_scope->close(); + } + } // Step 4: io_driver if (auto sr = run_before_step(StartStep::io_driver); !sr.has_value()) { @@ -840,17 +929,21 @@ struct HostCore { }; } auto drv_res = IO::Driver::create( - *owned_executor, std::move(io_opts), active_clock(), &active_budget()); + *exec_raw, std::move(io_opts), active_clock(), &active_budget()); if (!drv_res.has_value()) { return fail_at(StartStep::io_driver, std::move(drv_res.error())); } - owned_driver = std::move(*drv_res); + IO::Driver* drv_raw = drv_res->get(); + { + std::lock_guard lk{mu}; + owned_driver = std::move(*drv_res); + } // Step 5: file_workers if (auto sr = run_before_step(StartStep::file_workers); !sr.has_value()) { return fail_at(StartStep::file_workers, std::move(sr.error())); } - if (auto fw = owned_driver->start_file_workers(); !fw.has_value()) { + if (auto fw = drv_raw->start_file_workers(); !fw.has_value()) { return fail_at(StartStep::file_workers, std::move(fw.error())); } @@ -877,13 +970,18 @@ struct HostCore { started_workers = options.cpu_workers + options.file_workers + 1; } } else { - business_scope = std::make_unique( + auto scope_local = std::make_unique( *embedded.executor, Async::TaskScopeOptions{ .max_tasks = options.limits.max_cpu_tasks, .stop_on_first_error = false, }, active_clock()); + std::lock_guard lk{mu}; + business_scope = std::move(scope_local); + if (admission_closed) { + business_scope->close(); + } } // Step 7: components in startup_order (outside mu) @@ -898,17 +996,27 @@ struct HostCore { active_budget(), business_stop_source.get_token()}; for (const auto& id : plan.startup_order) { - auto it = registered_components.find(id); - if (it == registered_components.end() || !it->second) { + std::shared_ptr entry; + { + std::lock_guard lk{mu}; + auto it = registered_components.find(id); + if (it != registered_components.end()) { + entry = it->second; + } + } + if (!entry) { continue; } - auto comp_res = it->second->component->start(ctx); + auto comp_res = entry->component->start(ctx); if (!comp_res.has_value()) { return fail_at( StartStep::components, std::move(comp_res.error())); } - it->second->started = true; - started_component_ids.push_back(id); + { + std::lock_guard lk{mu}; + entry->started = true; + started_component_ids.push_back(id); + } } } @@ -954,8 +1062,16 @@ struct HostCore { { std::lock_guard lk{mu}; - state = HostState::running; - ready = true; + if (admission_closed || begin_shutdown_called) { + state = HostState::stopping_admission; + ready = false; + if (business_scope) { + business_scope->close(); + } + } else { + state = HostState::running; + ready = true; + } } return {}; } @@ -994,9 +1110,15 @@ struct HostCore { "Host::shutdown_blocking called from an owned worker, reactor, or IO " "worker thread")}; } - if (options.embedded_mode || - (active_executor() != nullptr && - !active_executor()->has_background_workers())) { + bool lacks_bg_workers = false; + { + std::lock_guard lk{mu}; + if (auto* exec = active_executor(); + exec != nullptr && !exec->has_background_workers()) { + lacks_bg_workers = true; + } + } + if (lacks_bg_workers) { return std::unexpected{make_runtime_error( RuntimeErrorCode::invalid_argument, "Host::shutdown_blocking requires background workers; use shutdown_pumping")}; @@ -1071,7 +1193,13 @@ private: { std::unique_lock lk{mu}; - while (shutdown_running) { + if (start_running && owner_thread.has_value() && + std::this_thread::get_id() == *owner_thread) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_state, + "Host shutdown cannot be called reentrantly from Host::start")}; + } + while (start_running || shutdown_running) { if (!unbounded && opts.stop.stop_requested()) { return build_report_locked(false); } @@ -1339,6 +1467,7 @@ private: return true; }; + bool polled_once = false; for (;;) { if (all_exporters_done()) { break; @@ -1355,6 +1484,14 @@ private: if (flushed_expired_now) { (void)exporter_stop_source.request_stop(); } + if (single_drain_if_poll && !polled_once && + manual != nullptr && !opts.stop.stop_requested()) { + polled_once = true; + (void)manual->drain(); + if (all_exporters_done()) { + break; + } + } if (deadline_or_stop()) { return return_incomplete(); } @@ -1450,8 +1587,12 @@ private: } auto io_rep = owned_driver->shutdown(std::move(io_op)); if (!io_rep.has_value() || !io_rep->complete) { + const std::size_t file_workers_alive = + owned_driver->telemetry().file_workers_running; std::lock_guard lk{mu}; - started_workers = options.cpu_workers; + started_workers = + (owned_executor ? options.cpu_workers : 0) + + file_workers_alive; state = HostState::shutdown_incomplete; last_report = build_report_locked(false); return *last_report; diff --git a/src/IO/EpollDriver.cpp b/src/IO/EpollDriver.cpp index 7c3b729..c0033ba 100644 --- a/src/IO/EpollDriver.cpp +++ b/src/IO/EpollDriver.cpp @@ -189,6 +189,7 @@ struct DescriptorSlot { bool close_enqueued{false}; bool eof_seen{false}; bool epoll_registered{false}; + bool epoll_in_armed{false}; bool epoll_out_armed{false}; // S5: a File occupies a slot with fd == -1; socket paths skip it and the // file descriptor lives only in FileState. @@ -731,6 +732,8 @@ protected: virtual std::size_t drain_socket_queues(std::vector& tickets) = 0; // Stopping: the slot's interest is dropped (poll owner only, mu_ held). virtual void on_slot_abort_locked(DescriptorSlot&) noexcept {} + // Called under mu_ right after an op is cleared from a slot. + virtual void on_op_retired_locked(DescriptorSlot&) noexcept {} // Shutdown step 5 for socket slots (mu_ held): close the native fd. [[nodiscard]] virtual bool closes_native_fds() const noexcept { return false; } virtual void on_slot_final_close_locked(DescriptorSlot&) noexcept {} @@ -800,6 +803,7 @@ protected: s.close_enqueued = false; s.eof_seen = false; s.epoll_registered = false; + s.epoll_in_armed = false; s.epoll_out_armed = false; s.is_file = false; s.file.reset(); @@ -830,6 +834,7 @@ protected: s.close_enqueued = false; s.eof_seen = false; s.epoll_registered = false; + s.epoll_in_armed = false; s.epoll_out_armed = false; s.is_file = false; s.file.reset(); @@ -867,6 +872,7 @@ protected: } else if (op.dir == Direction::write && slot.active_write.get() == &op) { slot.active_write.reset(); } + on_op_retired_locked(slot); if (slot.closing && !slot.active_read && !slot.active_write && kind() == BackendPreference::mock) { ready_close_waiters.insert( @@ -886,10 +892,14 @@ protected: bool complete_op_and_collect_tickets(const std::shared_ptr& op, const Void::Result::Result& res, std::vector& out_tickets, - std::vector& close_waiters) + std::vector& close_waiters, + bool skip_if_executing = false) { { std::lock_guard lk{mu_}; + if (skip_if_executing && op->in_execution) { + return false; + } if (op->retired) { duplicate_completions_ignored_.fetch_add(1, std::memory_order_acq_rel); return false; @@ -970,7 +980,8 @@ protected: op, std::unexpected{make_io_error(IoErrorCode::closed, "IO Driver shut down")}, tickets, - close_waiters)) { + close_waiters, + /*skip_if_executing=*/true)) { ++done; } } @@ -1774,11 +1785,15 @@ public: [[nodiscard]] std::size_t pending_count(DescriptorId id, Direction dir) const noexcept { std::lock_guard lk{mu_}; + if (stopping_.load(std::memory_order_acquire) || + shutdown_begun_.load(std::memory_order_acquire)) { + return 0; + } if (!id.valid() || id.slot >= slots_.size()) { return 0; } const auto& s = slots_[id.slot]; - if (!s.in_use || s.is_file || s.id.generation != id.generation) { + if (!s.in_use || s.is_file || s.closing || s.id.generation != id.generation) { return 0; } const auto& op = (dir == Direction::read) ? s.active_read : s.active_write; @@ -1789,11 +1804,15 @@ public: try_acquire(DescriptorId id, Direction dir) { std::lock_guard lk{mu_}; + if (stopping_.load(std::memory_order_acquire) || + shutdown_begun_.load(std::memory_order_acquire)) { + return std::nullopt; + } if (!id.valid() || id.slot >= slots_.size()) { return std::nullopt; } auto& s = slots_[id.slot]; - if (!s.in_use || s.is_file || s.id.generation != id.generation) { + if (!s.in_use || s.is_file || s.closing || s.id.generation != id.generation) { return std::nullopt; } auto& op = (dir == Direction::read) ? s.active_read : s.active_write; @@ -1909,19 +1928,12 @@ protected: std::size_t processed = 0; std::vector close_waiters; for (const auto& op : cancels) { - bool executing = false; - { - std::lock_guard lk{mu_}; - executing = op->in_execution && !op->retired; - } - if (executing) { - continue; // Held by a MockController token: stop intent only. - } if (complete_op_and_collect_tickets( op, std::unexpected{make_io_error(IoErrorCode::cancelled, "IO operation cancelled")}, tickets, - close_waiters)) { + close_waiters, + /*skip_if_executing=*/true)) { ++processed; } } @@ -2020,19 +2032,12 @@ private: std::size_t processed = 0; std::vector close_waiters; for (const auto& op : expired) { - bool executing = false; - { - std::lock_guard lk{mu_}; - executing = op->in_execution && !op->retired; - } - if (executing) { - continue; - } if (complete_op_and_collect_tickets( op, std::unexpected{make_io_error(IoErrorCode::timeout, "IO operation timed out")}, tickets, - close_waiters)) { + close_waiters, + /*skip_if_executing=*/true)) { ++processed; } } @@ -2375,9 +2380,15 @@ protected: (void)::epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, s.fd, nullptr); } s.epoll_registered = false; + s.epoll_in_armed = false; s.epoll_out_armed = false; } + void on_op_retired_locked(DescriptorSlot& s) noexcept override + { + sync_epoll_interest_locked(s); + } + [[nodiscard]] bool closes_native_fds() const noexcept override { return true; } void on_slot_final_close_locked(DescriptorSlot& s) noexcept override @@ -2395,7 +2406,9 @@ protected: Direction dir, const std::shared_ptr&) override { - if (!slot.epoll_registered || (dir == Direction::write && !slot.epoll_out_armed)) { + if (!slot.epoll_registered || + (dir == Direction::read && !slot.epoll_in_armed) || + (dir == Direction::write && !slot.epoll_out_armed)) { control_queue_.push_back(ControlAction{ControlAction::Type::arm_interest, slot.id}); } return {}; @@ -2427,13 +2440,30 @@ private: void sync_epoll_interest_locked(DescriptorSlot& slot) noexcept { - if (!slot.in_use || slot.is_file || slot.fd < 0 || slot.closing || epoll_fd_ < 0) { + if (!slot.in_use || slot.is_file || slot.fd < 0 || epoll_fd_ < 0) { + return; + } + const bool want_in = + !slot.closing && + (slot.active_read != nullptr && !slot.active_read->retired); + const bool want_out = + !slot.closing && + (slot.active_write != nullptr && !slot.active_write->retired); + if (!want_in && !want_out) { + if (slot.epoll_registered) { + (void)::epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, slot.fd, nullptr); + slot.epoll_registered = false; + slot.epoll_in_armed = false; + slot.epoll_out_armed = false; + } return; } - const bool want_out = (slot.active_write != nullptr && !slot.active_write->retired); epoll_event ev{}; - std::uint32_t events = static_cast(EPOLLIN) | - static_cast(EPOLLRDHUP); + std::uint32_t events = 0; + if (want_in) { + events |= static_cast(EPOLLIN) | + static_cast(EPOLLRDHUP); + } if (want_out) { events |= static_cast(EPOLLOUT); } @@ -2442,10 +2472,12 @@ private: if (!slot.epoll_registered) { if (::epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, slot.fd, &ev) == 0) { slot.epoll_registered = true; + slot.epoll_in_armed = want_in; slot.epoll_out_armed = want_out; } - } else if (slot.epoll_out_armed != want_out) { + } else if (slot.epoll_in_armed != want_in || slot.epoll_out_armed != want_out) { if (::epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, slot.fd, &ev) == 0) { + slot.epoll_in_armed = want_in; slot.epoll_out_armed = want_out; } } @@ -2485,30 +2517,12 @@ private: } for (const auto& op : cancels) { - bool executing = false; - { - std::lock_guard lk{mu_}; - executing = op->in_execution && !op->retired; - if (!executing && !op->retired && - op->desc_id.slot < slots_.size() && - slots_[op->desc_id.slot].in_use && - slots_[op->desc_id.slot].id.generation == op->desc_id.generation) { - auto& slot = slots_[op->desc_id.slot]; - if (op->dir == Direction::write && slot.epoll_out_armed) { - slot.active_write.reset(); - sync_epoll_interest_locked(slot); - slot.active_write = op; - } - } - } - if (executing) { - continue; // The syscall's real result settles it (D1). - } if (complete_op_and_collect_tickets( op, std::unexpected{make_io_error(IoErrorCode::cancelled, "IO operation cancelled")}, tickets, - close_waiters)) { + close_waiters, + /*skip_if_executing=*/true)) { ++done; } } @@ -2570,23 +2584,12 @@ private: std::size_t done = 0; std::vector close_waiters; for (const auto& op : expired) { - { - std::lock_guard lk{mu_}; - if (!op->retired && op->dir == Direction::write && - op->desc_id.slot < slots_.size() && - slots_[op->desc_id.slot].in_use && - slots_[op->desc_id.slot].id.generation == op->desc_id.generation) { - auto& s = slots_[op->desc_id.slot]; - s.active_write.reset(); - sync_epoll_interest_locked(s); - s.active_write = op; - } - } if (complete_op_and_collect_tickets( op, std::unexpected{make_io_error(IoErrorCode::timeout, "IO operation timed out")}, tickets, - close_waiters)) { + close_waiters, + /*skip_if_executing=*/true)) { ++done; } } diff --git a/tests/standalone/Async/EventBusJoin.cpp b/tests/standalone/Async/EventBusJoin.cpp index 85e0188..649f520 100644 --- a/tests/standalone/Async/EventBusJoin.cpp +++ b/tests/standalone/Async/EventBusJoin.cpp @@ -598,3 +598,172 @@ Void::Testing::Test bus_flush_blocking_self_join_and_manual_invalid() Void::Testing::require(exec->join().has_value()); } } + +Void::Testing::Test bus_pumping_self_join_returns_self_join() +{ + using namespace Void::EventBus; + Void::Async::ManualExecutor manual; + EventBus bus{manual}; + std::optional> fp_res; + std::optional> cj_res; + + auto sub = bus.try_subscribe([&](const Ping&) { + fp_res = bus.flush_pumping(manual); + cj_res = bus.close_and_join_pumping(manual); + }); + Void::Testing::require(sub.has_value()); + Void::Testing::require(bus.try_publish(Ping{7}).has_value()); + (void)manual.drain(); + + Void::Testing::require(fp_res.has_value() && !fp_res->has_value()); + Void::Testing::expect_eq( + async_code(fp_res->error()), + static_cast(Void::Async::AsyncErrorCode::self_join)); + Void::Testing::require(cj_res.has_value() && !cj_res->has_value()); + Void::Testing::expect_eq( + async_code(cj_res->error()), + static_cast(Void::Async::AsyncErrorCode::self_join)); + Void::Testing::require(bus.close_and_join_pumping(manual).has_value()); +} + +Void::Testing::Test bus_close_and_join_waits_for_slow_capture_destructor() +{ + using namespace Void::EventBus; + struct SlowGuard { + explicit SlowGuard(std::atomic* p) : destroyed(p) {} + std::atomic* destroyed{nullptr}; + ~SlowGuard() + { + if (destroyed != nullptr) { + std::this_thread::sleep_for(std::chrono::milliseconds{15}); + destroyed->store(true, std::memory_order_release); + } + } + }; + + // 1. ThreadExecutor subscription::close_and_join waits until slow capture dtor finishes. + { + auto exec_res = Void::Async::ThreadExecutor::create( + Void::Async::ThreadExecutorOptions{.workers = 2, .max_admitted = 16}); + Void::Testing::require(exec_res.has_value()); + auto exec = std::move(*exec_res); + Void::Testing::require(exec->start().has_value()); + + EventBus bus{*exec}; + std::atomic destroyed{false}; + std::latch entered{1}; + std::promise rel; + auto rel_fut = rel.get_future().share(); + auto guard = std::make_shared(&destroyed); + + auto sub = bus.try_subscribe([&, guard](const Ping&) { + (void)guard; + entered.count_down(); + rel_fut.wait(); + }); + Void::Testing::require(sub.has_value()); + guard.reset(); + + Void::Testing::require(bus.try_publish(Ping{1}).has_value()); + entered.wait(); + + std::thread releaser([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + rel.set_value(); + }); + Void::Testing::require(sub->close_and_join().has_value()); + // Must ALREADY be destroyed when close_and_join returns! + Void::Testing::expect(destroyed.load(std::memory_order_acquire)); + releaser.join(); + + Void::Testing::require(bus.close_and_join().has_value()); + exec->close(); + Void::Testing::require(exec->join().has_value()); + } + + // 2. Mode::Async EventBus::close_and_join waits until slow capture dtor finishes. + { + EventBus bus{Mode::Async}; + std::atomic destroyed{false}; + std::latch entered{1}; + std::promise rel; + auto rel_fut = rel.get_future().share(); + auto guard = std::make_shared(&destroyed); + + auto sub = bus.try_subscribe([&, guard](const Ping&) { + (void)guard; + entered.count_down(); + rel_fut.wait(); + }); + Void::Testing::require(sub.has_value()); + guard.reset(); + + bus.publish(Ping{2}); + entered.wait(); + + std::thread releaser([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + rel.set_value(); + }); + Void::Testing::require(bus.close_and_join().has_value()); + Void::Testing::expect(destroyed.load(std::memory_order_acquire)); + releaser.join(); + } +} + +Void::Testing::Test bus_legacy_async_purged_drop_outside_lock() +{ + using namespace Void::EventBus; + struct MuLockingDtor { + EventBus* bus{nullptr}; + std::atomic* dropped{nullptr}; + std::atomic* calls{nullptr}; + ~MuLockingDtor() + { + if (bus != nullptr) { + bus->unsubscribe(0); // Acquires BusCore::mu; would deadlock under lock. + } + if (dropped != nullptr) { + dropped->store(true, std::memory_order_release); + } + if (calls != nullptr) { + calls->fetch_add(1, std::memory_order_relaxed); + } + } + }; + + EventBus bus{Mode::Async}; + std::atomic dropped{false}; + std::atomic dtor_calls{0}; + std::atomic b_ran{0}; + std::optional> sub_b_join_res; + auto sub_b_ptr = std::make_shared>(); + + // Subscribe A before B so run_worker visits A first for the same queued item. + auto sub_a = bus.try_subscribe([&](const Ping&) { + if (*sub_b_ptr) { + sub_b_join_res = (*sub_b_ptr)->close_and_join(); + } + }); + Void::Testing::require(sub_a.has_value()); + + { + auto guard = std::shared_ptr( + new MuLockingDtor{&bus, &dropped, &dtor_calls}); + auto sb = bus.try_subscribe([&, guard](const Ping&) { + (void)guard; + b_ran.fetch_add(1, std::memory_order_relaxed); + }); + Void::Testing::require(sb.has_value()); + *sub_b_ptr = std::move(*sb); + } + + bus.publish(Ping{1}); + bus.flush(); + Void::Testing::require(sub_b_join_res.has_value()); + Void::Testing::expect(sub_b_join_res->has_value()); + Void::Testing::expect_eq(b_ran.load(), 0); + Void::Testing::expect(dropped.load(std::memory_order_acquire)); + Void::Testing::expect_eq(dtor_calls.load(), 1); + Void::Testing::require(bus.close_and_join().has_value()); +} diff --git a/tests/standalone/IO/IoPump.cpp b/tests/standalone/IO/IoPump.cpp index 9b3cd7f..dd58761 100644 --- a/tests/standalone/IO/IoPump.cpp +++ b/tests/standalone/IO/IoPump.cpp @@ -267,3 +267,27 @@ Void::Testing::Test io_pump_until_exits_after_shutdown_complete() require(scope.join_pumping(exec).has_value()); } } + +Void::Testing::Test io_pump_until_mock_max_wait_paces_idle_turns() +{ + ManualExecutor exec; + const auto& clock = Void::Time::SystemMonotonicClock::instance(); + auto drv_res = Driver::create( + exec, BackendOptions{.preference = BackendPreference::mock}, clock); + require(drv_res.has_value()); + Driver& drv = **drv_res; + + auto res = pump_until( + drv, + exec, + [] { return false; }, + PumpOptions{ + .max_wait = 5ms, + .max_turns = 200, + .operation = OperationOptions{.deadline = clock.now() + 20ms}, + }); + require(!res.has_value()); + expect_eq(res.error().code().value, + static_cast(IoErrorCode::timeout)); + expect(drv.telemetry().turns < std::uint64_t{100}); +} diff --git a/tests/standalone/IO/IoShutdown.cpp b/tests/standalone/IO/IoShutdown.cpp index d435793..2f650a9 100644 --- a/tests/standalone/IO/IoShutdown.cpp +++ b/tests/standalone/IO/IoShutdown.cpp @@ -530,3 +530,207 @@ Void::Testing::Test io_run_busy_and_mock_wait_does_not_spin() expect(drv.telemetry().turns < 50); } } + +Void::Testing::Test io_shutdown_epoll_idle_readable_fd_no_busy_spin() +{ + ManualExecutor exec; + auto drv_res = Driver::create( + exec, BackendOptions{.preference = BackendPreference::epoll}); + require(drv_res.has_value()); + Driver& drv = **drv_res; + + auto pair_res = drv.create_socket_pair(); + require(pair_res.has_value()); + ByteStream a = std::move(pair_res->first); + ByteStream b = std::move(pair_res->second); + + // Push unread data into stream `a` while NO read operation is pending on `a`. + TaskScope scope{exec}; + const std::array msg{ + std::byte{'p'}, std::byte{'i'}, std::byte{'n'}, std::byte{'g'}}; + std::optional> wres; + auto wtask = [](ByteStream* st, + std::span sp, + std::optional>* out) + -> Void::Coro::Task { *out = co_await st->write_some(sp); }; + require(scope.spawn(wtask(&b, msg, &wres)).has_value()); + (void)exec.drain(); + while (!wres.has_value()) { + (void)drv.poll_once(1ms); + (void)exec.drain(); + } + require(wres->has_value()); + expect_eq((*wres)->bytes, std::size_t{4}); + + // Running driver with unread data on `a` and no active reader must NOT busy-spin. + std::stop_source stop; + Void::Result::Result run_res{std::size_t{0}}; + std::thread runner([&]() { run_res = drv.run(stop.get_token(), 10ms); }); + std::this_thread::sleep_for(40ms); + stop.request_stop(); + runner.join(); + + require(run_res.has_value()); + expect(drv.telemetry().turns <= std::uint64_t{15}); + + auto rep = drv.shutdown(OperationOptions{}); + require(rep.has_value()); + expect(rep->complete); + require(scope.join_pumping(exec).has_value()); + (void)a; +} + +Void::Testing::Test io_shutdown_mock_try_acquire_race_tsan() +{ + // 1. try_acquire_read refuses once stream close or driver shutdown begins. + { + ManualExecutor exec; + auto drv_res = Driver::create( + exec, BackendOptions{.preference = BackendPreference::mock}); + require(drv_res.has_value()); + Driver& drv = **drv_res; + auto* ctrl = drv.mock_controller(); + require(ctrl != nullptr); + + auto s_res = drv.create_mock_stream(); + require(s_res.has_value()); + ByteStream s = std::move(*s_res); + + std::array buf{}; + std::optional> rres; + TaskScope scope{exec}; + auto rtask = [](ByteStream* st, + std::span sp, + std::optional>* out) + -> Void::Coro::Task { *out = co_await st->read_some(sp); }; + require(scope.spawn(rtask(&s, buf, &rres)).has_value()); + (void)exec.drain(); + + std::optional> cres; + auto ctask = [](ByteStream* st, + std::optional>* out) + -> Void::Coro::Task { *out = co_await st->close_and_join(); }; + require(scope.spawn(ctask(&s, &cres)).has_value()); + (void)exec.drain(); + + expect(!ctrl->try_acquire_read(s).has_value()); + (void)drv.poll_once(0ns); + require(scope.join_pumping(exec).has_value()); + auto rep = drv.shutdown(OperationOptions{}); + require(rep.has_value()); + expect(rep->complete); + } + + // 2. Concurrent race between try_acquire_read and stop_requested cancellation (TSan). + { + ManualExecutor exec; + auto drv_res = Driver::create( + exec, BackendOptions{.preference = BackendPreference::mock}); + require(drv_res.has_value()); + Driver& drv = **drv_res; + auto* ctrl = drv.mock_controller(); + require(ctrl != nullptr); + + auto s_res = drv.create_mock_stream(); + require(s_res.has_value()); + ByteStream s = std::move(*s_res); + + const std::array payload{std::byte{'o'}, std::byte{'k'}}; + for (int iter = 0; iter < 30; ++iter) { + std::array buf{}; + std::optional> rres; + std::stop_source stop_src; + TaskScope scope{exec}; + auto rtask = [](ByteStream* st, + std::span sp, + std::stop_token tok, + std::optional>* out) + -> Void::Coro::Task { + *out = co_await st->read_some(sp, OperationOptions{.stop = tok}); + }; + require(scope.spawn(rtask(&s, buf, stop_src.get_token(), &rres)).has_value()); + (void)exec.drain(); + + std::atomic finish_ok{true}; + std::thread finisher([&]() { + if (auto tok = ctrl->try_acquire_read(s)) { + finish_ok.store( + ctrl->finish_read_data(*tok, payload, false), + std::memory_order_release); + } + }); + std::thread canceller([&]() { + stop_src.request_stop(); + (void)drv.poll_once(0ns); + }); + finisher.join(); + canceller.join(); + expect(finish_ok.load(std::memory_order_acquire)); + (void)drv.poll_once(0ns); + require(scope.join_pumping(exec).has_value()); + + require(rres.has_value()); + if (rres->has_value()) { + expect_eq((*rres)->bytes, std::size_t{2}); + } else { + expect_eq(rres->error().code().value, + static_cast(IoErrorCode::cancelled)); + } + } + auto rep = drv.shutdown(OperationOptions{}); + require(rep.has_value()); + expect(rep->complete); + } + + // 3. Concurrent race between try_acquire_read and Driver::shutdown (TSan). + for (int iter = 0; iter < 15; ++iter) { + ManualExecutor exec; + auto drv_res = Driver::create( + exec, BackendOptions{.preference = BackendPreference::mock}); + require(drv_res.has_value()); + Driver& drv = **drv_res; + auto* ctrl = drv.mock_controller(); + require(ctrl != nullptr); + + auto s_res = drv.create_mock_stream(); + require(s_res.has_value()); + ByteStream s = std::move(*s_res); + + std::array buf{}; + std::optional> rres; + TaskScope scope{exec}; + auto rtask = [](ByteStream* st, + std::span sp, + std::optional>* out) + -> Void::Coro::Task { *out = co_await st->read_some(sp); }; + require(scope.spawn(rtask(&s, buf, &rres)).has_value()); + (void)exec.drain(); + + const std::array payload{std::byte{'o'}, std::byte{'k'}}; + std::atomic finish_ok{true}; + std::thread finisher([&]() { + if (auto tok = ctrl->try_acquire_read(s)) { + finish_ok.store( + ctrl->finish_read_data(*tok, payload, false), + std::memory_order_release); + } + }); + std::optional> sd_rep; + std::thread shutdowner([&]() { + sd_rep = drv.shutdown(OperationOptions{}); + }); + finisher.join(); + shutdowner.join(); + expect(finish_ok.load(std::memory_order_acquire)); + require(sd_rep.has_value() && sd_rep->has_value()); + expect((*sd_rep)->complete); + require(scope.join_pumping(exec).has_value()); + require(rres.has_value()); + if (rres->has_value()) { + expect_eq((*rres)->bytes, std::size_t{2}); + } else { + expect_eq(rres->error().code().value, + static_cast(IoErrorCode::closed)); + } + } +} diff --git a/tests/standalone/Runtime/RuntimeShutdown.cpp b/tests/standalone/Runtime/RuntimeShutdown.cpp index 5d95094..e640f44 100644 --- a/tests/standalone/Runtime/RuntimeShutdown.cpp +++ b/tests/standalone/Runtime/RuntimeShutdown.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -939,3 +940,93 @@ Void::Testing::Test runtime_destructor_blocks_until_complete_after_incomplete_sh expect(task_finished.load(std::memory_order_acquire)); expect_eq(wait_for_task_count(baseline), baseline); } + +Void::Testing::Test runtime_embedded_manual_poll_shutdown_completes_exporter() +{ + ManualExecutor manual; + Void::Time::ManualClock clock; + auto drv_res = Void::IO::Driver::create( + manual, + Void::IO::BackendOptions{.preference = Void::IO::BackendPreference::mock}, + clock); + require(drv_res.has_value()); + + auto exp = std::make_shared(); + HostBuilder builder; + builder.with_embedded(EmbeddedResources{ + .executor = &manual, + .io = drv_res->get(), + .clock = &clock, + }); + require(builder.add_component("exp", ResourceKind::exporter, exp).has_value()); + + auto host_res = builder.build(); + require(host_res.has_value()); + Host host = std::move(*host_res); + require(host.start().has_value()); + + std::optional rep; + for (int i = 0; i < 10; ++i) { + auto pr = host.poll_shutdown(); + require(pr.has_value()); + rep = *pr; + if (rep->complete) { + break; + } + } + require(rep.has_value()); + expect(rep->complete); + expect(rep->state == HostState::stopped); + expect(exp->stop_ran.load(std::memory_order_acquire)); +} + +Void::Testing::Test runtime_embedded_thread_executor_shutdown_blocking_succeeds() +{ + const std::size_t baseline = settle_baseline_tasks(); + auto exec_res = Void::Async::ThreadExecutor::create( + Void::Async::ThreadExecutorOptions{.workers = 2, .max_admitted = 32}); + require(exec_res.has_value()); + auto exec = std::move(*exec_res); + require(exec->start().has_value()); + + auto drv_res = Void::IO::Driver::create( + *exec, + Void::IO::BackendOptions{.preference = Void::IO::BackendPreference::mock}); + require(drv_res.has_value()); + + auto svc = std::make_shared(); + std::atomic task_done{false}; + { + HostBuilder builder; + builder.with_embedded(EmbeddedResources{ + .executor = exec.get(), + .io = drv_res->get(), + }); + require(builder.add_component("svc", ResourceKind::service, svc).has_value()); + + auto host_res = builder.build(); + require(host_res.has_value()); + Host host = std::move(*host_res); + require(host.start().has_value()); + + auto jh = host.spawn(quick_done_task(&task_done)); + require(jh.has_value()); + + auto rep = host.shutdown_blocking(); + require(rep.has_value()); + expect(rep->complete); + expect(rep->state == HostState::stopped); + } + + expect(task_done.load(std::memory_order_acquire)); + expect(svc->stop_ran.load(std::memory_order_acquire)); + expect(!(*drv_res)->shutdown_complete()); + expect(exec->try_reserve_slot().has_value()); + exec->release_reserved(); + + auto drep = (*drv_res)->shutdown(OperationOptions{}); + require(drep.has_value() && drep->complete); + exec->close(); + require(exec->join().has_value()); + expect_eq(wait_for_task_count(baseline), baseline); +} diff --git a/tests/standalone/Runtime/RuntimeStart.cpp b/tests/standalone/Runtime/RuntimeStart.cpp index 3d0a7b8..ae97c17 100644 --- a/tests/standalone/Runtime/RuntimeStart.cpp +++ b/tests/standalone/Runtime/RuntimeStart.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -692,3 +693,81 @@ Void::Testing::Test runtime_moved_from_host_safe_defaults() h1.begin_shutdown(); } + +Void::Testing::Test runtime_begin_shutdown_during_start_prevents_ready() +{ + const std::size_t baseline = settle_baseline_tasks(); + Options opts; + opts.cpu_workers = 1; + opts.file_workers = 1; + opts.io.preference = Void::IO::BackendPreference::mock; + + auto host_res = Host::create(opts); + require(host_res.has_value()); + Host host = std::move(*host_res); + + bool invoked = false; + auto sr = host.start(StartOptions{ + .before_step = [&](StartStep step) -> Void::Result::Result { + if (step == StartStep::components && !invoked) { + invoked = true; + std::thread t([&]() { host.begin_shutdown(); }); + t.join(); + } + return {}; + }, + }); + require(sr.has_value()); + expect(invoked); + expect(!host.is_ready()); + expect(host.state() == HostState::stopping_admission); + + std::atomic flag{false}; + auto spw = host.spawn(set_flag_task(&flag)); + expect(!spw.has_value()); + expect(spw.error() == Void::Async::AdmissionError::stopped); + + auto rep = host.shutdown_blocking(); + require(rep.has_value()); + expect(rep->complete); + expect(rep->state == HostState::stopped); + expect_eq(wait_for_task_count(baseline), baseline); +} + +Void::Testing::Test runtime_concurrent_shutdown_waits_for_start_tsan() +{ + const std::size_t baseline = settle_baseline_tasks(); + Options opts; + opts.cpu_workers = 1; + opts.file_workers = 1; + opts.io.preference = Void::IO::BackendPreference::mock; + + auto host_res = Host::create(opts); + require(host_res.has_value()); + Host host = std::move(*host_res); + + std::latch entered_components{1}; + std::optional> sd_res; + std::thread stopper([&]() { + entered_components.wait(); + sd_res = host.shutdown_blocking(); + }); + + auto sr = host.start(StartOptions{ + .before_step = [&](StartStep step) -> Void::Result::Result { + if (step == StartStep::components) { + entered_components.count_down(); + std::this_thread::sleep_for(10ms); + } + return {}; + }, + }); + stopper.join(); + + require(sr.has_value()); + require(sd_res.has_value() && sd_res->has_value()); + expect((*sd_res)->complete); + expect(host.state() == HostState::stopped); + expect(!host.is_ready()); + expect_eq(wait_for_task_count(baseline), baseline); +}