fix(wave11): resolve adversarial review findings in EventBus, IO, and Runtime

This commit is contained in:
faumaray committed 2026-12-01 22:03:35 +03:00
1 parent 7bea7df46d
commit c6de7842f7
10 files changed
+871 -134

No files matched your search

+36 -36
View File
@@ -240,6 +240,27 @@ struct BusCore : std::enable_shared_from_this<BusCore> {
}
}
void finish_entry_dispatch(const std::shared_ptr<SubEntry>& entry) noexcept
{
for (;;) {
std::function<void(const void*)> 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<void> join_entry(
const std::shared_ptr<SubEntry>& entry)
{
@@ -298,10 +319,11 @@ struct BusCore : std::enable_shared_from_this<BusCore> {
const void* ev_raw = item.event.get();
for (auto& rec : item.recipients) {
std::function<void(const void*)> fn;
std::function<void(const void*)> 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<BusCore> {
}
fn = {};
std::function<void(const void*)> 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<void(const void*)> 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<void(const void*)> 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<std::function<void(const void*)>> to_drop;
{
+17 -3
View File
@@ -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<std::int32_t>(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<std::chrono::nanoseconds>(
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;
+15 -3
View File
@@ -102,7 +102,9 @@ template <class Done>
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 <class Done>
}
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 <class Done>
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<std::chrono::nanoseconds>(
wait - poll_elapsed);
const auto slice = std::min(
remain,
std::chrono::nanoseconds{std::chrono::milliseconds{1}});
wait_stop_aware(slice);
}
}
}
+172 -31
View File
@@ -183,6 +183,7 @@ struct HostCore {
std::vector<std::string> 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<std::int32_t>(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<std::int32_t>(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<std::chrono::nanoseconds>(
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<void> {
{
@@ -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<Async::TaskScope>(
*owned_executor,
auto scope_local = std::make_unique<Async::TaskScope>(
*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<Async::TaskScope>(
auto scope_local = std::make_unique<Async::TaskScope>(
*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<ComponentEntry> 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;