diff --git a/include/Void/Async/AsyncChannel.hpp b/include/Void/Async/AsyncChannel.hpp new file mode 100644 index 0000000..d512c23 --- /dev/null +++ b/include/Void/Async/AsyncChannel.hpp @@ -0,0 +1,768 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ── AsyncChannel ────────────────────────────────────────────────────────────── +// A bounded multi-producer / multi-consumer channel with coroutine `send` / +// `receive`, cooperative cancellation and optional injected-clock deadlines +// (C-03/C-04). Blocking waits do not exist: a waiter suspends its coroutine +// and is always resumed through `resume.post_completion(...)` (never while the +// channel lock is held; an executor that has been joined resumes the handle +// inline on the calling thread, as ThreadExecutor does after join()). +// +// Arbitration (one `std::mutex` covers the buffer and both waiter lists) +// A waiter is a heap node (`shared_ptr`) with the state +// {fresh, linked, claimed, cancelled, timed_out, closed, overloaded}. +// `fresh` is the pre-link state (callbacks that settle a fresh waiter make +// the awaiting coroutine skip suspension); `overloaded` is the internal +// result of a refused wait. Pairing a sender with a receiver happens in ONE +// critical section: the waiter is unlinked and claimed and the value is +// moved, so a value is always in exactly one place: the sender's node, the +// buffer, or the receiver's slot. Stop callbacks and timer callbacks take the +// same lock: a still-`linked` waiter is unlinked and settled +// `cancelled`/`timed_out` (a sender keeps its value and gets it back), a +// `claimed` waiter is left alone (a sender succeeded, a receiver already +// holds its value). Each operation is settled exactly once. +// +// Ordering and capacity +// FIFO means per-producer order (items of one producer are received in the +// order they were sent; items of different producers interleave). Waiting +// senders and waiting receivers are served in arrival order. `capacity` and +// `max_waiters` (per direction) must be > 0 (`create` -> invalid_argument). +// A wait that would exceed `max_waiters` returns `overloaded` (a send gets +// its value back). +// +// Close +// `close()` is idempotent and noexcept. Waiting senders complete `closed` +// and get their value back; waiting receivers complete `closed`. Items +// already buffered stay receivable: receivers drain the buffer in FIFO order +// and then get `closed`. `send`/`try_send` on a closed channel return +// `closed` with the value. +// +// Options checks (send/receive with OperationOptions), in this order and +// BEFORE any state change (a send returns its value in `SendFailure`): +// 1. stop already requested -> cancelled +// 2. a deadline is set: it is judged by +// `timers->clock()`; already reached -> timed_out +// no `timers` configured -> invalid_argument +// 3. the fast path (value moved / received) +// 4. a deadline timer is armed (schedule_at failure: overloaded -> +// overloaded, stopped -> cancelled; the value is returned) +// 5. the waiter is linked and the coroutine suspends. +// `TimerEvent::closed` (queue closed or destroyed) settles the wait +// `cancelled`. The system clock is never consulted. +// +// Lifetime and caller errors +// * `send`/`receive` return lazy Tasks; their frames hold +// `shared_from_this()`, so the channel outlives every pending operation. +// * Destroying a Task that is suspended inside a channel operation is a +// caller error (the waiter would be resumed into a destroyed frame). +// * The resume executor and the TimerQueue must outlive the channel and every +// pending operation. +// * Timer callbacks hold only weak references (channel + waiter); a stop or +// timer callback that races with completion finds a settled waiter and +// does nothing. No raw pointer into a coroutine frame is ever captured. +// * A `std::stop_callback` is never constructed or destroyed while the +// channel lock is held, and a timer is never cancelled under the lock. +// * Exceptions: if `T`'s move constructor throws, the exception propagates +// from the operation; the channel's structural invariants (lists, bound) +// are preserved, but the value being moved is then unspecified (strong +// guarantee only for T with a non-throwing move constructor). + +namespace Void::Async +{ + +enum class ChannelError : std::uint8_t { + closed, + empty, + full, + cancelled, + timed_out, + overloaded, + invalid_argument +}; + +// closed -> AsyncErrorCode::closed, cancelled -> cancelled, timed_out -> +// timeout, overloaded/full -> overloaded, empty/invalid_argument -> +// invalid_argument. +[[nodiscard]] inline Void::Result::Error + make_async_error(ChannelError error, std::string message = {}) +{ + AsyncErrorCode code = AsyncErrorCode::invalid_argument; + const char* text = "Invalid async channel argument"; + switch (error) { + case ChannelError::closed: + code = AsyncErrorCode::closed; + text = "Async channel is closed"; + break; + case ChannelError::empty: + code = AsyncErrorCode::invalid_argument; + text = "Async channel is empty"; + break; + case ChannelError::full: + code = AsyncErrorCode::overloaded; + text = "Async channel is full"; + break; + case ChannelError::cancelled: + code = AsyncErrorCode::cancelled; + text = "Async channel operation cancelled"; + break; + case ChannelError::timed_out: + code = AsyncErrorCode::timeout; + text = "Async channel operation deadline expired"; + break; + case ChannelError::overloaded: + code = AsyncErrorCode::overloaded; + text = "Async channel waiter capacity exceeded"; + break; + case ChannelError::invalid_argument: + code = AsyncErrorCode::invalid_argument; + text = "Invalid async channel argument"; + break; + } + if (message.empty()) { + message = text; + } + return make_async_error(code, std::move(message)); +} + +struct ChannelOptions { + std::size_t capacity{1024}; + std::size_t max_waiters{1024}; + // Required only for waits with a deadline; must outlive the channel. + TimerQueue* timers{nullptr}; +}; + +template +struct SendFailure { + ChannelError error; + T value; +}; + +namespace detail +{ + +enum class ChannelWaiterState : std::uint8_t { + fresh, + linked, + claimed, + cancelled, + timed_out, + closed, + overloaded +}; + +// Heap-allocated so stop/timer callbacks can reference it through shared or +// weak ownership instead of a pointer into a coroutine frame. All members +// except `sender` are protected by the owning channel's mutex (the waiter's +// owner may read `value` without the lock only after the state is terminal). +template +struct ChannelWaiter { + explicit ChannelWaiter(bool is_sender) noexcept : sender(is_sender) {} + + const bool sender; + ChannelWaiterState state{ChannelWaiterState::fresh}; + // Sender: the value to deliver. Receiver: the delivered value. + std::optional value{}; + std::coroutine_handle<> handle{}; + TimerHandle timer{}; + typename std::list>::iterator position{}; +}; + +} // namespace detail + +template +class AsyncChannel : public std::enable_shared_from_this> +{ + static_assert(std::is_object_v && std::is_move_constructible_v, + "AsyncChannel requires a move-constructible object type"); + + using Waiter = detail::ChannelWaiter; + using WaiterPtr = std::shared_ptr; + using WaiterList = std::list; + using WaiterState = detail::ChannelWaiterState; + using SendResult = std::expected>; + using ReceiveResult = std::expected; + +public: + // Errors: invalid_argument when capacity == 0 or max_waiters == 0. + [[nodiscard]] static Void::Result::Result> + create(Executor& resume, ChannelOptions options = {}) + { + if (options.capacity == 0) { + return std::unexpected{make_async_error( + AsyncErrorCode::invalid_argument, + "AsyncChannel capacity must be greater than zero")}; + } + if (options.max_waiters == 0) { + return std::unexpected{make_async_error( + AsyncErrorCode::invalid_argument, + "AsyncChannel max_waiters must be greater than zero")}; + } + return std::shared_ptr(new AsyncChannel(resume, options)); + } + + AsyncChannel(const AsyncChannel&) = delete; + AsyncChannel& operator=(const AsyncChannel&) = delete; + AsyncChannel(AsyncChannel&&) = delete; + AsyncChannel& operator=(AsyncChannel&&) = delete; + ~AsyncChannel() = default; + + // Non-blocking send. Errors (the value is returned): closed, full. + [[nodiscard]] std::expected> try_send(T value) + { + WaiterPtr woken; + SendAttempt attempt{}; + { + std::lock_guard lk{mu_}; + attempt = try_send_locked(value, woken); + } + resume_waiter(woken); + switch (attempt) { + case SendAttempt::sent: + return {}; + case SendAttempt::closed: + return std::unexpected{SendFailure{ChannelError::closed, std::move(value)}}; + case SendAttempt::full: + break; + } + return std::unexpected{SendFailure{ChannelError::full, std::move(value)}}; + } + + // Suspends until the value is delivered (to a waiting receiver or the + // buffer). Results: success; or SendFailure with the value returned: + // closed, cancelled, timed_out, overloaded, invalid_argument (see the + // header comment for the check order). + [[nodiscard]] Coro::Task>> + send(T value, OperationOptions options = {}) + { + return send_impl(this->shared_from_this(), std::move(value), std::move(options)); + } + + // Non-blocking receive. Errors: empty, closed (closed AND drained). + [[nodiscard]] std::expected try_receive() + { + std::optional out; + WaiterPtr woken; + ReceiveAttempt attempt{}; + { + std::lock_guard lk{mu_}; + attempt = try_receive_locked(out, woken); + } + resume_waiter(woken); + switch (attempt) { + case ReceiveAttempt::received: + return std::move(*out); + case ReceiveAttempt::closed: + return std::unexpected{ChannelError::closed}; + case ReceiveAttempt::empty: + break; + } + return std::unexpected{ChannelError::empty}; + } + + // Suspends until a value arrives. Errors: closed (closed AND drained), + // cancelled, timed_out, overloaded, invalid_argument. + [[nodiscard]] Coro::Task> + receive(OperationOptions options = {}) + { + return receive_impl(this->shared_from_this(), std::move(options)); + } + + // Idempotent. See the header comment. + void close() noexcept + { + WaiterList senders; + WaiterList receivers; + { + std::lock_guard lk{mu_}; + if (closed_) { + return; + } + closed_ = true; + senders.splice(senders.end(), senders_); + receivers.splice(receivers.end(), receivers_); + for (auto& waiter : senders) { + waiter->state = WaiterState::closed; + } + for (auto& waiter : receivers) { + waiter->state = WaiterState::closed; + } + } + for (auto& waiter : senders) { + resume_waiter(waiter); + } + for (auto& waiter : receivers) { + resume_waiter(waiter); + } + } + + // Number of buffered items. + [[nodiscard]] std::size_t size() const + { + std::lock_guard lk{mu_}; + return buffer_.size(); + } + + [[nodiscard]] bool is_closed() const + { + std::lock_guard lk{mu_}; + return closed_; + } + +private: + enum class SendAttempt : std::uint8_t { sent, closed, full }; + enum class ReceiveAttempt : std::uint8_t { received, closed, empty }; + + AsyncChannel(Executor& resume, const ChannelOptions& options) + : resume_(resume) + , capacity_(options.capacity) + , max_waiters_(options.max_waiters) + , timers_(options.timers) + { + } + + // ── locked primitives (mu_ held) ────────────────────────────────────── + + // Moves from `value` only on success. A waiting receiver implies an empty + // buffer, so a direct hand-off preserves FIFO order. + [[nodiscard]] SendAttempt try_send_locked(T& value, WaiterPtr& woken) + { + if (closed_) { + return SendAttempt::closed; + } + if (!receivers_.empty()) { + WaiterPtr receiver = receivers_.front(); + receiver->value.emplace(std::move(value)); + receivers_.pop_front(); + receiver->state = WaiterState::claimed; + woken = std::move(receiver); + return SendAttempt::sent; + } + if (buffer_.size() < capacity_) { + buffer_.push_back(std::move(value)); + return SendAttempt::sent; + } + return SendAttempt::full; + } + + // A waiting sender implies a full buffer: the freed slot is refilled from + // the first waiting sender, which is claimed (it succeeded). + [[nodiscard]] ReceiveAttempt try_receive_locked(std::optional& out, WaiterPtr& woken) + { + if (!buffer_.empty()) { + out.emplace(std::move(buffer_.front())); + buffer_.pop_front(); + if (!senders_.empty()) { + WaiterPtr sender = senders_.front(); + try { + buffer_.push_back(std::move(*sender->value)); + } catch (...) { + // Best effort: put the received value back so it is not lost. + try { + buffer_.push_front(std::move(*out)); + } catch (...) { + } + throw; + } + senders_.pop_front(); + sender->state = WaiterState::claimed; + woken = std::move(sender); + } + return ReceiveAttempt::received; + } + if (closed_) { + return ReceiveAttempt::closed; + } + return ReceiveAttempt::empty; + } + + void link_locked(WaiterList& list, const WaiterPtr& waiter) + { + waiter->position = list.insert(list.end(), waiter); + waiter->state = WaiterState::linked; + } + + // ── settlement (no lock held) ───────────────────────────────────────── + + // Cancels the waiter's deadline timer and resumes its coroutine through + // the completion lane. The waiter must already be in a terminal state. + void resume_waiter(WaiterPtr& waiter) + { + if (!waiter) { + return; + } + (void)waiter->timer.cancel(); + resume_.post_completion(waiter->handle); + waiter.reset(); + } + + // Stop/timer callback entry point. A `fresh` waiter is only marked (the + // awaiting coroutine will not suspend); a `linked` waiter is unlinked and + // resumed; anything else was already settled and is left alone. + void settle_pending(const WaiterPtr& waiter, WaiterState to) noexcept + { + { + std::lock_guard lk{mu_}; + if (waiter->state == WaiterState::fresh) { + waiter->state = to; + return; + } + if (waiter->state != WaiterState::linked) { + return; + } + (waiter->sender ? senders_ : receivers_).erase(waiter->position); + waiter->state = to; + } + WaiterPtr settled = waiter; + resume_waiter(settled); + } + + // ── option handling ─────────────────────────────────────────────────── + + [[nodiscard]] std::optional precheck(const OperationOptions& options) const + { + if (options.stop.stop_requested()) { + return ChannelError::cancelled; + } + if (options.deadline.has_value()) { + if (timers_ == nullptr) { + return ChannelError::invalid_argument; + } + if (timers_->clock().now() >= *options.deadline) { + return ChannelError::timed_out; + } + } + return std::nullopt; + } + + // Arms the deadline timer while the waiter is still `fresh` (so a failure + // leaves no state behind and a timer that fires early settles the fresh + // waiter without a ticket). The callback holds only weak references. + [[nodiscard]] std::optional + arm_deadline(const WaiterPtr& waiter, Void::Time::MonotonicClock::time_point deadline) + { + auto scheduled = timers_->schedule_at( + deadline, + TimerCallback{[channel = this->weak_from_this(), + target = std::weak_ptr{waiter}](TimerEvent event) noexcept { + const auto chan = channel.lock(); + const auto settled = target.lock(); + if (chan && settled) { + chan->settle_pending( + settled, + event == TimerEvent::expired ? WaiterState::timed_out + : WaiterState::cancelled); + } + }}); + if (!scheduled.has_value()) { + switch (scheduled.error()) { + case AdmissionError::overloaded: + return ChannelError::overloaded; + case AdmissionError::stopped: + return ChannelError::cancelled; + case AdmissionError::deadline_expired: + return ChannelError::timed_out; + case AdmissionError::invalid_argument: + case AdmissionError::self_join: + return ChannelError::invalid_argument; + } + return ChannelError::invalid_argument; + } + bool settled_meanwhile = false; + { + std::lock_guard lk{mu_}; + if (waiter->state == WaiterState::fresh) { + waiter->timer = std::move(*scheduled); + } else { + settled_meanwhile = true; + } + } + if (settled_meanwhile) { + (void)scheduled->cancel(); + } + return std::nullopt; + } + + struct StopFn { + std::weak_ptr channel; + WaiterPtr waiter; + + void operator()() const noexcept + { + // Copy first: once the waiter is settled the resumed frame may + // destroy the stop_callback that owns this object. + const auto chan = channel.lock(); + const WaiterPtr target = waiter; + if (chan) { + chan->settle_pending(target, WaiterState::cancelled); + } + } + }; + + // ── awaiters ────────────────────────────────────────────────────────── + + // Links the waiter (re-running the fast path under the same lock so no + // wake-up can be lost) and suspends. Once the waiter is visible to other + // threads the frame may be resumed and destroyed concurrently, so + // everything after the unlock touches locals only. + struct SendAwaiter { + std::shared_ptr channel; + WaiterPtr waiter; + + [[nodiscard]] bool await_ready() const noexcept { return false; } + + [[nodiscard]] bool await_suspend(std::coroutine_handle<> handle) + { + std::shared_ptr chan = channel; + WaiterPtr self = waiter; + WaiterPtr woken; + bool suspended = false; + try { + std::lock_guard lk{chan->mu_}; + if (self->state == WaiterState::fresh) { + switch (chan->try_send_locked(*self->value, woken)) { + case SendAttempt::sent: + self->state = WaiterState::claimed; + break; + case SendAttempt::closed: + self->state = WaiterState::closed; + break; + case SendAttempt::full: + if (chan->senders_.size() >= chan->max_waiters_) { + self->state = WaiterState::overloaded; + } else { + self->handle = handle; + chan->link_locked(chan->senders_, self); + suspended = true; + } + break; + } + } + } catch (...) { + (void)self->timer.cancel(); + throw; + } + if (suspended) { + return true; + } + (void)self->timer.cancel(); + chan->resume_waiter(woken); + return false; + } + + [[nodiscard]] SendResult await_resume() + { + WaiterState state{}; + { + std::lock_guard lk{channel->mu_}; + state = waiter->state; + } + switch (state) { + case WaiterState::claimed: + return {}; + case WaiterState::closed: + return fail(ChannelError::closed); + case WaiterState::timed_out: + return fail(ChannelError::timed_out); + case WaiterState::overloaded: + return fail(ChannelError::overloaded); + case WaiterState::cancelled: + case WaiterState::fresh: + case WaiterState::linked: + break; + } + return fail(ChannelError::cancelled); + } + + private: + [[nodiscard]] SendResult fail(ChannelError error) + { + return std::unexpected{SendFailure{error, std::move(*waiter->value)}}; + } + }; + + struct ReceiveAwaiter { + std::shared_ptr channel; + WaiterPtr waiter; + + [[nodiscard]] bool await_ready() const noexcept { return false; } + + [[nodiscard]] bool await_suspend(std::coroutine_handle<> handle) + { + std::shared_ptr chan = channel; + WaiterPtr self = waiter; + WaiterPtr woken; + bool suspended = false; + try { + std::lock_guard lk{chan->mu_}; + if (self->state == WaiterState::fresh) { + switch (chan->try_receive_locked(self->value, woken)) { + case ReceiveAttempt::received: + self->state = WaiterState::claimed; + break; + case ReceiveAttempt::closed: + self->state = WaiterState::closed; + break; + case ReceiveAttempt::empty: + if (chan->receivers_.size() >= chan->max_waiters_) { + self->state = WaiterState::overloaded; + } else { + self->handle = handle; + chan->link_locked(chan->receivers_, self); + suspended = true; + } + break; + } + } + } catch (...) { + (void)self->timer.cancel(); + throw; + } + if (suspended) { + return true; + } + (void)self->timer.cancel(); + chan->resume_waiter(woken); + return false; + } + + [[nodiscard]] ReceiveResult await_resume() + { + WaiterState state{}; + { + std::lock_guard lk{channel->mu_}; + state = waiter->state; + } + switch (state) { + case WaiterState::claimed: + return std::move(*waiter->value); + case WaiterState::closed: + return std::unexpected{ChannelError::closed}; + case WaiterState::timed_out: + return std::unexpected{ChannelError::timed_out}; + case WaiterState::overloaded: + return std::unexpected{ChannelError::overloaded}; + case WaiterState::cancelled: + case WaiterState::fresh: + case WaiterState::linked: + break; + } + return std::unexpected{ChannelError::cancelled}; + } + }; + + // ── operations (free-standing coroutines holding the channel) ───────── + + static Coro::Task + send_impl(std::shared_ptr self, T value, OperationOptions options) + { + if (const auto refused = self->precheck(options); refused.has_value()) { + co_return std::unexpected{SendFailure{*refused, std::move(value)}}; + } + { + WaiterPtr woken; + SendAttempt attempt{}; + { + std::lock_guard lk{self->mu_}; + attempt = self->try_send_locked(value, woken); + } + self->resume_waiter(woken); + if (attempt == SendAttempt::sent) { + co_return SendResult{}; + } + if (attempt == SendAttempt::closed) { + co_return std::unexpected{SendFailure{ChannelError::closed, std::move(value)}}; + } + } + + auto waiter = std::make_shared(true); + waiter->value.emplace(std::move(value)); + std::optional> stop_cb; + if (options.stop.stop_possible()) { + stop_cb.emplace(options.stop, StopFn{self->weak_from_this(), waiter}); + } + if (options.deadline.has_value()) { + if (const auto failure = self->arm_deadline(waiter, *options.deadline); + failure.has_value()) { + co_return std::unexpected{SendFailure{*failure, std::move(*waiter->value)}}; + } + } + + SendResult result = co_await SendAwaiter{self, waiter}; + // Waits for a stop callback that is mid-settle (no lock is held here). + stop_cb.reset(); + co_return result; + } + + static Coro::Task + receive_impl(std::shared_ptr self, OperationOptions options) + { + if (const auto refused = self->precheck(options); refused.has_value()) { + co_return std::unexpected{*refused}; + } + { + std::optional out; + WaiterPtr woken; + ReceiveAttempt attempt{}; + { + std::lock_guard lk{self->mu_}; + attempt = self->try_receive_locked(out, woken); + } + self->resume_waiter(woken); + if (attempt == ReceiveAttempt::received) { + co_return ReceiveResult{std::move(*out)}; + } + if (attempt == ReceiveAttempt::closed) { + co_return std::unexpected{ChannelError::closed}; + } + } + + auto waiter = std::make_shared(false); + std::optional> stop_cb; + if (options.stop.stop_possible()) { + stop_cb.emplace(options.stop, StopFn{self->weak_from_this(), waiter}); + } + if (options.deadline.has_value()) { + if (const auto failure = self->arm_deadline(waiter, *options.deadline); + failure.has_value()) { + co_return std::unexpected{*failure}; + } + } + + ReceiveResult result = co_await ReceiveAwaiter{self, waiter}; + stop_cb.reset(); + co_return result; + } + + Executor& resume_; + const std::size_t capacity_; + const std::size_t max_waiters_; + TimerQueue* const timers_; + mutable std::mutex mu_{}; + std::deque buffer_{}; + WaiterList senders_{}; + WaiterList receivers_{}; + bool closed_{false}; +}; + +} // namespace Void::Async diff --git a/include/Void/Async/Executor.hpp b/include/Void/Async/Executor.hpp index e8d6497..ca1d8be 100644 --- a/include/Void/Async/Executor.hpp +++ b/include/Void/Async/Executor.hpp @@ -276,29 +276,41 @@ struct ScheduleAwaiter { // coroutine owns the task; its frame self-destroys on completion. An // exception escaping the task terminates (there is no awaiter to receive // it) — handle errors inside the task. +// +// The wrapper starts suspended and is posted only after its ramp function has +// returned. An eagerly started wrapper that posted itself from its first +// co_await could be resumed and destroyed by an executor worker while the +// spawning thread was still inside the ramp (data race reported by TSan when +// spawning from a non-worker thread onto a multi-worker executor; W11). namespace Detail { struct DetachedTask { struct promise_type { - DetachedTask get_return_object() noexcept { return {}; } - std::suspend_never initial_suspend() noexcept { return {}; } + DetachedTask get_return_object() noexcept + { + return DetachedTask{ + std::coroutine_handle::from_promise(*this)}; + } + std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_void() noexcept {} void unhandled_exception() noexcept { std::terminate(); } }; + + std::coroutine_handle handle{}; }; - inline DetachedTask spawn_impl(Executor& executor, Coro::Task task) + inline DetachedTask spawn_impl(Coro::Task task) { - co_await schedule_on(executor); co_await std::move(task); } } // namespace Detail inline void spawn(Executor& executor, Coro::Task task) { - Detail::spawn_impl(executor, std::move(task)); + Detail::DetachedTask detached = Detail::spawn_impl(std::move(task)); + executor.post(detached.handle); } struct ScheduleStatusAwaiter { diff --git a/include/Void/Async/FuturePool.hpp b/include/Void/Async/FuturePool.hpp new file mode 100644 index 0000000..f1eb213 --- /dev/null +++ b/include/Void/Async/FuturePool.hpp @@ -0,0 +1,131 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +// ── FuturePool ──────────────────────────────────────────────────────────────── +// `std::future` adapter over a started `ThreadExecutor`. +// +// try_submit(f) is reserve-then-transfer: +// 1. one slot of the executor bound is reserved (`overloaded` / `stopped` +// are returned WITHOUT touching `f`: a rejected callable is never moved); +// 2. only after the reservation succeeded is `f` moved into a +// `std::packaged_task` owned by a self-destroying coroutine frame; +// 3. the frame is committed to the executor's normal lane. +// The reservation is released if any step throws (the exception propagates). +// Exceptions thrown by `f` are stored in the returned future. The executor +// bound counts queued, running and reserved work, so a running submission +// keeps its slot until `f` has returned. +// +// The executor must outlive the pool and must be started (or joined by the +// owner afterwards): a submission is resumed by a worker, or inline once the +// executor has been joined. + +namespace Void::Async +{ + +namespace detail +{ + +// Fire-and-forget coroutine frame: created suspended, destroyed after it ran. +struct FutureJob { + struct promise_type { + FutureJob get_return_object() noexcept + { + return FutureJob{std::coroutine_handle::from_promise(*this)}; + } + std::suspend_always initial_suspend() noexcept { return {}; } + std::suspend_never final_suspend() noexcept { return {}; } + void return_void() noexcept {} + // packaged_task stores the callable's exception in the future, so + // nothing escapes the frame. + void unhandled_exception() noexcept { std::terminate(); } + }; + + std::coroutine_handle handle{}; +}; + +template +FutureJob run_future_job(std::packaged_task task) +{ + task(); + co_return; +} + +// Releases a reservation unless dismissed. +class ReservationGuard +{ +public: + explicit ReservationGuard(ThreadExecutor& executor) noexcept + : executor_(&executor) + { + } + + ReservationGuard(const ReservationGuard&) = delete; + ReservationGuard& operator=(const ReservationGuard&) = delete; + + ~ReservationGuard() + { + if (executor_ != nullptr) { + executor_->release_reserved(); + } + } + + void dismiss() noexcept { executor_ = nullptr; } + +private: + ThreadExecutor* executor_; +}; + +} // namespace detail + +class FuturePool +{ +public: + explicit FuturePool(ThreadExecutor& executor) noexcept + : executor_(&executor) + { + } + + // Errors: overloaded (admitted() >= max_admitted), stopped (executor + // closed). On an error `f` is untouched. Throws only on allocation + // failure (the reservation is released first). + template + [[nodiscard]] std::expected>, AdmissionError> + try_submit(F&& f) + { + using R = std::invoke_result_t; + + if (auto reserved = executor_->try_reserve_slot(); !reserved.has_value()) { + return std::unexpected{reserved.error()}; + } + detail::ReservationGuard guard{*executor_}; + + std::packaged_task task{std::forward(f)}; + std::future future = task.get_future(); + detail::FutureJob job = detail::run_future_job(std::move(task)); + try { + executor_->commit_reserved(job.handle); + } catch (...) { + // The reservation is still held (guard releases it); the frame was + // never queued. + job.handle.destroy(); + throw; + } + guard.dismiss(); + return future; + } + +private: + ThreadExecutor* executor_; +}; + +} // namespace Void::Async diff --git a/include/Void/Async/ParallelFor.hpp b/include/Void/Async/ParallelFor.hpp index be96352..6d291d3 100644 --- a/include/Void/Async/ParallelFor.hpp +++ b/include/Void/Async/ParallelFor.hpp @@ -1,7 +1,20 @@ #pragma once #include +#include +#include #include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include #include namespace Void::Concurrency @@ -9,6 +22,10 @@ namespace Void::Concurrency // Submit one task per index in [first, last) to pool; block until all done. // Exceptions from tasks propagate via std::future::get() to the caller. + // + // Every submitted future is waited for before the first exception is + // rethrown (a throwing task, or a failing submit, never leaves other tasks + // running against the caller's stack). template F> void parallel_for(I first, I last, F&& f, ThreadPool& pool) { @@ -17,11 +34,25 @@ namespace Void::Concurrency } std::vector> futures; futures.reserve(static_cast(last - first)); - for (auto i = first; i < last; ++i) { - futures.push_back(pool.submit([f, i] { f(i); })); + std::exception_ptr first_error; + try { + for (auto i = first; i < last; ++i) { + futures.push_back(pool.submit([f, i] { f(i); })); + } + } catch (...) { + first_error = std::current_exception(); } for (auto& fut : futures) { - fut.get(); + try { + fut.get(); + } catch (...) { + if (!first_error) { + first_error = std::current_exception(); + } + } + } + if (first_error) { + std::rethrow_exception(first_error); } } @@ -34,4 +65,272 @@ namespace Void::Concurrency parallel_for(first, last, std::forward(f), pool); } + // ── Bounded, chunked parallel_for ──────────────────────────────────────── + + struct ParallelForOptions { + // Indices per chunk; zero is invalid. + std::size_t grain{1}; + // Maximum chunks running at once (the calling thread counts when it + // runs chunks inline); zero means the pool's thread count. + std::size_t max_concurrency{0}; + // No new chunk starts once stop is requested. + std::stop_token stop{}; + // No new chunk starts after the first failed chunk. When false every + // chunk runs and all failures are counted. + bool stop_on_error{true}; + }; + + struct ParallelForError { + enum class Kind : std::uint8_t { + invalid_argument, + rejected, // reserved: not produced in this release + stopped, + failed + } kind; + std::size_t chunks_total{0}; + std::size_t chunks_started{0}; + std::size_t chunks_failed{0}; + std::optional first_failed_chunk{}; + std::exception_ptr first_exception{}; + }; + + namespace detail + { + // Shared between the caller and every runner. Runners hold it through + // a shared_ptr, so a runner that starts after the caller stopped + // claiming chunks (or that the pool never started in time) never + // touches freed state. + template struct PForState { + template + PForState(G&& fn_in, Index first_in, std::uintmax_t count_in, + std::uintmax_t grain_in, std::size_t chunks, + std::stop_token stop_in, bool stop_on_error_in) + : fn(std::forward(fn_in)), first(first_in), + count(count_in), grain(grain_in), chunks_total(chunks), + stop(std::move(stop_in)), stop_on_error(stop_on_error_in) + { + } + + const Fn fn; + const Index first; + const std::uintmax_t count; + const std::uintmax_t grain; + const std::size_t chunks_total; + const std::stop_token stop; + const bool stop_on_error; + + std::atomic next_chunk{0}; + std::atomic started{0}; + std::atomic failed_flag{false}; + std::atomic aborted{false}; + + std::mutex error_mu{}; + std::size_t failed{0}; + std::optional first_failed{}; + std::exception_ptr first_exception{}; + + [[nodiscard]] bool should_stop() const noexcept + { + return aborted.load(std::memory_order_acquire) || + stop.stop_requested() || + (stop_on_error && + failed_flag.load(std::memory_order_acquire)); + } + + void record_failure(std::size_t chunk, std::exception_ptr error) + { + std::lock_guard lk{error_mu}; + ++failed; + if (!first_failed.has_value() || chunk < *first_failed) { + first_failed = chunk; + first_exception = std::move(error); + } + failed_flag.store(true, std::memory_order_release); + } + + // Claims and runs chunks until the range is exhausted, a stop + // is requested or (stop_on_error) a chunk failed. Never throws: + // every chunk failure is recorded. + void run_chunks() noexcept + { + using U = std::make_unsigned_t, unsigned char, Index>>; + for (;;) { + if (should_stop()) { + return; + } + const std::size_t chunk = + next_chunk.fetch_add(1, std::memory_order_acq_rel); + if (chunk >= chunks_total) { + return; + } + // A stop that arrived between the check and the claim: + // the claimed chunk is abandoned unstarted. + if (should_stop()) { + return; + } + started.fetch_add(1, std::memory_order_relaxed); + const std::uintmax_t begin = + static_cast(chunk) * grain; + const std::uintmax_t length = + std::min(grain, count - begin); + try { + for (std::uintmax_t k = 0; k < length; ++k) { + const Index i = static_cast( + static_cast(static_cast(first) + + static_cast(begin + k))); + fn(i); + } + } catch (...) { + record_failure(chunk, std::current_exception()); + } + } + } + }; + + // Waits for every future on every exit path (including an exception + // thrown while submitting): a runner may still call `f`, which can + // capture the caller's stack by reference. + class RunnerJoin + { + public: + + explicit RunnerJoin(std::vector>& futures) + : futures_(futures) + { + } + + RunnerJoin(const RunnerJoin&) = delete; + RunnerJoin& operator=(const RunnerJoin&) = delete; + + ~RunnerJoin() { join(); } + + void join() noexcept + { + for (auto& fut : futures_) { + if (fut.valid()) { + fut.wait(); + } + } + } + + private: + + std::vector>& futures_; + }; + } // namespace detail + + // Bounded, chunked parallel_for over [first, last). + // + // The range is split into chunks of `options.grain` indices. At most + // `max_concurrency` chunks run at once (0 = pool.thread_count(); the + // caller counts when it runs chunks inline). Runners are submitted with + // try_submit; when the pool rejects a runner (full or stopped) the CALLING + // thread runs chunks itself (no further runner is submitted). The caller + // waits for EVERY submitted runner, including runners that never started. + // + // Results: success when every chunk ran (also for first >= last); + // otherwise a ParallelForError with precedence invalid_argument (grain == + // 0) > failed (a chunk threw; the lowest-indexed failed chunk is + // reported) > stopped (stop requested before every chunk started). + // `Kind::rejected` is not produced in this release. With `stop_on_error` + // no new chunk starts after the first failure (chunks already running + // finish). Chunk boundaries and the range arithmetic use the unsigned type + // of `I`, so the full range of `I` is safe. + // + // `f` is copied once into shared state and invoked concurrently through a + // const reference, so it must be safe to call concurrently (as with the + // legacy overload). Calling this from a worker of the same `pool` is + // unsupported (the caller would wait for runners that need its thread). + template F> + [[nodiscard]] std::expected + parallel_for(I first, I last, F&& f, ThreadPool& pool, + ParallelForOptions options) + { + using Fn = std::decay_t; + using U = std::make_unsigned_t< + std::conditional_t, unsigned char, I>>; + + if (options.grain == 0) { + return std::unexpected{ParallelForError{ + ParallelForError::Kind::invalid_argument}}; + } + if (first >= last) { + return {}; + } + + const std::uintmax_t count = static_cast( + static_cast(static_cast(last) - static_cast(first))); + const std::uintmax_t grain = options.grain; + const std::uintmax_t chunk_count = + count / grain + (count % grain != 0 ? 1 : 0); + if (chunk_count > std::numeric_limits::max()) { + return std::unexpected{ParallelForError{ + ParallelForError::Kind::invalid_argument}}; + } + const std::size_t chunks_total = static_cast(chunk_count); + + std::size_t concurrency = options.max_concurrency != 0 + ? options.max_concurrency + : pool.thread_count(); + concurrency = std::max(concurrency, 1); + const std::size_t runner_count = std::min(concurrency, chunks_total); + + auto state = std::make_shared>( + std::forward(f), first, count, grain, chunks_total, options.stop, + options.stop_on_error); + + std::vector> futures; + futures.reserve(runner_count); + bool run_inline = false; + if (!options.stop.stop_requested()) { + // Declared after `futures`: waits for every submitted runner on + // every exit path, including an exception while submitting. + detail::RunnerJoin join{futures}; + try { + for (std::size_t r = 0; r < runner_count; ++r) { + // The runner moves its reference out of the capture and + // drops it before its future becomes ready, so the caller + // always releases the last reference: the shared state + // (copied F, stored exception) is never destroyed on a + // pool worker after parallel_for has returned. + auto submitted = pool.try_submit( + [runner_state = state]() mutable { + auto local = std::move(runner_state); + local->run_chunks(); + }); + if (!submitted.has_value()) { + run_inline = true; + break; + } + futures.push_back(std::move(*submitted)); + } + if (run_inline) { + // The pool is full or stopped: this thread is one more + // runner (fewer than runner_count runners were submitted, + // so the total stays within the bound). + state->run_chunks(); + } + } catch (...) { + state->aborted.store(true, std::memory_order_release); + throw; + } + } + + const std::size_t started = + state->started.load(std::memory_order_acquire); + std::lock_guard lk{state->error_mu}; + if (state->failed > 0) { + return std::unexpected{ParallelForError{ + ParallelForError::Kind::failed, chunks_total, started, + state->failed, state->first_failed, state->first_exception}}; + } + if (started < chunks_total) { + return std::unexpected{ParallelForError{ + ParallelForError::Kind::stopped, chunks_total, started, 0, + std::nullopt, nullptr}}; + } + return {}; + } + } // namespace Void::Concurrency diff --git a/include/Void/Async/ThreadExecutor.hpp b/include/Void/Async/ThreadExecutor.hpp new file mode 100644 index 0000000..803c36d --- /dev/null +++ b/include/Void/Async/ThreadExecutor.hpp @@ -0,0 +1,604 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ── ThreadExecutor ──────────────────────────────────────────────────────────── +// A thread-backed `Executor` with a bounded normal lane and a reserved, +// prioritized completion lane (C-03/C-04). +// +// Lifecycle +// create() builds the object and starts NO thread. Admission before start() +// queues normally; nothing runs until start() succeeds. +// start() once. `before_worker_start(i)` (a fault-injection hook, called on +// the starting thread with no lock held) and every `std::thread` +// construction share ONE failure path: workers that were already +// started are told to exit WITHOUT dequeuing anything and are +// joined, start() returns the error and may be retried. start() +// after a successful start, or after close()/join(), returns +// `invalid_argument`. +// close() normal admission (`try_post`, `try_reserve_slot`) returns +// `stopped`; a legacy `post()` is redirected onto the completion +// lane (counted); `post_completion` keeps working. Reservations +// taken before close() stay binding. +// join() close() + drain BOTH lanes until they are empty with nothing +// running and no reservation outstanding, then joins the worker +// threads. Safe to call repeatedly and concurrently (later callers +// wait for the first join to finish). On an executor thread it +// returns `AdmissionError::self_join`. When no worker is running +// (never started, or start() failed) join() drains both lanes +// INLINE on the caller under `ExecutorThreadGuard` (counted as +// `inline_after_join`) and never waits for workers; it still waits +// for an outstanding reservation, which another thread must commit +// or release. +// after join(): `post` / `post_completion` / `commit_reserved` resume the +// handle inline on the caller (counted `inline_after_join`); +// a handle is never dropped. `try_post` / `try_reserve_slot` +// return `stopped`. The switch to inline mode happens under the +// executor mutex in the same critical section that observes +// quiescence, so no handle can be stranded between the two modes. +// ~ThreadExecutor without a prior join() is close() + join(). Destroying the +// executor on one of its own executor threads (a worker, or a +// thread currently resuming a handle inline) prints a diagnostic +// to stderr and calls std::terminate. +// +// Bound +// `admitted()` = queued + running (normal lane) + reserved. `try_post` and +// `try_reserve_slot` return `overloaded` once `admitted() >= max_admitted`. +// A slot is released only after the resumed handle returns. A reservation +// counts in the bound until it is committed or released. Legacy `post()` +// never rejects (it is counted and may exceed the bound). The completion +// lane is not bounded and not counted in `admitted()`. +// +// Drain policy +// There is NO drain cap (C-03 forbids abandoning a frame). A handle that +// keeps re-posting itself prevents join() from returning; that is a caller +// error. A handle must not let an exception escape `resume()` (the worker +// would std::terminate). A reservation that is never committed or released +// prevents join() from returning (caller error). +// +// Snapshots: `idle()`, `admitted()` and `stats()` are point-in-time snapshots. +// `has_background_workers()` is the constant `true` (the design intent is a +// threaded executor; start() must have succeeded for work to make progress). + +namespace Void::Async +{ + +struct ThreadExecutorOptions { + // Number of worker threads; zero is rejected by create(). + std::size_t workers{1}; + // Bound on queued + running normal-lane work (+ reservations); >= 1. + std::size_t max_admitted{4096}; + // Called once per worker, on the starting thread with no lock held, before + // that worker's std::thread is created. An error (or a thrown exception) + // aborts start() through the shared failure path. + std::function(std::size_t)> before_worker_start{}; +}; + +struct ThreadExecutorStats { + std::size_t queued{0}; // normal lane, not yet running + std::size_t running{0}; // handles being resumed now (both lanes) + std::size_t completion_queued{0}; // completion lane, not yet running + std::uint64_t rejected{0}; // try_post / try_reserve_slot -> overloaded + std::uint64_t legacy_posts{0}; // every post() call + std::uint64_t inline_after_join{0}; // handles resumed inline on a caller +}; + +class ThreadExecutor final : public Executor +{ +public: + // Errors: invalid_argument when workers == 0 or max_admitted == 0. + // Starts no thread. + [[nodiscard]] static Void::Result::Result> + create(ThreadExecutorOptions options = {}) + { + if (options.workers == 0) { + return std::unexpected{make_async_error( + AsyncErrorCode::invalid_argument, + "ThreadExecutor workers must be greater than zero")}; + } + if (options.max_admitted == 0) { + return std::unexpected{make_async_error( + AsyncErrorCode::invalid_argument, + "ThreadExecutor max_admitted must be greater than zero")}; + } + return std::unique_ptr(new ThreadExecutor(std::move(options))); + } + + ThreadExecutor(const ThreadExecutor&) = delete; + ThreadExecutor& operator=(const ThreadExecutor&) = delete; + ThreadExecutor(ThreadExecutor&&) = delete; + ThreadExecutor& operator=(ThreadExecutor&&) = delete; + + ~ThreadExecutor() override + { + if (is_executor_thread()) { + std::fputs( + "Void::Async::ThreadExecutor destroyed on its own executor thread\n", + stderr); + std::terminate(); + } + (void)join(); + } + + // Starts the workers. Errors: invalid_argument (after close(), join() or a + // successful start()), the hook's error, or backend_error (with the + // system code when a std::system_error was caught) when a thread could not + // be created. After an error no thread is left running and start() may be + // retried. + [[nodiscard]] Void::Result::Result start() + { + { + std::lock_guard lk{mu_}; + if (closed_ || phase_ != Phase::created) { + return std::unexpected{make_async_error( + AsyncErrorCode::invalid_argument, + "ThreadExecutor::start after start, close or join")}; + } + phase_ = Phase::starting; + } + + std::optional failure; + try { + workers_.reserve(options_.workers); + for (std::size_t i = 0; i < options_.workers; ++i) { + if (options_.before_worker_start) { + auto hook = options_.before_worker_start(i); + if (!hook.has_value()) { + failure = std::move(hook.error()); + break; + } + } + workers_.emplace_back([this] { worker_loop(); }); + } + } catch (const std::system_error& e) { + failure = Void::Result::Error{ + Void::Result::ErrorKind::internal, + std::string{"ThreadExecutor worker start failed: "} + e.what(), + Void::Result::ErrorCode{ + Void::Result::kAsyncErrorDomain, + static_cast(AsyncErrorCode::backend_error)}, + e.code()}; + } catch (const std::exception& e) { + failure = make_async_error( + AsyncErrorCode::backend_error, + std::string{"ThreadExecutor worker start failed: "} + e.what()); + } catch (...) { + failure = make_async_error( + AsyncErrorCode::backend_error, + "ThreadExecutor worker start failed: unknown exception"); + } + + if (failure.has_value()) { + { + std::lock_guard lk{mu_}; + abort_start_ = true; + } + work_cv_.notify_all(); + for (auto& worker : workers_) { + worker.join(); + } + workers_.clear(); + { + std::lock_guard lk{mu_}; + abort_start_ = false; + phase_ = Phase::created; + } + state_cv_.notify_all(); + return std::unexpected{std::move(*failure)}; + } + + { + std::lock_guard lk{mu_}; + phase_ = Phase::running; + } + work_cv_.notify_all(); + state_cv_.notify_all(); + return {}; + } + + // Legacy admission: never rejects and never drops the handle. Counted in + // `legacy_posts`; may exceed the bound. After close() the handle goes to + // the completion lane; after join() it is resumed inline on the caller. + void post(std::coroutine_handle<> handle) override + { + if (!handle) { + return; + } + bool run_inline = false; + { + std::lock_guard lk{mu_}; + if (inline_mode_) { + ++legacy_posts_; + ++inline_after_join_; + run_inline = true; + } else { + if (closed_) { + completion_.push_back(handle); + } else { + normal_.push_back(handle); + } + ++legacy_posts_; + } + } + if (run_inline) { + resume_inline(handle); + } else { + wake_one(); + } + } + + // Bounded admission. Errors: invalid_argument (empty handle), stopped + // (after close()), overloaded (admitted() >= max_admitted). + [[nodiscard]] std::expected + try_post(std::coroutine_handle<> handle) override + { + if (!handle) { + return std::unexpected{AdmissionError::invalid_argument}; + } + { + std::lock_guard lk{mu_}; + if (closed_) { + return std::unexpected{AdmissionError::stopped}; + } + if (admitted_locked() >= options_.max_admitted) { + ++rejected_; + return std::unexpected{AdmissionError::overloaded}; + } + normal_.push_back(handle); + } + wake_one(); + return {}; + } + + // Reserved lane: never rejected, prioritized over the normal lane and + // drained after close(). After join() the handle is resumed inline. + void post_completion(std::coroutine_handle<> handle) override + { + if (!handle) { + return; + } + bool run_inline = false; + { + std::lock_guard lk{mu_}; + if (inline_mode_) { + ++inline_after_join_; + run_inline = true; + } else { + completion_.push_back(handle); + } + } + if (run_inline) { + resume_inline(handle); + } else { + wake_one(); + } + } + + [[nodiscard]] bool supports_reservation() const noexcept override { return true; } + + // Reserves one slot of the bound. Errors: stopped (after close()), + // overloaded (admitted() >= max_admitted). A reservation must be answered + // by commit_reserved() or release_reserved(). + [[nodiscard]] std::expected try_reserve_slot() override + { + std::lock_guard lk{mu_}; + if (closed_) { + return std::unexpected{AdmissionError::stopped}; + } + if (admitted_locked() >= options_.max_admitted) { + ++rejected_; + return std::unexpected{AdmissionError::overloaded}; + } + ++reserved_; + return {}; + } + + // Turns a reservation into a queued handle. Binding even after close(). + // If enqueuing throws (allocation failure) the reservation is still held + // and the caller must release_reserved() it. An empty handle releases the + // reservation. + void commit_reserved(std::coroutine_handle<> handle) override + { + if (!handle) { + release_reserved(); + return; + } + bool run_inline = false; + { + std::lock_guard lk{mu_}; + if (inline_mode_) { + if (reserved_ > 0) { + --reserved_; + } + ++inline_after_join_; + run_inline = true; + } else { + normal_.push_back(handle); + if (reserved_ > 0) { + --reserved_; + } + } + } + if (run_inline) { + resume_inline(handle); + } else { + wake_one(); + } + } + + void release_reserved() noexcept override + { + { + std::lock_guard lk{mu_}; + if (reserved_ > 0) { + --reserved_; + } + } + state_cv_.notify_all(); + } + + [[nodiscard]] bool has_background_workers() const noexcept override { return true; } + + // Closes normal admission (see the class comment). Idempotent. + void close() noexcept + { + { + std::lock_guard lk{mu_}; + closed_ = true; + } + work_cv_.notify_all(); + state_cv_.notify_all(); + } + + // close() + drain + join (see the class comment). Errors: self_join on an + // executor thread. + [[nodiscard]] Void::Result::Result join() + { + if (is_executor_thread()) { + return std::unexpected{make_async_error( + AdmissionError::self_join, + "ThreadExecutor::join called from an executor thread")}; + } + + std::unique_lock lk{mu_}; + closed_ = true; + for (;;) { + if (phase_ == Phase::joined) { + return {}; + } + if (phase_ == Phase::starting || phase_ == Phase::joining) { + state_cv_.wait(lk, [this] { + return phase_ != Phase::starting && phase_ != Phase::joining; + }); + continue; + } + break; + } + + if (phase_ == Phase::running) { + phase_ = Phase::joining; + work_cv_.notify_all(); + state_cv_.wait(lk, [this] { return quiescent_locked(); }); + // Same critical section as the quiescence observation: from here + // every admission resumes inline on its caller. + inline_mode_ = true; + std::vector threads = std::move(workers_); + workers_.clear(); + lk.unlock(); + work_cv_.notify_all(); + for (auto& worker : threads) { + worker.join(); + } + lk.lock(); + phase_ = Phase::joined; + lk.unlock(); + state_cv_.notify_all(); + return {}; + } + + // Phase::created: no worker exists. The joiner is the worker. + phase_ = Phase::joining; + for (;;) { + if (!completion_.empty() || !normal_.empty()) { + const bool from_completion = !completion_.empty(); + std::coroutine_handle<> handle; + if (from_completion) { + handle = completion_.front(); + completion_.pop_front(); + } else { + handle = normal_.front(); + normal_.pop_front(); + } + ++inline_after_join_; + run_locked(lk, handle, from_completion); + continue; + } + if (reserved_ == 0 && running_normal_ == 0 && running_completion_ == 0) { + break; + } + state_cv_.wait(lk, [this] { + return !completion_.empty() || !normal_.empty() || + (reserved_ == 0 && running_normal_ == 0 && + running_completion_ == 0); + }); + } + inline_mode_ = true; + phase_ = Phase::joined; + lk.unlock(); + state_cv_.notify_all(); + return {}; + } + + // True when both lanes are empty and nothing is running (a snapshot). + [[nodiscard]] bool idle() const noexcept + { + std::lock_guard lk{mu_}; + return normal_.empty() && completion_.empty() && running_normal_ == 0 && + running_completion_ == 0; + } + + // queued + running (normal lane) + reserved (a snapshot). + [[nodiscard]] std::size_t admitted() const noexcept + { + std::lock_guard lk{mu_}; + return admitted_locked(); + } + + [[nodiscard]] ThreadExecutorStats stats() const noexcept + { + std::lock_guard lk{mu_}; + return ThreadExecutorStats{ + normal_.size(), + running_normal_ + running_completion_, + completion_.size(), + rejected_, + legacy_posts_, + inline_after_join_}; + } + +private: + enum class Phase : std::uint8_t { + created, // no worker; start() allowed + starting, // start() in progress + running, // workers live + joining, // join() in progress + joined // workers gone; inline mode + }; + + explicit ThreadExecutor(ThreadExecutorOptions options) + : options_(std::move(options)) + { + } + + [[nodiscard]] std::size_t admitted_locked() const noexcept + { + return normal_.size() + running_normal_ + reserved_; + } + + [[nodiscard]] bool quiescent_locked() const noexcept + { + return normal_.empty() && completion_.empty() && running_normal_ == 0 && + running_completion_ == 0 && reserved_ == 0; + } + + void wake_one() + { + work_cv_.notify_one(); + // A joiner without workers drains the lanes itself and waits for them + // on the state condition variable. + state_cv_.notify_all(); + } + + void resume_inline(std::coroutine_handle<> handle) + { + detail::ExecutorThreadGuard guard{this}; + handle.resume(); + } + + // Resumes `handle` (already popped and not yet counted as running) with + // the lock released, then re-acquires it and releases the slot. The slot is + // released only after the handle returned (or threw). + void run_locked(std::unique_lock& lk, + std::coroutine_handle<> handle, + bool from_completion) + { + if (from_completion) { + ++running_completion_; + } else { + ++running_normal_; + } + lk.unlock(); + try { + detail::ExecutorThreadGuard guard{this}; + handle.resume(); + } catch (...) { + lk.lock(); + finish_locked(from_completion); + throw; + } + lk.lock(); + finish_locked(from_completion); + } + + void finish_locked(bool from_completion) noexcept + { + if (from_completion) { + --running_completion_; + } else { + --running_normal_; + } + if (phase_ == Phase::joining) { + state_cv_.notify_all(); + } + } + + void worker_loop() + { + std::unique_lock lk{mu_}; + for (;;) { + work_cv_.wait(lk, [this] { + if (abort_start_ || inline_mode_) { + return true; + } + if (phase_ != Phase::running && phase_ != Phase::joining) { + return false; + } + return !completion_.empty() || !normal_.empty(); + }); + if (abort_start_ || inline_mode_) { + return; + } + const bool from_completion = !completion_.empty(); + std::coroutine_handle<> handle; + if (from_completion) { + handle = completion_.front(); + completion_.pop_front(); + } else { + handle = normal_.front(); + normal_.pop_front(); + } + run_locked(lk, handle, from_completion); + } + } + + ThreadExecutorOptions options_; + mutable std::mutex mu_{}; + std::condition_variable work_cv_{}; // wakes workers + std::condition_variable state_cv_{}; // wakes start()/join() waiters + std::deque> normal_{}; + std::deque> completion_{}; + std::vector workers_{}; + std::size_t running_normal_{0}; + std::size_t running_completion_{0}; + std::size_t reserved_{0}; + std::uint64_t rejected_{0}; + std::uint64_t legacy_posts_{0}; + std::uint64_t inline_after_join_{0}; + Phase phase_{Phase::created}; + bool closed_{false}; + bool inline_mode_{false}; + bool abort_start_{false}; +}; + +} // namespace Void::Async diff --git a/tests/standalone/Async/AsyncChannel.cpp b/tests/standalone/Async/AsyncChannel.cpp new file mode 100644 index 0000000..c0074b2 --- /dev/null +++ b/tests/standalone/Async/AsyncChannel.cpp @@ -0,0 +1,1189 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Assertions run on the test thread only (the assertion context is +// thread_local); coroutines resumed by pool workers write into probes or +// atomics. Race loops count violations and assert once after the loop (the +// runner keeps only the first 1,000 assertions per test). + +namespace +{ + +using namespace Void::Async; +using namespace std::chrono_literals; +using Chan = AsyncChannel; +using TimePoint = Void::Time::MonotonicClock::time_point; +using Void::Time::ManualClock; + +using SendResult = std::expected>; +using ReceiveResult = std::expected; + +struct SendProbe { + std::optional result{}; + int resumes{0}; + + [[nodiscard]] bool succeeded() const { return result.has_value() && result->has_value(); } + + [[nodiscard]] std::optional error() const + { + if (!result.has_value() || result->has_value()) { + return std::nullopt; + } + return result->error().error; + } + + [[nodiscard]] std::optional returned_value() const + { + if (!result.has_value() || result->has_value()) { + return std::nullopt; + } + return result->error().value; + } +}; + +struct ReceiveProbe { + std::optional result{}; + int resumes{0}; + + [[nodiscard]] bool received() const { return result.has_value() && result->has_value(); } + + [[nodiscard]] std::optional value() const + { + if (!received()) { + return std::nullopt; + } + return **result; + } + + [[nodiscard]] std::optional error() const + { + if (!result.has_value() || result->has_value()) { + return std::nullopt; + } + return result->error(); + } +}; + +Void::Coro::Task run_send(std::shared_ptr channel, + int value, + OperationOptions options, + SendProbe* probe) +{ + auto result = co_await channel->send(value, std::move(options)); + probe->result = std::move(result); + ++probe->resumes; +} + +Void::Coro::Task run_receive(std::shared_ptr channel, + OperationOptions options, + ReceiveProbe* probe) +{ + auto result = co_await channel->receive(std::move(options)); + probe->result = std::move(result); + ++probe->resumes; +} + +void start(Void::Coro::Task& task) +{ + task.handle().resume(); +} + +std::shared_ptr make_channel(Executor& exec, ChannelOptions options = {}) +{ + auto created = Chan::create(exec, options); + Void::Testing::require(created.has_value()); + return std::move(*created); +} + +std::unique_ptr make_timers(Executor& exec, + const Void::Time::MonotonicClock& clock, + std::size_t max_timers = 64) +{ + auto created = TimerQueue::create(exec, clock, TimerQueueOptions{.max_timers = max_timers}); + Void::Testing::require(created.has_value()); + return std::move(*created); +} + +void advance_clock(ManualClock& clock, std::chrono::nanoseconds delta) +{ + Void::Testing::require(clock.advance(delta).has_value()); +} + +std::optional async_code(const Void::Result::Error& error) +{ + if (error.code().domain != Void::Result::kAsyncErrorDomain) { + return std::nullopt; + } + return static_cast(error.code().value); +} + + +// Starts `task` on `exec` through a lazily created detached frame. The +// library's spawn() is deliberately not used here: ThreadSanitizer reports a +// data race in Executor.hpp's spawn_impl (lines 292/296) when spawn() is called +// from a thread other than the executor's workers onto a multi-worker +// executor. That is independent of ThreadExecutor and is escalated to the root. +struct DetachedRun { + struct promise_type { + DetachedRun get_return_object() noexcept + { + return DetachedRun{std::coroutine_handle::from_promise(*this)}; + } + std::suspend_always initial_suspend() noexcept { return {}; } + std::suspend_never final_suspend() noexcept { return {}; } + void return_void() noexcept {} + void unhandled_exception() noexcept { std::terminate(); } + }; + + std::coroutine_handle handle{}; +}; + +DetachedRun run_detached(Void::Coro::Task task) +{ + co_await std::move(task); +} + +void launch(Executor& exec, Void::Coro::Task task) +{ + exec.post(run_detached(std::move(task)).handle); +} + +template +bool wait_until(Pred pred, std::chrono::milliseconds timeout = 10000ms) +{ + const auto end = std::chrono::steady_clock::now() + timeout; + while (!pred()) { + if (std::chrono::steady_clock::now() >= end) { + return false; + } + std::this_thread::yield(); + } + return true; +} + +} // namespace + +Void::Testing::Test channel_zero_capacity_invalid() +{ + ManualExecutor exec; + const auto zero_capacity = Chan::create(exec, ChannelOptions{.capacity = 0}); + Void::Testing::require(!zero_capacity.has_value()); + Void::Testing::expect(async_code(zero_capacity.error()) == AsyncErrorCode::invalid_argument); + Void::Testing::expect(zero_capacity.error().kind() == Void::Result::ErrorKind::invalid_argument); + + const auto zero_waiters = Chan::create(exec, ChannelOptions{.max_waiters = 0}); + Void::Testing::require(!zero_waiters.has_value()); + Void::Testing::expect(async_code(zero_waiters.error()) == AsyncErrorCode::invalid_argument); + + const auto ok = Chan::create(exec, ChannelOptions{.capacity = 1, .max_waiters = 1}); + Void::Testing::require(ok.has_value()); + Void::Testing::expect_eq((*ok)->size(), std::size_t{0}); + Void::Testing::expect(!(*ok)->is_closed()); + + // ChannelError maps into the async error domain via the existing codes. + Void::Testing::expect(async_code(make_async_error(ChannelError::closed)) == AsyncErrorCode::closed); + Void::Testing::expect(make_async_error(ChannelError::closed).kind() == + Void::Result::ErrorKind::cancelled); + Void::Testing::expect(async_code(make_async_error(ChannelError::cancelled)) == + AsyncErrorCode::cancelled); + Void::Testing::expect(async_code(make_async_error(ChannelError::timed_out)) == + AsyncErrorCode::timeout); + Void::Testing::expect(async_code(make_async_error(ChannelError::overloaded)) == + AsyncErrorCode::overloaded); + Void::Testing::expect(async_code(make_async_error(ChannelError::full)) == + AsyncErrorCode::overloaded); + Void::Testing::expect(async_code(make_async_error(ChannelError::empty)) == + AsyncErrorCode::invalid_argument); + Void::Testing::expect(async_code(make_async_error(ChannelError::invalid_argument, "custom")) == + AsyncErrorCode::invalid_argument); + Void::Testing::expect_eq(make_async_error(ChannelError::invalid_argument, "custom").message(), + std::string{"custom"}); +} + +Void::Testing::Test channel_try_send_full_returns_value() +{ + ManualExecutor exec; + auto string_channel = AsyncChannel::create(exec, ChannelOptions{.capacity = 2}); + Void::Testing::require(string_channel.has_value()); + auto& channel = **string_channel; + + Void::Testing::require(channel.try_send("a").has_value()); + Void::Testing::require(channel.try_send("b").has_value()); + Void::Testing::expect_eq(channel.size(), std::size_t{2}); + + // A full channel hands the value back, untouched. + const auto full = channel.try_send(std::string(64, 'x')); + Void::Testing::require(!full.has_value()); + Void::Testing::expect(full.error().error == ChannelError::full); + Void::Testing::expect_eq(full.error().value, std::string(64, 'x')); + Void::Testing::expect_eq(channel.size(), std::size_t{2}); + + const auto first = channel.try_receive(); + Void::Testing::require(first.has_value()); + Void::Testing::expect_eq(*first, std::string{"a"}); + const auto second = channel.try_receive(); + Void::Testing::require(second.has_value()); + Void::Testing::expect_eq(*second, std::string{"b"}); + const auto empty = channel.try_receive(); + Void::Testing::require(!empty.has_value()); + Void::Testing::expect(empty.error() == ChannelError::empty); + + // Closed channel: send returns the value with `closed`; receive reports + // `closed` only once the buffer is drained. + Void::Testing::require(channel.try_send("kept").has_value()); + channel.close(); + Void::Testing::expect(channel.is_closed()); + const auto closed = channel.try_send("late"); + Void::Testing::require(!closed.has_value()); + Void::Testing::expect(closed.error().error == ChannelError::closed); + Void::Testing::expect_eq(closed.error().value, std::string{"late"}); + const auto drained = channel.try_receive(); + Void::Testing::require(drained.has_value()); + Void::Testing::expect_eq(*drained, std::string{"kept"}); + const auto done = channel.try_receive(); + Void::Testing::require(!done.has_value()); + Void::Testing::expect(done.error() == ChannelError::closed); +} + +Void::Testing::Test channel_send_waits_resumes_on_receive() +{ + ManualExecutor exec; + auto channel = make_channel(exec, ChannelOptions{.capacity = 1}); + Void::Testing::require(channel->try_send(1).has_value()); + + // The buffer is full: the sender suspends. + SendProbe send_probe; + auto sender = run_send(channel, 2, {}, &send_probe); + start(sender); + Void::Testing::expect_eq(send_probe.resumes, 0); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); + + // Receiving frees a slot: the waiting sender's value moves into the + // buffer, the sender is claimed and resumed through the completion lane. + const auto first = channel->try_receive(); + Void::Testing::require(first.has_value()); + Void::Testing::expect_eq(*first, 1); + Void::Testing::expect_eq(send_probe.resumes, 0); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(send_probe.resumes, 1); + Void::Testing::expect(send_probe.succeeded()); + Void::Testing::expect(sender.done()); + Void::Testing::expect_eq(channel->size(), std::size_t{1}); + const auto second = channel->try_receive(); + Void::Testing::require(second.has_value()); + Void::Testing::expect_eq(*second, 2); + + // A waiting receiver gets a directly handed-off value. + ReceiveProbe receive_probe; + auto receiver = run_receive(channel, {}, &receive_probe); + start(receiver); + Void::Testing::expect_eq(receive_probe.resumes, 0); + Void::Testing::require(channel->try_send(3).has_value()); + // The value went straight to the receiver, not into the buffer. + Void::Testing::expect_eq(channel->size(), std::size_t{0}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(receive_probe.resumes, 1); + Void::Testing::expect(receive_probe.value() == std::optional{3}); + + // The coroutine fast paths do not suspend. + SendProbe immediate_send; + auto fast_sender = run_send(channel, 4, {}, &immediate_send); + start(fast_sender); + Void::Testing::expect_eq(immediate_send.resumes, 1); + Void::Testing::expect(immediate_send.succeeded()); + ReceiveProbe immediate_receive; + auto fast_receiver = run_receive(channel, {}, &immediate_receive); + start(fast_receiver); + Void::Testing::expect_eq(immediate_receive.resumes, 1); + Void::Testing::expect(immediate_receive.value() == std::optional{4}); +} + +Void::Testing::Test channel_producer_stop_returns_value_cancelled_once() +{ + ManualExecutor exec; + auto channel = make_channel(exec, ChannelOptions{.capacity = 1}); + Void::Testing::require(channel->try_send(1).has_value()); + + std::stop_source stop; + SendProbe probe; + auto sender = run_send(channel, 2, OperationOptions{.stop = stop.get_token()}, &probe); + start(sender); + Void::Testing::expect_eq(probe.resumes, 0); + + // stop: unlink + cancelled, value returned, resumed via the completion lane. + Void::Testing::expect(stop.request_stop()); + Void::Testing::expect_eq(probe.resumes, 0); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(probe.resumes, 1); + Void::Testing::expect(probe.error() == std::optional{ChannelError::cancelled}); + Void::Testing::expect(probe.returned_value() == std::optional{2}); + + // Exactly once: a second stop request and further traffic change nothing, + // and the cancelled value never reaches the buffer. + Void::Testing::expect(!stop.request_stop()); + const auto received = channel->try_receive(); + Void::Testing::require(received.has_value()); + Void::Testing::expect_eq(*received, 1); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); + Void::Testing::expect_eq(probe.resumes, 1); + Void::Testing::expect_eq(channel->size(), std::size_t{0}); + + // Stop already requested: refused before any state change, value returned. + SendProbe pre_stopped; + auto refused = run_send(channel, 9, OperationOptions{.stop = stop.get_token()}, &pre_stopped); + start(refused); + Void::Testing::expect_eq(pre_stopped.resumes, 1); + Void::Testing::expect(pre_stopped.error() == std::optional{ChannelError::cancelled}); + Void::Testing::expect(pre_stopped.returned_value() == std::optional{9}); + Void::Testing::expect_eq(channel->size(), std::size_t{0}); + + // A receiver cancelled by stop leaves the channel intact. + std::stop_source receive_stop; + ReceiveProbe receive_probe; + auto receiver = run_receive(channel, OperationOptions{.stop = receive_stop.get_token()}, &receive_probe); + start(receiver); + Void::Testing::expect(receive_stop.request_stop()); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(receive_probe.resumes, 1); + Void::Testing::expect(receive_probe.error() == std::optional{ChannelError::cancelled}); + Void::Testing::require(channel->try_send(5).has_value()); + Void::Testing::expect_eq(channel->size(), std::size_t{1}); +} + +Void::Testing::Test channel_receiver_stop_after_claim_delivers_value_no_loss() +{ + ManualExecutor exec; + auto channel = make_channel(exec, ChannelOptions{.capacity = 1}); + + std::stop_source stop; + ReceiveProbe probe; + auto receiver = run_receive(channel, OperationOptions{.stop = stop.get_token()}, &probe); + start(receiver); + Void::Testing::expect_eq(probe.resumes, 0); + + // A sender claims the waiting receiver: the value is already in its slot. + Void::Testing::require(channel->try_send(77).has_value()); + // The stop request arrives after the claim and before the resume ran: the + // callback finds a claimed waiter and does nothing. + Void::Testing::expect(stop.request_stop()); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(probe.resumes, 1); + Void::Testing::expect(probe.value() == std::optional{77}); + Void::Testing::expect_eq(channel->size(), std::size_t{0}); + + // Same for a sender claimed by a receive before the stop callback ran. + auto full = make_channel(exec, ChannelOptions{.capacity = 1}); + Void::Testing::require(full->try_send(1).has_value()); + std::stop_source send_stop; + SendProbe send_probe; + auto sender = run_send(full, 2, OperationOptions{.stop = send_stop.get_token()}, &send_probe); + start(sender); + const auto taken = full->try_receive(); + Void::Testing::require(taken.has_value()); + Void::Testing::expect_eq(*taken, 1); + Void::Testing::expect(send_stop.request_stop()); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(send_probe.resumes, 1); + Void::Testing::expect(send_probe.succeeded()); + const auto delivered = full->try_receive(); + Void::Testing::require(delivered.has_value()); + Void::Testing::expect_eq(*delivered, 2); +} + +namespace +{ + +// Busy delay used to sweep the relative timing of the two racing threads. +void spin_for(int rounds) +{ + std::atomic sink{0}; + for (int k = 0; k < rounds; ++k) { + sink.fetch_add(1, std::memory_order_relaxed); + } +} + +// Reusable two-party barrier that spins (with yield) instead of sleeping on a +// futex, so both racing threads leave it at nearly the same instant. +class SpinBarrier +{ +public: + explicit SpinBarrier(unsigned parties) noexcept : parties_(parties) {} + + void arrive_and_wait() noexcept + { + const unsigned target = (count_.fetch_add(1, std::memory_order_acq_rel) / parties_ + 1) * parties_; + while (count_.load(std::memory_order_acquire) < target) { + std::this_thread::yield(); + } + } + +private: + const unsigned parties_; + std::atomic count_{0}; +}; + +} // namespace + +Void::Testing::Test channel_sender_stop_vs_receive_race_exactly_once_tsan() +{ + constexpr int kIterations = 10000; + auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 64}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + Void::Testing::require(exec.start().has_value()); + + SpinBarrier go{2}; + SpinBarrier finished{2}; + std::shared_ptr current; + std::optional helper_value; + int helper_delay = 0; + std::atomic stop_loop{false}; + + // Persistent helper: receives once per iteration, racing the stop request. + std::thread helper([&] { + for (;;) { + go.arrive_and_wait(); + if (stop_loop.load(std::memory_order_acquire)) { + return; + } + spin_for(helper_delay); + auto got = current->try_receive(); + helper_value = got.has_value() ? std::optional{*got} : std::nullopt; + finished.arrive_and_wait(); + } + }); + + int violations = 0; + int timeouts = 0; + std::uint64_t cancelled_sends = 0; + std::uint64_t completed_sends = 0; + for (int i = 0; i < kIterations; ++i) { + const int sentinel = 2 * i; + const int sent = 2 * i + 1; + // No assertion (and no throw) while the helper thread is joinable. + auto created_channel = Chan::create(exec, ChannelOptions{.capacity = 1, .max_waiters = 4}); + if (!created_channel.has_value()) { + ++violations; + break; + } + auto channel = std::move(*created_channel); + (void)channel->try_send(sentinel); + std::stop_source stop; + SendProbe probe; + std::atomic done{false}; + launch(exec, [](std::shared_ptr ch, int v, std::stop_token token, SendProbe* out, + std::atomic* flag) -> Void::Coro::Task { + auto result = co_await ch->send(v, OperationOptions{.stop = token}); + out->result = std::move(result); + flag->store(true, std::memory_order_release); + }(channel, sent, stop.get_token(), &probe, &done)); + + // Three of four iterations race a stop against a receive while the + // sender is already linked (the executor is idle once the sender + // suspended, since the buffer is full); the rest race the stop against + // the sender's own start. + if (i % 4 != 0) { + (void)wait_until([&] { return exec.idle(); }); + } + const int skew = (i % 41) - 20; // < 0: delay the stop, > 0: delay the receive + helper_delay = skew > 0 ? skew * 12 : 0; + current = channel; + go.arrive_and_wait(); + spin_for(skew < 0 ? -skew * 12 : 0); + stop.request_stop(); + finished.arrive_and_wait(); + if (!wait_until([&] { return done.load(std::memory_order_acquire); })) { + ++timeouts; + break; + } + + // Every value must be in exactly one place: received by the helper, + // returned to the sender, or still buffered. + int seen[2] = {0, 0}; + const auto note = [&](int value) { + if (value == sentinel) { + ++seen[0]; + } else if (value == sent) { + ++seen[1]; + } else { + ++violations; + } + }; + if (helper_value.has_value()) { + note(*helper_value); + } + if (probe.returned_value().has_value()) { + note(*probe.returned_value()); + ++cancelled_sends; + } else if (probe.succeeded()) { + ++completed_sends; + } else { + ++violations; + } + for (;;) { + auto rest = channel->try_receive(); + if (!rest.has_value()) { + break; + } + note(*rest); + } + if (seen[0] != 1 || seen[1] != 1) { + ++violations; + } + current.reset(); + } + stop_loop.store(true, std::memory_order_release); + go.arrive_and_wait(); + helper.join(); + Void::Testing::require(exec.join().has_value()); + + Void::Testing::expect_eq(timeouts, 0); + Void::Testing::expect_eq(violations, 0); + // Whichever side won each race, the sender settled exactly once. + Void::Testing::expect_eq(cancelled_sends + completed_sends, static_cast(kIterations)); +} + +Void::Testing::Test channel_close_wakes_senders_with_value_and_drains_receivers() +{ + ManualExecutor exec; + auto channel = make_channel(exec, ChannelOptions{.capacity = 2}); + Void::Testing::require(channel->try_send(1).has_value()); + Void::Testing::require(channel->try_send(2).has_value()); + + SendProbe first_sender; + SendProbe second_sender; + auto sender_a = run_send(channel, 3, {}, &first_sender); + auto sender_b = run_send(channel, 4, {}, &second_sender); + start(sender_a); + start(sender_b); + Void::Testing::expect_eq(first_sender.resumes + second_sender.resumes, 0); + + channel->close(); + Void::Testing::expect(channel->is_closed()); + Void::Testing::expect_eq(first_sender.resumes + second_sender.resumes, 0); + Void::Testing::expect_eq(exec.drain(), std::size_t{2}); + // Waiting senders: `closed` plus their own value back, each exactly once. + Void::Testing::expect_eq(first_sender.resumes, 1); + Void::Testing::expect_eq(second_sender.resumes, 1); + Void::Testing::expect(first_sender.error() == std::optional{ChannelError::closed}); + Void::Testing::expect(second_sender.error() == std::optional{ChannelError::closed}); + Void::Testing::expect(first_sender.returned_value() == std::optional{3}); + Void::Testing::expect(second_sender.returned_value() == std::optional{4}); + + // close() is idempotent and wakes nobody twice. + channel->close(); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); + + // Receivers drain the buffer in FIFO order, then get `closed`. + ReceiveProbe r1; + ReceiveProbe r2; + ReceiveProbe r3; + auto rt1 = run_receive(channel, {}, &r1); + auto rt2 = run_receive(channel, {}, &r2); + auto rt3 = run_receive(channel, {}, &r3); + start(rt1); + start(rt2); + start(rt3); + Void::Testing::expect(r1.value() == std::optional{1}); + Void::Testing::expect(r2.value() == std::optional{2}); + Void::Testing::expect(r3.error() == std::optional{ChannelError::closed}); + + // Receivers that are already waiting when close() runs get `closed`. + auto empty = make_channel(exec, ChannelOptions{.capacity = 2}); + ReceiveProbe w1; + ReceiveProbe w2; + auto wt1 = run_receive(empty, {}, &w1); + auto wt2 = run_receive(empty, {}, &w2); + start(wt1); + start(wt2); + Void::Testing::expect_eq(w1.resumes + w2.resumes, 0); + empty->close(); + Void::Testing::expect_eq(exec.drain(), std::size_t{2}); + Void::Testing::expect(w1.error() == std::optional{ChannelError::closed}); + Void::Testing::expect(w2.error() == std::optional{ChannelError::closed}); + Void::Testing::expect_eq(w1.resumes + w2.resumes, 2); + + // send() after close(): closed, value returned, without suspending. + SendProbe late; + auto late_sender = run_send(empty, 8, {}, &late); + start(late_sender); + Void::Testing::expect(late.error() == std::optional{ChannelError::closed}); + Void::Testing::expect(late.returned_value() == std::optional{8}); +} + +Void::Testing::Test channel_deadline_requires_timers() +{ + ManualExecutor exec; + auto channel = make_channel(exec, ChannelOptions{.capacity = 1}); + const OperationOptions with_deadline{.deadline = TimePoint{std::chrono::seconds{5}}}; + + // No `timers`: a deadline cannot be judged -> invalid_argument, value back. + SendProbe send_probe; + auto sender = run_send(channel, 6, with_deadline, &send_probe); + start(sender); + Void::Testing::expect_eq(send_probe.resumes, 1); + Void::Testing::expect(send_probe.error() == std::optional{ChannelError::invalid_argument}); + Void::Testing::expect(send_probe.returned_value() == std::optional{6}); + // ... before any state change: nothing was buffered. + Void::Testing::expect_eq(channel->size(), std::size_t{0}); + + ReceiveProbe receive_probe; + auto receiver = run_receive(channel, with_deadline, &receive_probe); + start(receiver); + Void::Testing::expect_eq(receive_probe.resumes, 1); + Void::Testing::expect(receive_probe.error() == std::optional{ChannelError::invalid_argument}); + + // Even when the channel could serve the request immediately. + Void::Testing::require(channel->try_send(1).has_value()); + ReceiveProbe still_invalid; + auto second_receiver = run_receive(channel, with_deadline, &still_invalid); + start(second_receiver); + Void::Testing::expect(still_invalid.error() == std::optional{ChannelError::invalid_argument}); + Void::Testing::expect_eq(channel->size(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); +} + +Void::Testing::Test channel_deadline_times_out_once_manual_clock_poll() +{ + ManualExecutor exec; + ManualClock clock; + auto timers = make_timers(exec, clock); + auto channel = make_channel(exec, ChannelOptions{.capacity = 1, .timers = timers.get()}); + Void::Testing::require(channel->try_send(1).has_value()); + const TimePoint deadline = clock.now() + 100ms; + + SendProbe send_probe; + auto sender = run_send(channel, 2, OperationOptions{.deadline = deadline}, &send_probe); + start(sender); + Void::Testing::expect_eq(send_probe.resumes, 0); + Void::Testing::expect_eq(timers->active_timers(), std::size_t{1}); + + advance_clock(clock, 99ms); + Void::Testing::expect_eq(timers->poll_expired(), std::size_t{0}); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); + Void::Testing::expect_eq(send_probe.resumes, 0); + + advance_clock(clock, 1ms); + Void::Testing::expect_eq(timers->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(send_probe.resumes, 0); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(send_probe.resumes, 1); + Void::Testing::expect(send_probe.error() == std::optional{ChannelError::timed_out}); + Void::Testing::expect(send_probe.returned_value() == std::optional{2}); + + // Exactly once: later polls and traffic never touch the settled sender. + advance_clock(clock, 1s); + Void::Testing::expect_eq(timers->poll_expired(), std::size_t{0}); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); + Void::Testing::expect_eq(send_probe.resumes, 1); + Void::Testing::expect_eq(timers->active_timers(), std::size_t{0}); + const auto kept = channel->try_receive(); + Void::Testing::require(kept.has_value()); + Void::Testing::expect_eq(*kept, 1); + Void::Testing::expect_eq(channel->size(), std::size_t{0}); + + // A receiver times out the same way. + ReceiveProbe receive_probe; + auto receiver = run_receive(channel, OperationOptions{.deadline = clock.now() + 10ms}, &receive_probe); + start(receiver); + Void::Testing::expect_eq(timers->active_timers(), std::size_t{1}); + advance_clock(clock, 10ms); + Void::Testing::expect_eq(timers->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(receive_probe.error() == std::optional{ChannelError::timed_out}); + Void::Testing::expect_eq(receive_probe.resumes, 1); + + // A deadline that is already reached is refused before any state change. + SendProbe expired; + auto expired_sender = run_send(channel, 3, OperationOptions{.deadline = clock.now()}, &expired); + start(expired_sender); + Void::Testing::expect_eq(expired.resumes, 1); + Void::Testing::expect(expired.error() == std::optional{ChannelError::timed_out}); + Void::Testing::expect(expired.returned_value() == std::optional{3}); + Void::Testing::expect_eq(channel->size(), std::size_t{0}); + Void::Testing::expect_eq(timers->active_timers(), std::size_t{0}); + + // A wait that is satisfied before the deadline cancels its timer. + SendProbe satisfied; + Void::Testing::require(channel->try_send(10).has_value()); + auto early_sender = run_send(channel, 11, OperationOptions{.deadline = clock.now() + 1s}, &satisfied); + start(early_sender); + Void::Testing::expect_eq(timers->active_timers(), std::size_t{1}); + const auto early = channel->try_receive(); + Void::Testing::require(early.has_value()); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(satisfied.succeeded()); + Void::Testing::expect_eq(timers->active_timers(), std::size_t{0}); +} + +Void::Testing::Test channel_timer_close_settles_waiter_cancelled() +{ + ManualExecutor exec; + ManualClock clock; + auto timers = make_timers(exec, clock, 2); + auto channel = make_channel(exec, ChannelOptions{.capacity = 1, .timers = timers.get()}); + Void::Testing::require(channel->try_send(1).has_value()); + const OperationOptions options{.deadline = clock.now() + 1s}; + + SendProbe send_probe; + auto sender = run_send(channel, 2, options, &send_probe); + start(sender); + ReceiveProbe receive_probe; + auto other = make_channel(exec, ChannelOptions{.capacity = 1, .timers = timers.get()}); + auto receiver = run_receive(other, options, &receive_probe); + start(receiver); + Void::Testing::expect_eq(timers->active_timers(), std::size_t{2}); + + // The timer queue is at max_timers: a third deadline wait is refused with + // overloaded and the value comes back. + SendProbe overloaded; + auto third = run_send(channel, 3, options, &overloaded); + start(third); + Void::Testing::expect_eq(overloaded.resumes, 1); + Void::Testing::expect(overloaded.error() == std::optional{ChannelError::overloaded}); + Void::Testing::expect(overloaded.returned_value() == std::optional{3}); + + // TimerEvent::closed settles every pending channel wait `cancelled`. + timers->close(); + Void::Testing::expect_eq(send_probe.resumes, 0); + Void::Testing::expect_eq(exec.drain(), std::size_t{2}); + Void::Testing::expect_eq(send_probe.resumes, 1); + Void::Testing::expect_eq(receive_probe.resumes, 1); + Void::Testing::expect(send_probe.error() == std::optional{ChannelError::cancelled}); + Void::Testing::expect(send_probe.returned_value() == std::optional{2}); + Void::Testing::expect(receive_probe.error() == std::optional{ChannelError::cancelled}); + + // A closed timer queue refuses new deadline waits: stopped -> cancelled. + SendProbe after_close; + auto fourth = run_send(channel, 4, options, &after_close); + start(fourth); + Void::Testing::expect_eq(after_close.resumes, 1); + Void::Testing::expect(after_close.error() == std::optional{ChannelError::cancelled}); + Void::Testing::expect(after_close.returned_value() == std::optional{4}); + // The channel itself is untouched. + Void::Testing::expect_eq(channel->size(), std::size_t{1}); +} + +Void::Testing::Test channel_timer_fire_after_waiter_destroyed_safe() +{ + ManualExecutor exec; + ManualClock clock; + auto timers = make_timers(exec, clock); + auto channel = make_channel(exec, ChannelOptions{.capacity = 1, .timers = timers.get()}); + Void::Testing::require(channel->try_send(1).has_value()); + const TimePoint deadline = clock.now() + 50ms; + + SendProbe probe; + std::unique_ptr> task; + int gate_received = -1; + int gate_runs = 0; + // poll_expired() claims every due timer before running any callback, in + // (deadline, seq) order. The gate timer (lower seq) runs first: it lets the + // waiting sender complete, destroys its task and drops the last reference + // to the channel, so the sender's own timer callback then runs against a + // dead waiter and channel. + auto gate = timers->schedule_at( + deadline, + TimerCallback{[&](TimerEvent) noexcept { + ++gate_runs; + const auto got = channel->try_receive(); + gate_received = got.has_value() ? *got : -1; + (void)exec.drain(); + task.reset(); + channel.reset(); + }}); + Void::Testing::require(gate.has_value()); + + task = std::make_unique>( + run_send(channel, 2, OperationOptions{.deadline = deadline}, &probe)); + start(*task); + Void::Testing::expect_eq(timers->active_timers(), std::size_t{2}); + Void::Testing::expect_eq(probe.resumes, 0); + + advance_clock(clock, 50ms); + Void::Testing::expect_eq(timers->poll_expired(), std::size_t{2}); + Void::Testing::expect_eq(gate_runs, 1); + Void::Testing::expect_eq(gate_received, 1); + // The sender completed exactly once with success (no late timeout). + Void::Testing::expect_eq(probe.resumes, 1); + Void::Testing::expect(probe.succeeded()); + Void::Testing::expect(channel == nullptr); + Void::Testing::expect(task == nullptr); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); +} + +Void::Testing::Test channel_waiter_bound_overloaded() +{ + ManualExecutor exec; + auto channel = make_channel(exec, ChannelOptions{.capacity = 1, .max_waiters = 2}); + Void::Testing::require(channel->try_send(0).has_value()); + + SendProbe s1; + SendProbe s2; + SendProbe s3; + auto t1 = run_send(channel, 1, {}, &s1); + auto t2 = run_send(channel, 2, {}, &s2); + auto t3 = run_send(channel, 3, {}, &s3); + start(t1); + start(t2); + start(t3); + // Two senders wait; the third exceeds max_waiters and gets its value back. + Void::Testing::expect_eq(s1.resumes + s2.resumes, 0); + Void::Testing::expect_eq(s3.resumes, 1); + Void::Testing::expect(s3.error() == std::optional{ChannelError::overloaded}); + Void::Testing::expect(s3.returned_value() == std::optional{3}); + + // The bound is per direction: receivers have their own budget. + auto empty = make_channel(exec, ChannelOptions{.capacity = 1, .max_waiters = 1}); + ReceiveProbe r1; + ReceiveProbe r2; + auto rt1 = run_receive(empty, {}, &r1); + auto rt2 = run_receive(empty, {}, &r2); + start(rt1); + start(rt2); + Void::Testing::expect_eq(r1.resumes, 0); + Void::Testing::expect_eq(r2.resumes, 1); + Void::Testing::expect(r2.error() == std::optional{ChannelError::overloaded}); + + // A freed waiter slot can be reused: drain the waiting senders in order. + for (int expected : {0, 1, 2}) { + const auto got = channel->try_receive(); + Void::Testing::require(got.has_value()); + Void::Testing::expect_eq(*got, expected); + (void)exec.drain(); + } + Void::Testing::expect_eq(s1.resumes, 1); + Void::Testing::expect_eq(s2.resumes, 1); + Void::Testing::expect(s1.succeeded()); + Void::Testing::expect(s2.succeeded()); + Void::Testing::require(empty->try_send(5).has_value()); + (void)exec.drain(); + Void::Testing::expect(r1.value() == std::optional{5}); +} + +namespace +{ + +using Ptr = std::unique_ptr; +using PtrChannel = AsyncChannel; +using PtrSendResult = std::expected>; +using PtrReceiveResult = std::expected; + +Void::Coro::Task ptr_sender(std::shared_ptr channel, + Ptr value, + std::optional* out, + int* resumes) +{ + auto result = co_await channel->send(std::move(value)); + *out = std::move(result); + ++*resumes; +} + +Void::Coro::Task ptr_receiver(std::shared_ptr channel, + std::optional* out, + int* resumes) +{ + auto result = co_await channel->receive(); + *out = std::move(result); + ++*resumes; +} + +} // namespace + +Void::Testing::Test channel_move_only_values() +{ + ManualExecutor exec; + auto created = PtrChannel::create(exec, ChannelOptions{.capacity = 1}); + Void::Testing::require(created.has_value()); + auto channel = std::move(*created); + + Ptr first = std::make_unique(10); + int* const first_raw = first.get(); + Void::Testing::require(channel->try_send(std::move(first)).has_value()); + + // A rejected move-only value comes back intact (the same object). + Ptr second = std::make_unique(20); + int* const second_raw = second.get(); + auto full = channel->try_send(std::move(second)); + Void::Testing::require(!full.has_value()); + Void::Testing::expect(full.error().error == ChannelError::full); + Void::Testing::expect(full.error().value.get() == second_raw); + + auto received = channel->try_receive(); + Void::Testing::require(received.has_value()); + Void::Testing::expect(received->get() == first_raw); + + // A suspended coroutine send keeps ownership until the value is delivered. + Void::Testing::require(channel->try_send(std::make_unique(30)).has_value()); + Ptr third = std::make_unique(40); + int* const third_raw = third.get(); + std::optional send_result; + int resumes = 0; + auto sender = ptr_sender(channel, std::move(third), &send_result, &resumes); + start(sender); + Void::Testing::expect_eq(resumes, 0); + auto drained = channel->try_receive(); + Void::Testing::require(drained.has_value()); + Void::Testing::expect_eq(**drained, 30); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::require(send_result.has_value()); + Void::Testing::expect(send_result->has_value()); + auto buffered = channel->try_receive(); + Void::Testing::require(buffered.has_value()); + Void::Testing::expect(buffered->get() == third_raw); + + // A cancelled move-only send returns the pointer. + Void::Testing::require(channel->try_send(std::make_unique(50)).has_value()); + std::stop_source stop; + Ptr fourth = std::make_unique(60); + int* const fourth_raw = fourth.get(); + std::optional cancelled_result; + int cancelled_resumes = 0; + auto stoppable = [](std::shared_ptr ch, Ptr value, std::stop_token token, + std::optional* out, int* counter) -> Void::Coro::Task { + auto result = co_await ch->send(std::move(value), OperationOptions{.stop = token}); + *out = std::move(result); + ++*counter; + }(channel, std::move(fourth), stop.get_token(), &cancelled_result, &cancelled_resumes); + start(stoppable); + Void::Testing::expect(stop.request_stop()); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(cancelled_resumes, 1); + Void::Testing::require(cancelled_result.has_value()); + Void::Testing::require(!cancelled_result->has_value()); + Void::Testing::expect(cancelled_result->error().error == ChannelError::cancelled); + Void::Testing::expect(cancelled_result->error().value.get() == fourth_raw); + + // A waiting move-only receiver gets the handed-off pointer. + auto emptied = channel->try_receive(); + Void::Testing::require(emptied.has_value()); + std::optional receive_result; + int receive_resumes = 0; + auto receiver = ptr_receiver(channel, &receive_result, &receive_resumes); + start(receiver); + Void::Testing::expect_eq(receive_resumes, 0); + Ptr handed = std::make_unique(70); + int* const handed_raw = handed.get(); + Void::Testing::require(channel->try_send(std::move(handed)).has_value()); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(receive_resumes, 1); + Void::Testing::require(receive_result.has_value()); + Void::Testing::require(receive_result->has_value()); + Void::Testing::expect((*receive_result)->get() == handed_raw); +} + +namespace +{ + +constexpr std::uint64_t kProducerStride = 1'000'000; + +Void::Coro::Task producer_task(std::shared_ptr> channel, + std::uint64_t producer, + int items, + std::atomic* producers_done, + std::atomic* send_errors) +{ + for (int k = 0; k < items; ++k) { + auto result = co_await channel->send(producer * kProducerStride + static_cast(k)); + if (!result.has_value()) { + send_errors->fetch_add(1); + } + } + producers_done->fetch_add(1); +} + +Void::Coro::Task consumer_task(std::shared_ptr> channel, + std::vector* sink, + std::atomic* consumers_done) +{ + for (;;) { + auto result = co_await channel->receive(); + if (!result.has_value()) { + break; + } + sink->push_back(*result); + } + consumers_done->fetch_add(1); +} + +} // namespace + +Void::Testing::Test channel_mpmc_fifo_tsan() +{ + constexpr int kProducers = 3; + constexpr int kConsumers = 3; + constexpr int kItems = 1500; + auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 4}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + Void::Testing::require(exec.start().has_value()); + + auto channel_result = AsyncChannel::create( + exec, ChannelOptions{.capacity = 8, .max_waiters = 64}); + Void::Testing::require(channel_result.has_value()); + auto channel = std::move(*channel_result); + + std::atomic producers_done{0}; + std::atomic consumers_done{0}; + std::atomic send_errors{0}; + std::vector sinks[kConsumers]; + + for (int c = 0; c < kConsumers; ++c) { + launch(exec, consumer_task(channel, &sinks[c], &consumers_done)); + } + for (int p = 0; p < kProducers; ++p) { + launch(exec, producer_task(channel, static_cast(p), kItems, &producers_done, &send_errors)); + } + const bool producers_finished = wait_until([&] { return producers_done.load() == kProducers; }); + // close() unblocks every remaining waiter, so the joins below cannot hang. + channel->close(); + const bool consumers_finished = wait_until([&] { return consumers_done.load() == kConsumers; }); + Void::Testing::require(exec.join().has_value()); + Void::Testing::expect(producers_finished); + Void::Testing::expect(consumers_finished); + + std::size_t total = 0; + std::uint64_t order_violations = 0; + std::vector seen(static_cast(kProducers) * kItems, 0); + std::uint64_t unknown_values = 0; + for (const auto& sink : sinks) { + total += sink.size(); + std::int64_t last[kProducers]; + for (auto& l : last) { + l = -1; + } + for (const std::uint64_t value : sink) { + const std::uint64_t producer = value / kProducerStride; + const std::uint64_t index = value % kProducerStride; + if (producer >= static_cast(kProducers) || + index >= static_cast(kItems)) { + ++unknown_values; + continue; + } + // Per-producer FIFO: one consumer sees a producer's items in order. + if (static_cast(index) <= last[producer]) { + ++order_violations; + } + last[producer] = static_cast(index); + ++seen[static_cast(producer) * kItems + static_cast(index)]; + } + } + std::uint64_t not_exactly_once = 0; + for (const int count : seen) { + if (count != 1) { + ++not_exactly_once; + } + } + Void::Testing::expect_eq(send_errors.load(), 0); + Void::Testing::expect_eq(total, static_cast(kProducers) * kItems); + Void::Testing::expect_eq(unknown_values, std::uint64_t{0}); + Void::Testing::expect_eq(order_violations, std::uint64_t{0}); + Void::Testing::expect_eq(not_exactly_once, std::uint64_t{0}); + Void::Testing::expect_eq(channel->size(), std::size_t{0}); +} + +Void::Testing::Test channel_deadline_check_order_returns_value() +{ + ManualExecutor exec; + ManualClock clock; + auto timers = make_timers(exec, clock, 1); + auto with_timers = make_channel(exec, ChannelOptions{.capacity = 2, .timers = timers.get()}); + auto without_timers = make_channel(exec, ChannelOptions{.capacity = 2}); + const TimePoint expired = clock.now(); + const TimePoint future = clock.now() + 1s; + + std::stop_source requested; + requested.request_stop(); + + // 1. stop wins over an expired deadline, a missing timer queue and a + // closed channel. + SendProbe stop_vs_deadline; + auto t1 = run_send(with_timers, 1, OperationOptions{.stop = requested.get_token(), .deadline = expired}, + &stop_vs_deadline); + start(t1); + Void::Testing::expect(stop_vs_deadline.error() == std::optional{ChannelError::cancelled}); + Void::Testing::expect(stop_vs_deadline.returned_value() == std::optional{1}); + + SendProbe stop_vs_no_timers; + auto t2 = run_send(without_timers, 2, OperationOptions{.stop = requested.get_token(), .deadline = future}, + &stop_vs_no_timers); + start(t2); + Void::Testing::expect(stop_vs_no_timers.error() == std::optional{ChannelError::cancelled}); + Void::Testing::expect(stop_vs_no_timers.returned_value() == std::optional{2}); + + without_timers->close(); + SendProbe stop_vs_closed; + auto t3 = run_send(without_timers, 3, OperationOptions{.stop = requested.get_token()}, &stop_vs_closed); + start(t3); + Void::Testing::expect(stop_vs_closed.error() == std::optional{ChannelError::cancelled}); + Void::Testing::expect(stop_vs_closed.returned_value() == std::optional{3}); + + // 2. An expired deadline (judged by the TimerQueue's clock) beats the + // channel state: nothing is buffered even though there was room. + SendProbe expired_probe; + auto t4 = run_send(with_timers, 4, OperationOptions{.deadline = expired}, &expired_probe); + start(t4); + Void::Testing::expect(expired_probe.error() == std::optional{ChannelError::timed_out}); + Void::Testing::expect(expired_probe.returned_value() == std::optional{4}); + Void::Testing::expect_eq(with_timers->size(), std::size_t{0}); + + // 3. A deadline without timers is invalid_argument, also before `closed`. + SendProbe closed_no_timers; + auto t5 = run_send(without_timers, 5, OperationOptions{.deadline = future}, &closed_no_timers); + start(t5); + Void::Testing::expect(closed_no_timers.error() == std::optional{ChannelError::invalid_argument}); + Void::Testing::expect(closed_no_timers.returned_value() == std::optional{5}); + + // 4. A closed channel (no options) reports closed with the value. + SendProbe closed_plain; + auto t6 = run_send(without_timers, 6, {}, &closed_plain); + start(t6); + Void::Testing::expect(closed_plain.error() == std::optional{ChannelError::closed}); + Void::Testing::expect(closed_plain.returned_value() == std::optional{6}); + + // 5. A future deadline with room succeeds on the fast path and leaves no + // timer behind. + SendProbe fast; + auto t7 = run_send(with_timers, 7, OperationOptions{.deadline = future}, &fast); + start(t7); + Void::Testing::expect(fast.succeeded()); + Void::Testing::expect_eq(timers->active_timers(), std::size_t{0}); + Void::Testing::expect_eq(with_timers->size(), std::size_t{1}); + + // 6. When the timer queue refuses the timer the value comes back and no + // waiter is left behind: fill the channel, occupy the single timer slot. + Void::Testing::require(with_timers->try_send(8).has_value()); + auto foreign = timers->schedule_at(future, TimerCallback{[](TimerEvent) noexcept {}}); + Void::Testing::require(foreign.has_value()); + SendProbe refused; + auto t8 = run_send(with_timers, 9, OperationOptions{.deadline = future}, &refused); + start(t8); + Void::Testing::expect(refused.error() == std::optional{ChannelError::overloaded}); + Void::Testing::expect(refused.returned_value() == std::optional{9}); + Void::Testing::expect_eq(with_timers->size(), std::size_t{2}); + Void::Testing::expect(foreign->cancel()); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); +} diff --git a/tests/standalone/Async/FuturePool.cpp b/tests/standalone/Async/FuturePool.cpp new file mode 100644 index 0000000..3845f5d --- /dev/null +++ b/tests/standalone/Async/FuturePool.cpp @@ -0,0 +1,245 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// All assertions run on the test thread; callables executed by workers only +// touch atomics (the assertion context is thread_local). + +namespace +{ + +using namespace Void::Async; +using namespace std::chrono_literals; + +class Gate +{ +public: + void open() + { + { + std::lock_guard lk{mu_}; + open_ = true; + } + cv_.notify_all(); + } + + void wait() + { + std::unique_lock lk{mu_}; + cv_.wait(lk, [this] { return open_; }); + } + +private: + std::mutex mu_{}; + std::condition_variable cv_{}; + bool open_{false}; +}; + +template +bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms) +{ + const auto end = std::chrono::steady_clock::now() + timeout; + while (!pred()) { + if (std::chrono::steady_clock::now() >= end) { + return false; + } + std::this_thread::sleep_for(1ms); + } + return true; +} + +// Opens the gate before the executor is destroyed, so a failed assertion can +// never leave a blocked callable hanging ~ThreadExecutor. +struct Fixture { + Gate gate{}; + std::unique_ptr exec{}; + + Fixture(std::size_t workers, std::size_t max_admitted) + { + auto created = ThreadExecutor::create( + ThreadExecutorOptions{.workers = workers, .max_admitted = max_admitted}); + Void::Testing::require(created.has_value()); + exec = std::move(*created); + Void::Testing::require(exec->start().has_value()); + } + + ~Fixture() { gate.open(); } + + Fixture(const Fixture&) = delete; + Fixture& operator=(const Fixture&) = delete; +}; + +// Move-only callable that records every move: proves a rejected submission +// never consumed it. +struct TrackedCallable { + std::shared_ptr> moves{std::make_shared>(0)}; + std::unique_ptr payload{std::make_unique(41)}; + std::atomic* ran{nullptr}; + + TrackedCallable() = default; + explicit TrackedCallable(std::atomic* ran_flag) : ran(ran_flag) {} + + TrackedCallable(TrackedCallable&& other) noexcept + : moves(other.moves) + , payload(std::move(other.payload)) + , ran(other.ran) + { + moves->fetch_add(1); + } + + TrackedCallable& operator=(TrackedCallable&&) = delete; + TrackedCallable(const TrackedCallable&) = delete; + TrackedCallable& operator=(const TrackedCallable&) = delete; + + int operator()() + { + if (ran != nullptr) { + ran->store(true); + } + return payload ? *payload + 1 : -1; + } +}; + +} // namespace + +Void::Testing::Test future_pool_overloaded_does_not_consume_callable() +{ + std::atomic blocker_running{false}; + std::atomic ran{false}; + Fixture fx{1, 1}; + FuturePool pool{*fx.exec}; + + auto blocker = pool.try_submit([&] { + blocker_running.store(true); + fx.gate.wait(); + return 7; + }); + Void::Testing::require(blocker.has_value()); + Void::Testing::require(wait_until([&] { return blocker_running.load(); })); + + TrackedCallable callable{&ran}; + const auto rejected = pool.try_submit(std::move(callable)); + Void::Testing::require(!rejected.has_value()); + Void::Testing::expect(rejected.error() == AdmissionError::overloaded); + // Reserve-then-transfer: the callable was not even moved from. + Void::Testing::expect_eq(callable.moves->load(), 0); + Void::Testing::require(callable.payload != nullptr); + Void::Testing::expect_eq(*callable.payload, 41); + Void::Testing::expect(!ran.load()); + + fx.gate.open(); + Void::Testing::expect_eq(blocker->get(), 7); + Void::Testing::require(wait_until([&] { return fx.exec->admitted() == 0; })); + + // The very same callable is still usable. + auto accepted = pool.try_submit(std::move(callable)); + Void::Testing::require(accepted.has_value()); + Void::Testing::expect_eq(accepted->get(), 42); + Void::Testing::expect(ran.load()); +} + +Void::Testing::Test future_pool_stopped_after_close() +{ + Fixture fx{1, 4}; + FuturePool pool{*fx.exec}; + + auto before = pool.try_submit([] { return 1; }); + Void::Testing::require(before.has_value()); + Void::Testing::expect_eq(before->get(), 1); + + fx.exec->close(); + std::atomic ran{false}; + TrackedCallable callable{&ran}; + const auto stopped = pool.try_submit(std::move(callable)); + Void::Testing::require(!stopped.has_value()); + Void::Testing::expect(stopped.error() == AdmissionError::stopped); + Void::Testing::expect_eq(callable.moves->load(), 0); + Void::Testing::expect(callable.payload != nullptr); + Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{0}); + Void::Testing::require(fx.exec->join().has_value()); + Void::Testing::expect(!ran.load()); +} + +Void::Testing::Test future_pool_exception_in_future() +{ + Fixture fx{2, 8}; + FuturePool pool{*fx.exec}; + + auto failing = pool.try_submit([]() -> int { throw std::runtime_error{"boom"}; }); + Void::Testing::require(failing.has_value()); + bool caught = false; + try { + (void)failing->get(); + } catch (const std::runtime_error& error) { + caught = std::string{error.what()} == "boom"; + } + Void::Testing::expect(caught); + + // void callables work, and a thrown exception does not poison the pool. + std::atomic ran{0}; + auto void_job = pool.try_submit([&ran] { ran.fetch_add(1); }); + Void::Testing::require(void_job.has_value()); + void_job->get(); + Void::Testing::expect_eq(ran.load(), 1); + + auto after = pool.try_submit([] { return 5; }); + Void::Testing::require(after.has_value()); + Void::Testing::expect_eq(after->get(), 5); + // Slots are released even when the callable threw. + Void::Testing::expect(wait_until([&] { return fx.exec->admitted() == 0; })); +} + +Void::Testing::Test future_pool_bound_includes_running() +{ + std::atomic first_running{false}; + std::atomic started{0}; + Fixture fx{1, 2}; + FuturePool pool{*fx.exec}; + + auto running = pool.try_submit([&] { + first_running.store(true); + started.fetch_add(1); + fx.gate.wait(); + return 1; + }); + Void::Testing::require(running.has_value()); + Void::Testing::require(wait_until([&] { return first_running.load(); })); + // The running callable still counts against the bound. + Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{1}); + + auto queued = pool.try_submit([&] { + started.fetch_add(1); + return 2; + }); + Void::Testing::require(queued.has_value()); + Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{2}); + + const auto rejected = pool.try_submit([] { return 3; }); + Void::Testing::require(!rejected.has_value()); + Void::Testing::expect(rejected.error() == AdmissionError::overloaded); + Void::Testing::expect_eq(fx.exec->stats().rejected, std::uint64_t{1}); + + fx.gate.open(); + Void::Testing::expect_eq(running->get(), 1); + Void::Testing::expect_eq(queued->get(), 2); + Void::Testing::expect_eq(started.load(), 2); + Void::Testing::require(wait_until([&] { return fx.exec->admitted() == 0; })); + + auto again = pool.try_submit([] { return 4; }); + Void::Testing::require(again.has_value()); + Void::Testing::expect_eq(again->get(), 4); +} diff --git a/tests/standalone/Async/ParallelForBounded.cpp b/tests/standalone/Async/ParallelForBounded.cpp new file mode 100644 index 0000000..478f507 --- /dev/null +++ b/tests/standalone/Async/ParallelForBounded.cpp @@ -0,0 +1,626 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Assertions run on the test thread only (the assertion context is +// thread_local); the loop bodies executed by pool workers only touch atomics or +// distinct array elements. + +namespace +{ + +using namespace Void::Concurrency; +using namespace std::chrono_literals; +using Kind = ParallelForError::Kind; + +class Gate +{ +public: + void open() + { + { + std::lock_guard lk{mu_}; + open_ = true; + } + cv_.notify_all(); + } + + void wait() + { + std::unique_lock lk{mu_}; + cv_.wait(lk, [this] { return open_; }); + } + +private: + std::mutex mu_{}; + std::condition_variable cv_{}; + bool open_{false}; +}; + +template +bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms) +{ + const auto end = std::chrono::steady_clock::now() + timeout; + while (!pred()) { + if (std::chrono::steady_clock::now() >= end) { + return false; + } + std::this_thread::sleep_for(1ms); + } + return true; +} + +// Tracks the maximum number of concurrently running loop bodies. +struct ConcurrencyMeter { + std::atomic active{0}; + std::atomic peak{0}; + + void enter() + { + const int now = active.fetch_add(1) + 1; + int seen = peak.load(); + while (now > seen && !peak.compare_exchange_weak(seen, now)) { + } + } + + void leave() { active.fetch_sub(1); } +}; + +std::string what(const std::exception_ptr& error) +{ + if (!error) { + return ""; + } + try { + std::rethrow_exception(error); + } catch (const std::exception& e) { + return e.what(); + } catch (...) { + return ""; + } +} + +// Opens the gate on destruction so a failed assertion cannot leave a blocked +// pool task hanging ~ThreadPool. Declare it AFTER the pool it protects. +struct GateGuard { + Gate& gate; + ~GateGuard() { gate.open(); } +}; + +// Opens the gate and joins a helper thread on every exit path. +struct ThreadJoiner { + Gate& gate; + std::thread& thread; + ~ThreadJoiner() + { + gate.open(); + if (thread.joinable()) { + thread.join(); + } + } +}; + +} // namespace + +Void::Testing::Test parallel_for_bounded_grain_and_concurrency_limit() +{ + constexpr int kCount = 40; + ThreadPool pool{4}; + + // grain = 3 over [0, 40): 14 chunks, at most 2 running at once. + { + ConcurrencyMeter meter; + std::vector> hits(kCount); + std::vector owner(kCount); + std::vector order(kCount, 0); + std::atomic sequence{0}; + const auto result = parallel_for( + 0, kCount, + [&](int i) { + meter.enter(); + owner[static_cast(i)] = std::this_thread::get_id(); + order[static_cast(i)] = sequence.fetch_add(1); + hits[static_cast(i)].fetch_add(1); + std::this_thread::sleep_for(1ms); + meter.leave(); + }, + pool, ParallelForOptions{.grain = 3, .max_concurrency = 2}); + Void::Testing::expect(result.has_value()); + int bad_hits = 0; + int chunk_not_on_one_thread = 0; + int chunk_not_ordered = 0; + for (int i = 0; i < kCount; ++i) { + if (hits[static_cast(i)].load() != 1) { + ++bad_hits; + } + if (i % 3 != 0) { + if (owner[static_cast(i)] != owner[static_cast(i - 1)]) { + ++chunk_not_on_one_thread; + } + if (order[static_cast(i)] <= order[static_cast(i - 1)]) { + ++chunk_not_ordered; + } + } + } + Void::Testing::expect_eq(bad_hits, 0); + Void::Testing::expect_eq(chunk_not_on_one_thread, 0); + Void::Testing::expect_eq(chunk_not_ordered, 0); + Void::Testing::expect(meter.peak.load() >= 1); + Void::Testing::expect(meter.peak.load() <= 2); + } + + // max_concurrency == 0 means the pool's thread count. + { + ConcurrencyMeter meter; + std::atomic calls{0}; + const auto result = parallel_for( + 0, 64, + [&](int) { + meter.enter(); + calls.fetch_add(1); + std::this_thread::sleep_for(1ms); + meter.leave(); + }, + pool, ParallelForOptions{}); + Void::Testing::expect(result.has_value()); + Void::Testing::expect_eq(calls.load(), 64); + Void::Testing::expect(meter.peak.load() <= 4); + } + + // The error report carries the chunk geometry: 40 indices / grain 3 = 14. + { + std::atomic calls{0}; + const auto result = parallel_for( + 0, kCount, + [&](int i) { + calls.fetch_add(1); + if (i == 7) { + throw std::runtime_error{"seven"}; + } + }, + pool, ParallelForOptions{.grain = 3, .max_concurrency = 2, .stop_on_error = false}); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == Kind::failed); + Void::Testing::expect_eq(result.error().chunks_total, std::size_t{14}); + Void::Testing::expect_eq(result.error().chunks_started, std::size_t{14}); + Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{1}); + Void::Testing::expect(result.error().first_failed_chunk == std::optional{2}); + Void::Testing::expect_eq(what(result.error().first_exception), std::string{"seven"}); + // The throwing chunk [6, 9) stops at index 7; every other chunk ran fully. + Void::Testing::expect_eq(calls.load(), kCount - 1); + } +} + +Void::Testing::Test parallel_for_bounded_signed_and_unsigned_ranges() +{ + ThreadPool pool{3}; + + // Signed range crossing zero. + { + std::atomic sum{0}; + std::atomic calls{0}; + const auto result = parallel_for( + -5, 5, [&](int i) { sum.fetch_add(i); calls.fetch_add(1); }, pool, + ParallelForOptions{.grain = 4}); + Void::Testing::expect(result.has_value()); + Void::Testing::expect_eq(calls.load(), 10); + Void::Testing::expect_eq(sum.load(), -5); + } + + // The whole int8 range: 255 indices computed in the unsigned type. + { + std::vector> hits(256); + const auto result = parallel_for( + std::int8_t{-128}, std::int8_t{127}, + [&](std::int8_t i) { hits[static_cast(i + 128)].fetch_add(1); }, pool, + ParallelForOptions{.grain = 7}); + Void::Testing::expect(result.has_value()); + int wrong = 0; + for (std::size_t k = 0; k < 255; ++k) { + if (hits[k].load() != 1) { + ++wrong; + } + } + Void::Testing::expect_eq(wrong, 0); + Void::Testing::expect_eq(hits[255].load(), 0); + } + + // Top of the unsigned range, and a grain larger than the range. + { + std::atomic calls{0}; + std::atomic sum{0}; + const std::uint64_t top = std::numeric_limits::max(); + const auto result = parallel_for( + top - 3, top, [&](std::uint64_t i) { calls.fetch_add(1); sum.fetch_add(top - i); }, pool, + ParallelForOptions{.grain = 1000}); + Void::Testing::expect(result.has_value()); + Void::Testing::expect_eq(calls.load(), 3); + Void::Testing::expect_eq(sum.load(), std::uint64_t{3 + 2 + 1}); + } +} + +Void::Testing::Test parallel_for_bounded_stop_joins_started_no_new_chunks() +{ + ThreadPool pool{2}; + + // One runner: chunk 0 requests stop; no later chunk may start. + { + std::stop_source stop; + std::atomic started{0}; + std::atomic finished{0}; + const auto result = parallel_for( + 0, 100, + [&](int i) { + started.fetch_add(1); + if (i == 0) { + stop.request_stop(); + std::this_thread::sleep_for(5ms); + } + finished.fetch_add(1); + }, + pool, ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop = stop.get_token()}); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == Kind::stopped); + Void::Testing::expect_eq(result.error().chunks_total, std::size_t{100}); + Void::Testing::expect_eq(result.error().chunks_started, std::size_t{1}); + Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{0}); + Void::Testing::expect(!result.error().first_failed_chunk.has_value()); + // The started chunk was joined (ran to completion) and nothing else ran. + Void::Testing::expect_eq(started.load(), 1); + Void::Testing::expect_eq(finished.load(), 1); + } + + // Two runners: every chunk that started finishes; the rest never start. + { + std::stop_source stop; + std::atomic started{0}; + std::atomic finished{0}; + const auto result = parallel_for( + 0, 1000, + [&](int i) { + started.fetch_add(1); + if (i == 3) { + stop.request_stop(); + } + std::this_thread::sleep_for(1ms); + finished.fetch_add(1); + }, + pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop = stop.get_token()}); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == Kind::stopped); + Void::Testing::expect_eq(started.load(), finished.load()); + Void::Testing::expect_eq(result.error().chunks_started, static_cast(started.load())); + Void::Testing::expect(result.error().chunks_started < std::size_t{1000}); + Void::Testing::expect(result.error().chunks_started >= std::size_t{4}); + } + + // Stop requested before the call: nothing runs. + { + std::stop_source stop; + stop.request_stop(); + std::atomic calls{0}; + const auto result = parallel_for( + 0, 10, [&](int) { calls.fetch_add(1); }, pool, + ParallelForOptions{.stop = stop.get_token()}); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == Kind::stopped); + Void::Testing::expect_eq(result.error().chunks_started, std::size_t{0}); + Void::Testing::expect_eq(result.error().chunks_total, std::size_t{10}); + Void::Testing::expect_eq(calls.load(), 0); + } + + // A stop that arrives once every chunk has started is not an error. + { + std::stop_source stop; + std::atomic calls{0}; + const auto result = parallel_for( + 0, 4, + [&](int i) { + calls.fetch_add(1); + if (i == 3) { + stop.request_stop(); + } + }, + pool, ParallelForOptions{.max_concurrency = 1, .stop = stop.get_token()}); + Void::Testing::expect(result.has_value()); + Void::Testing::expect_eq(calls.load(), 4); + } +} + +Void::Testing::Test parallel_for_bounded_errors_join_all_lowest_index_reported() +{ + ThreadPool pool{2}; + + // stop_on_error == false: every chunk runs; the lowest failed chunk wins + // even though higher chunks fail first or concurrently. + { + std::atomic calls{0}; + const auto result = parallel_for( + 0, 10, + [&](int i) { + calls.fetch_add(1); + if (i == 5 || i == 2 || i == 8) { + throw std::runtime_error{"chunk " + std::to_string(i)}; + } + }, + pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop_on_error = false}); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == Kind::failed); + Void::Testing::expect_eq(calls.load(), 10); + Void::Testing::expect_eq(result.error().chunks_total, std::size_t{10}); + Void::Testing::expect_eq(result.error().chunks_started, std::size_t{10}); + Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{3}); + Void::Testing::expect(result.error().first_failed_chunk == std::optional{2}); + Void::Testing::expect_eq(what(result.error().first_exception), std::string{"chunk 2"}); + } + + // stop_on_error == true: chunk 1 fails first, chunk 0 (already started) + // fails afterwards. The caller joins both and reports the LOWER chunk; no + // new chunk starts after the first failure. + { + std::atomic chunk_one_failed{false}; + std::atomic chunk_zero_timed_out{false}; + std::atomic calls{0}; + const auto result = parallel_for( + 0, 10, + [&](int i) { + calls.fetch_add(1); + if (i == 0) { + const auto end = std::chrono::steady_clock::now() + 5s; + while (!chunk_one_failed.load() && std::chrono::steady_clock::now() < end) { + std::this_thread::yield(); + } + if (!chunk_one_failed.load()) { + chunk_zero_timed_out.store(true); + } + throw std::runtime_error{"zero"}; + } + if (i == 1) { + chunk_one_failed.store(true); + throw std::runtime_error{"one"}; + } + }, + pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop_on_error = true}); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(!chunk_zero_timed_out.load()); + Void::Testing::expect(result.error().kind == Kind::failed); + Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{2}); + Void::Testing::expect(result.error().first_failed_chunk == std::optional{0}); + Void::Testing::expect_eq(what(result.error().first_exception), std::string{"zero"}); + // Only the two started chunks ran. + Void::Testing::expect_eq(result.error().chunks_started, std::size_t{2}); + Void::Testing::expect_eq(calls.load(), 2); + } + + // `failed` outranks `stopped`. + { + std::stop_source stop; + const auto result = parallel_for( + 0, 10, + [&](int i) { + if (i == 0) { + stop.request_stop(); + throw std::runtime_error{"failed and stopped"}; + } + }, + pool, ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop = stop.get_token()}); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == Kind::failed); + Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{1}); + } + + // A non-std exception is preserved as an exception_ptr. + { + const auto result = parallel_for( + 0, 3, [](int i) { if (i == 1) { throw 42; } }, pool, + ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop_on_error = false}); + Void::Testing::require(!result.has_value()); + bool is_int = false; + try { + std::rethrow_exception(result.error().first_exception); + } catch (int value) { + is_int = value == 42; + } catch (...) { + } + Void::Testing::expect(is_int); + } +} + +Void::Testing::Test parallel_for_bounded_zero_grain_invalid() +{ + ThreadPool pool{2}; + std::atomic calls{0}; + + const auto zero_grain = parallel_for( + 0, 10, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{.grain = 0}); + Void::Testing::require(!zero_grain.has_value()); + Void::Testing::expect(zero_grain.error().kind == Kind::invalid_argument); + Void::Testing::expect_eq(zero_grain.error().chunks_total, std::size_t{0}); + Void::Testing::expect_eq(zero_grain.error().chunks_started, std::size_t{0}); + Void::Testing::expect_eq(calls.load(), 0); + + // An empty or reversed range is a success and runs nothing. + const auto empty = parallel_for(5, 5, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{}); + Void::Testing::expect(empty.has_value()); + const auto reversed = parallel_for(9, 2, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{}); + Void::Testing::expect(reversed.has_value()); + Void::Testing::expect_eq(calls.load(), 0); + + // The legacy overloads are unchanged. + std::atomic legacy{0}; + parallel_for(0, 5, [&](int) { legacy.fetch_add(1); }, pool); + Void::Testing::expect_eq(legacy.load(), 5); +} + +Void::Testing::Test parallel_for_bounded_rejected_pool_runs_inline() +{ + Gate gate; + std::atomic blocker_started{false}; + { + // One worker, queue bound 1: occupy the worker and fill the queue so + // every try_submit is rejected. + ThreadPool pool{1, 1}; + GateGuard guard{gate}; + auto blocker = pool.submit([&] { + blocker_started.store(true); + gate.wait(); + }); + Void::Testing::require(wait_until([&] { return blocker_started.load(); })); + auto filler = pool.submit([] {}); + Void::Testing::expect_eq(pool.pending_count(), std::size_t{1}); + + std::vector owner(20); + std::atomic calls{0}; + const auto caller = std::this_thread::get_id(); + const auto result = parallel_for( + 0, 20, + [&](int i) { + owner[static_cast(i)] = std::this_thread::get_id(); + calls.fetch_add(1); + }, + pool, ParallelForOptions{.grain = 4, .max_concurrency = 3}); + Void::Testing::expect(result.has_value()); + Void::Testing::expect_eq(calls.load(), 20); + int off_caller = 0; + for (const auto& id : owner) { + if (id != caller) { + ++off_caller; + } + } + // The pool rejected the runner, so the calling thread ran everything. + Void::Testing::expect_eq(off_caller, 0); + Void::Testing::expect(pool.stats().rejected >= 1); + + gate.open(); + blocker.get(); + filler.get(); + } + + // Partial rejection: the caller joins the accepted runner but the bound + // on running chunks still holds (accepted runners + the caller). + { + ThreadPool pool{1, 1}; + ConcurrencyMeter meter; + std::vector> hits(30); + const auto result = parallel_for( + 0, 30, + [&](int i) { + meter.enter(); + hits[static_cast(i)].fetch_add(1); + std::this_thread::sleep_for(1ms); + meter.leave(); + }, + pool, ParallelForOptions{.grain = 1, .max_concurrency = 2}); + Void::Testing::expect(result.has_value()); + int wrong = 0; + for (const auto& hit : hits) { + if (hit.load() != 1) { + ++wrong; + } + } + Void::Testing::expect_eq(wrong, 0); + Void::Testing::expect(meter.peak.load() <= 2); + } +} + +Void::Testing::Test parallel_for_bounded_waits_all_submitted_runners() +{ + Gate gate; + std::atomic blocker_started{false}; + std::atomic returned{false}; + std::atomic calls{0}; + std::optional> outcome; + std::stop_source stop; + + ThreadPool pool{1}; + GateGuard guard{gate}; + auto blocker = pool.submit([&] { + blocker_started.store(true); + gate.wait(); + }); + Void::Testing::require(wait_until([&] { return blocker_started.load(); })); + + // Three runners queue behind the blocker and cannot start. The caller must + // still wait for every one of them, also after a stop was requested. + std::thread caller([&] { + outcome = parallel_for( + 0, 100, [&](int) { calls.fetch_add(1); }, pool, + ParallelForOptions{.grain = 10, .max_concurrency = 3, .stop = stop.get_token()}); + returned.store(true); + }); + ThreadJoiner joiner{gate, caller}; + Void::Testing::expect(wait_until([&] { return pool.pending_count() == 3; })); + stop.request_stop(); + std::this_thread::sleep_for(60ms); + Void::Testing::expect(!returned.load()); + + gate.open(); + caller.join(); + blocker.get(); + Void::Testing::expect(returned.load()); + Void::Testing::require(outcome.has_value()); + Void::Testing::require(!outcome->has_value()); + Void::Testing::expect((*outcome).error().kind == Kind::stopped); + // The runners found the stop request: no chunk ever started. + Void::Testing::expect_eq((*outcome).error().chunks_started, std::size_t{0}); + Void::Testing::expect_eq((*outcome).error().chunks_total, std::size_t{10}); + Void::Testing::expect_eq(calls.load(), 0); + // Every runner future was waited for: the queue is empty. + Void::Testing::expect_eq(pool.pending_count(), std::size_t{0}); +} + +Void::Testing::Test legacy_parallel_for_exception_joins_all() +{ + ThreadPool pool{2}; + std::atomic finished{0}; + bool caught = false; + try { + parallel_for(0, 8, [&](int i) { + if (i == 0) { + throw std::runtime_error{"first"}; + } + std::this_thread::sleep_for(25ms); + finished.fetch_add(1); + }, pool); + } catch (const std::runtime_error& error) { + caught = std::string{error.what()} == "first"; + } + Void::Testing::expect(caught); + // The exception surfaced only after every other task finished; none is + // still running against this stack. + Void::Testing::expect_eq(finished.load(), 7); + + // With several failures the first (lowest index) is rethrown. + std::atomic second_finished{0}; + std::string message; + try { + parallel_for(0, 6, [&](int i) { + std::this_thread::sleep_for(5ms); + second_finished.fetch_add(1); + if (i == 1 || i == 3) { + throw std::runtime_error{"error " + std::to_string(i)}; + } + }, pool); + } catch (const std::runtime_error& error) { + message = error.what(); + } + Void::Testing::expect_eq(message, std::string{"error 1"}); + Void::Testing::expect_eq(second_finished.load(), 6); +} diff --git a/tests/standalone/Async/ThreadExecutor.cpp b/tests/standalone/Async/ThreadExecutor.cpp new file mode 100644 index 0000000..995911e --- /dev/null +++ b/tests/standalone/Async/ThreadExecutor.cpp @@ -0,0 +1,881 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Every assertion runs on the test thread: jobs executed by workers only touch +// atomics or mutex-guarded containers (the assertion context is thread_local). + +namespace +{ + +using namespace Void::Async; +using namespace std::chrono_literals; + +// Detached, self-destroying coroutine frame created suspended: a handle to +// post. A job that is never resumed must be destroy()ed by its creator. +struct Job { + struct promise_type { + Job get_return_object() noexcept + { + return Job{std::coroutine_handle::from_promise(*this)}; + } + std::suspend_always initial_suspend() noexcept { return {}; } + std::suspend_never final_suspend() noexcept { return {}; } + void return_void() noexcept {} + void unhandled_exception() noexcept { std::terminate(); } + }; + + std::coroutine_handle handle{}; +}; + +Job make_job(std::function body) +{ + body(); + co_return; +} + +class Gate +{ +public: + void open() + { + { + std::lock_guard lk{mu_}; + open_ = true; + } + cv_.notify_all(); + } + + void wait() + { + std::unique_lock lk{mu_}; + cv_.wait(lk, [this] { return open_; }); + } + +private: + std::mutex mu_{}; + std::condition_variable cv_{}; + bool open_{false}; +}; + +template +bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms) +{ + const auto end = std::chrono::steady_clock::now() + timeout; + while (!pred()) { + if (std::chrono::steady_clock::now() >= end) { + return false; + } + std::this_thread::sleep_for(1ms); + } + return true; +} + +// Owns the executor and a gate. The destructor opens the gate FIRST, so a +// failed assertion can never leave a blocker job hanging ~ThreadExecutor, then +// destroys the executor (which joins) and finally the gate. +struct Fixture { + Gate gate{}; + std::unique_ptr exec{}; + + Fixture(std::size_t workers, std::size_t max_admitted, bool start = true) + { + auto created = ThreadExecutor::create( + ThreadExecutorOptions{.workers = workers, .max_admitted = max_admitted}); + Void::Testing::require(created.has_value()); + exec = std::move(*created); + if (start) { + Void::Testing::require(exec->start().has_value()); + } + } + + ~Fixture() { gate.open(); } + + Fixture(const Fixture&) = delete; + Fixture& operator=(const Fixture&) = delete; + + ThreadExecutor& operator*() { return *exec; } + ThreadExecutor* operator->() { return exec.get(); } +}; + +// A job that occupies a worker until the fixture gate opens. +Job make_blocker(Fixture& fx, std::atomic& running) +{ + return make_job([&fx, &running] { + running.store(true, std::memory_order_release); + fx.gate.wait(); + }); +} + +std::optional async_code(const Void::Result::Error& error) +{ + if (error.code().domain != Void::Result::kAsyncErrorDomain) { + return std::nullopt; + } + return static_cast(error.code().value); +} + +Void::Coro::Task bump_task(std::atomic* counter) +{ + counter->fetch_add(1, std::memory_order_relaxed); + co_return; +} + +// Posts `job` through one of the four admission paths (retrying while the +// bound is full). Returns false (and destroys the frame) on an unexpected +// rejection. Assertion free: runs on poster threads. +bool post_one(ThreadExecutor& exec, int kind, Job& job) +{ + switch (kind) { + case 0: + for (;;) { + const auto admitted = exec.try_post(job.handle); + if (admitted.has_value()) { + return true; + } + if (admitted.error() != AdmissionError::overloaded) { + job.handle.destroy(); + return false; + } + std::this_thread::yield(); + } + case 1: + exec.post(job.handle); + return true; + case 2: + exec.post_completion(job.handle); + return true; + default: + for (;;) { + const auto reserved = exec.try_reserve_slot(); + if (reserved.has_value()) { + break; + } + if (reserved.error() != AdmissionError::overloaded) { + job.handle.destroy(); + return false; + } + std::this_thread::yield(); + } + exec.commit_reserved(job.handle); + return true; + } +} + +} // namespace + +Void::Testing::Test thread_executor_create_starts_no_threads() +{ + std::atomic hook_calls{0}; + std::atomic ran{0}; + auto created = ThreadExecutor::create(ThreadExecutorOptions{ + .workers = 2, + .max_admitted = 4, + .before_worker_start = [&hook_calls](std::size_t) -> Void::Result::Result { + hook_calls.fetch_add(1); + return {}; + }}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + + // No thread (and no hook call) exists yet. + Void::Testing::expect_eq(hook_calls.load(), 0); + Void::Testing::expect(exec.idle()); + Void::Testing::expect_eq(exec.admitted(), std::size_t{0}); + Void::Testing::expect(exec.supports_reservation()); + Void::Testing::expect(exec.has_background_workers()); + + // Admission before start() queues normally and nothing runs. + auto job = make_job([&ran] { ran.fetch_add(1); }); + Void::Testing::require(exec.try_post(job.handle).has_value()); + Void::Testing::expect_eq(exec.admitted(), std::size_t{1}); + std::this_thread::sleep_for(30ms); + Void::Testing::expect_eq(ran.load(), 0); + Void::Testing::expect_eq(exec.stats().queued, std::size_t{1}); + Void::Testing::expect(!exec.idle()); + + Void::Testing::require(exec.start().has_value()); + Void::Testing::expect_eq(hook_calls.load(), 2); + Void::Testing::expect(wait_until([&] { return ran.load() == 1; })); + Void::Testing::require(exec.join().has_value()); + + // create() validates its options. + const auto zero_workers = ThreadExecutor::create(ThreadExecutorOptions{.workers = 0}); + Void::Testing::require(!zero_workers.has_value()); + Void::Testing::expect(async_code(zero_workers.error()) == AsyncErrorCode::invalid_argument); + const auto zero_bound = ThreadExecutor::create(ThreadExecutorOptions{.max_admitted = 0}); + Void::Testing::require(!zero_bound.has_value()); + Void::Testing::expect(async_code(zero_bound.error()) == AsyncErrorCode::invalid_argument); +} + +Void::Testing::Test thread_executor_bound_includes_running_work() +{ + std::atomic blocker_running{false}; + std::atomic ran{0}; + Fixture exec{1, 2}; + + auto blocker = make_blocker(exec, blocker_running); + Void::Testing::require(exec->try_post(blocker.handle).has_value()); + Void::Testing::require(wait_until([&] { return blocker_running.load(); })); + // The running blocker keeps its slot. + Void::Testing::expect_eq(exec->admitted(), std::size_t{1}); + Void::Testing::expect_eq(exec->stats().running, std::size_t{1}); + + auto queued = make_job([&ran] { ran.fetch_add(1); }); + Void::Testing::require(exec->try_post(queued.handle).has_value()); + Void::Testing::expect_eq(exec->admitted(), std::size_t{2}); + + // running (1) + queued (1) == max_admitted (2): the next one is rejected. + auto rejected = make_job([&ran] { ran.fetch_add(100); }); + const auto overloaded = exec->try_post(rejected.handle); + Void::Testing::expect(!overloaded.has_value()); + Void::Testing::expect(overloaded.error() == AdmissionError::overloaded); + rejected.handle.destroy(); + Void::Testing::expect_eq(exec->stats().rejected, std::uint64_t{1}); + Void::Testing::expect_eq(exec->stats().queued, std::size_t{1}); + + // Legacy post() never rejects: it may exceed the bound and is counted. + auto legacy = make_job([&ran] { ran.fetch_add(10); }); + exec->post(legacy.handle); + Void::Testing::expect_eq(exec->admitted(), std::size_t{3}); + Void::Testing::expect_eq(exec->stats().legacy_posts, std::uint64_t{1}); + + // A null handle is invalid for try_post. + const auto null_handle = exec->try_post({}); + Void::Testing::expect(!null_handle.has_value()); + Void::Testing::expect(null_handle.error() == AdmissionError::invalid_argument); + + exec.gate.open(); + Void::Testing::expect(wait_until([&] { return ran.load() == 11 && exec->idle(); })); + // A slot is free again once the work returned. + auto again = make_job([&ran] { ran.fetch_add(1000); }); + Void::Testing::require(exec->try_post(again.handle).has_value()); + Void::Testing::expect(wait_until([&] { return ran.load() == 1011; })); + Void::Testing::expect(wait_until([&] { return exec->admitted() == 0; })); +} + +Void::Testing::Test thread_executor_reservation_with_task_scope_preserves_task() +{ + std::atomic blocker_running{false}; + std::atomic ran{0}; + Fixture exec{1, 1}; + TaskScope scope{*exec, TaskScopeOptions{.max_tasks = 8}}; + + auto blocker = make_blocker(exec, blocker_running); + Void::Testing::require(exec->try_post(blocker.handle).has_value()); + Void::Testing::require(wait_until([&] { return blocker_running.load(); })); + + // The bound is full: TaskScope's reserve-then-transfer is rejected and the + // caller still owns the task. + auto preserved = bump_task(&ran); + const auto rejected = scope.spawn(std::move(preserved)); + Void::Testing::require(!rejected.has_value()); + Void::Testing::expect(rejected.error() == AdmissionError::overloaded); + Void::Testing::expect(static_cast(preserved.handle())); + Void::Testing::expect(!preserved.done()); + // The failed reservation did not leak a slot. + Void::Testing::expect_eq(exec->admitted(), std::size_t{1}); + Void::Testing::expect_eq(ran.load(), 0); + + exec.gate.open(); + Void::Testing::require(wait_until([&] { return exec->admitted() == 0; })); + const auto accepted = scope.spawn(std::move(preserved)); + Void::Testing::require(accepted.has_value()); + Void::Testing::require(scope.join_blocking().has_value()); + Void::Testing::expect_eq(ran.load(), 1); + Void::Testing::expect(wait_until([&] { return exec->admitted() == 0; })); +} + +Void::Testing::Test thread_executor_completion_lane_bypasses_full_normal_lane() +{ + std::atomic blocker_running{false}; + std::atomic completion_ran{0}; + Fixture exec{1, 1}; + + auto blocker = make_blocker(exec, blocker_running); + Void::Testing::require(exec->try_post(blocker.handle).has_value()); + Void::Testing::require(wait_until([&] { return blocker_running.load(); })); + + // The normal lane is full ... + auto normal = make_job([] {}); + const auto overloaded = exec->try_post(normal.handle); + Void::Testing::expect(!overloaded.has_value()); + normal.handle.destroy(); + const auto reserve_rejected = exec->try_reserve_slot(); + Void::Testing::expect(!reserve_rejected.has_value()); + Void::Testing::expect(reserve_rejected.error() == AdmissionError::overloaded); + + // ... but the completion lane still accepts and is not part of the bound. + auto completion = make_job([&completion_ran] { completion_ran.fetch_add(1); }); + exec->post_completion(completion.handle); + Void::Testing::expect_eq(exec->stats().completion_queued, std::size_t{1}); + Void::Testing::expect_eq(exec->admitted(), std::size_t{1}); + + exec.gate.open(); + Void::Testing::expect(wait_until([&] { return completion_ran.load() == 1; })); + Void::Testing::expect(wait_until([&] { return exec->idle(); })); +} + +Void::Testing::Test thread_executor_close_rejects_normal_drains_completion() +{ + std::atomic blocker_running{false}; + std::atomic order_counter{0}; + std::atomic completion_order{-1}; + std::atomic legacy_order{-1}; + std::atomic queued_order{-1}; + Fixture exec{1, 8}; + + auto blocker = make_blocker(exec, blocker_running); + Void::Testing::require(exec->try_post(blocker.handle).has_value()); + Void::Testing::require(wait_until([&] { return blocker_running.load(); })); + + auto queued = make_job([&] { queued_order.store(order_counter.fetch_add(1)); }); + Void::Testing::require(exec->try_post(queued.handle).has_value()); + + exec->close(); + + // Normal admission is closed. + auto refused = make_job([] {}); + const auto stopped_post = exec->try_post(refused.handle); + Void::Testing::expect(!stopped_post.has_value()); + Void::Testing::expect(stopped_post.error() == AdmissionError::stopped); + refused.handle.destroy(); + const auto stopped_reserve = exec->try_reserve_slot(); + Void::Testing::expect(!stopped_reserve.has_value()); + Void::Testing::expect(stopped_reserve.error() == AdmissionError::stopped); + + // A legacy post after close() is redirected to the completion lane and + // counted; post_completion keeps working. + auto legacy = make_job([&] { legacy_order.store(order_counter.fetch_add(1)); }); + exec->post(legacy.handle); + auto completion = make_job([&] { completion_order.store(order_counter.fetch_add(1)); }); + exec->post_completion(completion.handle); + Void::Testing::expect_eq(exec->stats().completion_queued, std::size_t{2}); + Void::Testing::expect_eq(exec->stats().legacy_posts, std::uint64_t{1}); + + exec.gate.open(); + Void::Testing::require(exec->join().has_value()); + // Both lanes drained; the completion lane (legacy post, then the explicit + // completion) runs before the queued normal handle. + Void::Testing::expect_eq(legacy_order.load(), 0); + Void::Testing::expect_eq(completion_order.load(), 1); + Void::Testing::expect_eq(queued_order.load(), 2); + Void::Testing::expect(exec->idle()); +} + +Void::Testing::Test thread_executor_join_self_join_on_worker() +{ + std::atomic code{-1}; + std::atomic observed_executor_thread{false}; + Fixture exec{1, 4}; + + auto job = make_job([&] { + const auto joined = exec->join(); + code.store(joined.has_value() ? 0 : static_cast(joined.error().code().value)); + observed_executor_thread.store(exec->is_executor_thread()); + }); + Void::Testing::require(exec->try_post(job.handle).has_value()); + Void::Testing::require(wait_until([&] { return code.load() != -1; })); + Void::Testing::expect_eq(code.load(), static_cast(AsyncErrorCode::self_join)); + Void::Testing::expect(observed_executor_thread.load()); + // A normal join from a non-executor thread still works afterwards. + Void::Testing::expect(!exec->is_executor_thread()); + Void::Testing::require(exec->join().has_value()); +} + +Void::Testing::Test thread_executor_partial_start_failure_joins_started() +{ + std::atomic hook_calls{0}; + std::atomic fail{true}; + std::atomic ran{0}; + auto created = ThreadExecutor::create(ThreadExecutorOptions{ + .workers = 3, + .max_admitted = 8, + .before_worker_start = [&](std::size_t index) -> Void::Result::Result { + hook_calls.fetch_add(1); + if (fail.load() && index == 2) { + return std::unexpected{make_async_error( + AsyncErrorCode::limit_exceeded, "injected thread start failure")}; + } + return {}; + }}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + + // Work admitted before start() must not run on workers of a failed start. + auto job = make_job([&ran] { ran.fetch_add(1); }); + Void::Testing::require(exec.try_post(job.handle).has_value()); + + const auto failed = exec.start(); + Void::Testing::require(!failed.has_value()); + Void::Testing::expect(async_code(failed.error()) == AsyncErrorCode::limit_exceeded); + Void::Testing::expect_eq(hook_calls.load(), 3); + std::this_thread::sleep_for(30ms); + Void::Testing::expect_eq(ran.load(), 0); + Void::Testing::expect_eq(exec.stats().queued, std::size_t{1}); + Void::Testing::expect_eq(exec.stats().running, std::size_t{0}); + + // The two workers that were already started were joined: a retry starts a + // full set again. + fail.store(false); + Void::Testing::require(exec.start().has_value()); + Void::Testing::expect_eq(hook_calls.load(), 6); + Void::Testing::expect(wait_until([&] { return ran.load() == 1; })); + Void::Testing::require(exec.join().has_value()); +} + +Void::Testing::Test thread_executor_system_error_path_shared_with_hook() +{ + std::atomic mode{0}; // 0 = ok, 1 = system_error, 2 = runtime_error + std::atomic hook_calls{0}; + std::atomic ran{0}; + auto created = ThreadExecutor::create(ThreadExecutorOptions{ + .workers = 3, + .max_admitted = 8, + .before_worker_start = [&](std::size_t index) -> Void::Result::Result { + hook_calls.fetch_add(1); + if (index == 1 && mode.load() == 1) { + throw std::system_error{std::make_error_code(std::errc::resource_unavailable_try_again), + "injected thread creation failure"}; + } + if (index == 1 && mode.load() == 2) { + throw std::runtime_error{"injected hook failure"}; + } + return {}; + }}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + + auto job = make_job([&ran] { ran.fetch_add(1); }); + Void::Testing::require(exec.try_post(job.handle).has_value()); + + // std::system_error: same cleanup path as a hook error, system code kept. + mode.store(1); + const auto sys_failed = exec.start(); + Void::Testing::require(!sys_failed.has_value()); + Void::Testing::expect(async_code(sys_failed.error()) == AsyncErrorCode::backend_error); + Void::Testing::expect(sys_failed.error().system_code() == + std::make_error_code(std::errc::resource_unavailable_try_again)); + Void::Testing::expect_eq(hook_calls.load(), 2); + + // Any other exception takes the same path, without a system code. + mode.store(2); + const auto other_failed = exec.start(); + Void::Testing::require(!other_failed.has_value()); + Void::Testing::expect(async_code(other_failed.error()) == AsyncErrorCode::backend_error); + Void::Testing::expect(!other_failed.error().system_code()); + Void::Testing::expect_eq(hook_calls.load(), 4); + Void::Testing::expect_eq(ran.load(), 0); + + mode.store(0); + Void::Testing::require(exec.start().has_value()); + Void::Testing::expect(wait_until([&] { return ran.load() == 1; })); + Void::Testing::require(exec.join().has_value()); +} + +namespace +{ + +Void::Coro::Task hop_task(ThreadExecutor* exec, + std::atomic* stage, + std::atomic* on_executor_before, + std::atomic* on_executor_after, + std::atomic* status_code) +{ + on_executor_before->store(exec->is_executor_thread()); + stage->store(1); + co_await schedule_on(*exec); + stage->store(2); + const auto status = co_await schedule_on(*exec, OperationOptions{}); + status_code->store(status.has_value() ? 0 : static_cast(status.error().code().value)); + on_executor_after->store(exec->is_executor_thread()); + stage->store(3); +} + +} // namespace + +Void::Testing::Test thread_executor_legacy_post_spawn_schedule_on_compat() +{ + std::atomic stage{0}; + std::atomic before{false}; + std::atomic after{false}; + std::atomic status_code{-1}; + std::atomic blocker_running{false}; + std::atomic ran{0}; + Fixture exec{1, 2}; + + // spawn() and schedule_on(executor) use the legacy post(): never rejected. + // spawn() is called from the single worker itself, not from a foreign + // thread: ThreadSanitizer reports a data race in Executor.hpp's spawn_impl + // (lines 292/296) when spawn() is called from a thread other than the + // executor's workers onto a multi-worker executor. That behaviour is + // independent of ThreadExecutor and is escalated to the root; it is not + // covered here. + auto spawner = make_job([&] { + spawn(*exec, hop_task(exec.exec.get(), &stage, &before, &after, &status_code)); + }); + Void::Testing::require(exec->try_post(spawner.handle).has_value()); + Void::Testing::require(wait_until([&] { return stage.load() == 3; })); + Void::Testing::expect(before.load()); + Void::Testing::expect(after.load()); + Void::Testing::expect_eq(status_code.load(), 0); + Void::Testing::expect(exec->stats().legacy_posts >= 2); + + // A full bound (running + queued == 2) rejects try_post (and the status + // schedule_on built on it) but never the legacy post. + auto blocker = make_blocker(exec, blocker_running); + Void::Testing::require(exec->try_post(blocker.handle).has_value()); + Void::Testing::require(wait_until([&] { return blocker_running.load(); })); + auto filler = make_job([&ran] { ran.fetch_add(1); }); + Void::Testing::require(exec->try_post(filler.handle).has_value()); + auto rejected = make_job([] {}); + Void::Testing::expect(!exec->try_post(rejected.handle).has_value()); + rejected.handle.destroy(); + + const std::uint64_t legacy_before = exec->stats().legacy_posts; + auto j1 = make_job([&ran] { ran.fetch_add(1); }); + auto j2 = make_job([&ran] { ran.fetch_add(1); }); + exec->post(j1.handle); + exec->post(j2.handle); + Void::Testing::expect_eq(exec->stats().legacy_posts, legacy_before + 2); + Void::Testing::expect_eq(exec->admitted(), std::size_t{4}); + exec.gate.open(); + Void::Testing::expect(wait_until([&] { return ran.load() == 3; })); + Void::Testing::require(exec->join().has_value()); +} + +Void::Testing::Test thread_executor_inline_after_join_counted() +{ + std::atomic ran{0}; + std::mutex mu; + std::vector threads; + std::atomic guarded{false}; + auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 4}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + Void::Testing::require(exec.start().has_value()); + + auto before_join = make_job([&] { ran.fetch_add(1); }); + Void::Testing::require(exec.try_post(before_join.handle).has_value()); + Void::Testing::require(exec.join().has_value()); + Void::Testing::expect_eq(ran.load(), 1); + Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{0}); + + // After join, posts resume inline on the caller (counted), never dropped. + const auto caller = std::this_thread::get_id(); + auto record = [&] { + std::lock_guard lk{mu}; + threads.push_back(std::this_thread::get_id()); + guarded.store(exec.is_executor_thread()); + }; + auto j1 = make_job(record); + exec.post(j1.handle); + auto j2 = make_job(record); + exec.post_completion(j2.handle); + Void::Testing::expect_eq(threads.size(), std::size_t{2}); + Void::Testing::expect(threads[0] == caller); + Void::Testing::expect(threads[1] == caller); + // The inline resume runs under ExecutorThreadGuard. + Void::Testing::expect(guarded.load()); + Void::Testing::expect(!exec.is_executor_thread()); + Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{2}); + Void::Testing::expect_eq(exec.stats().legacy_posts, std::uint64_t{1}); + + // Normal admission stays closed after join, and join/start are repeatable + // or rejected. + auto refused = make_job([] {}); + const auto stopped = exec.try_post(refused.handle); + Void::Testing::expect(!stopped.has_value()); + Void::Testing::expect(stopped.error() == AdmissionError::stopped); + refused.handle.destroy(); + const auto reserved = exec.try_reserve_slot(); + Void::Testing::expect(!reserved.has_value()); + Void::Testing::expect(reserved.error() == AdmissionError::stopped); + Void::Testing::require(exec.join().has_value()); + const auto restarted = exec.start(); + Void::Testing::expect(!restarted.has_value()); + Void::Testing::expect(exec.idle()); +} + +Void::Testing::Test thread_executor_join_without_start_drains_inline() +{ + std::mutex mu; + std::vector order; + std::atomic all_on_caller{true}; + const auto caller = std::this_thread::get_id(); + auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 8}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + + auto make_marker = [&](int id) { + return make_job([&, id] { + std::lock_guard lk{mu}; + order.push_back(id); + if (std::this_thread::get_id() != caller) { + all_on_caller.store(false); + } + }); + }; + auto n1 = make_marker(1); + auto n2 = make_marker(2); + auto c1 = make_marker(10); + auto n3 = make_marker(3); + Void::Testing::require(exec.try_post(n1.handle).has_value()); + Void::Testing::require(exec.try_post(n2.handle).has_value()); + exec.post_completion(c1.handle); + exec.post(n3.handle); + Void::Testing::expect_eq(exec.admitted(), std::size_t{3}); + + // No worker exists: join() drains both lanes inline, never waits. + Void::Testing::require(exec.join().has_value()); + Void::Testing::expect(all_on_caller.load()); + // Completion lane first, then the normal lane in FIFO order. + Void::Testing::expect_eq(order.size(), std::size_t{4}); + if (order.size() == 4) { + Void::Testing::expect_eq(order[0], 10); + Void::Testing::expect_eq(order[1], 1); + Void::Testing::expect_eq(order[2], 2); + Void::Testing::expect_eq(order[3], 3); + } + Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{4}); + Void::Testing::expect(exec.idle()); + Void::Testing::expect(!exec.start().has_value()); + + // The destructor of a never-started executor also drains inline. + std::atomic ran{0}; + { + auto second = ThreadExecutor::create(); + Void::Testing::require(second.has_value()); + auto pending = make_job([&ran] { ran.fetch_add(1); }); + Void::Testing::require((*second)->try_post(pending.handle).has_value()); + } + Void::Testing::expect_eq(ran.load(), 1); +} + +Void::Testing::Test thread_executor_start_twice_and_after_close_invalid() +{ + auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 4}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + Void::Testing::require(exec.start().has_value()); + const auto twice = exec.start(); + Void::Testing::require(!twice.has_value()); + Void::Testing::expect(async_code(twice.error()) == AsyncErrorCode::invalid_argument); + + auto closed_created = ThreadExecutor::create(); + Void::Testing::require(closed_created.has_value()); + auto& closed = **closed_created; + closed.close(); + const auto after_close = closed.start(); + Void::Testing::require(!after_close.has_value()); + Void::Testing::expect(async_code(after_close.error()) == AsyncErrorCode::invalid_argument); + + Void::Testing::require(exec.join().has_value()); + const auto after_join = exec.start(); + Void::Testing::require(!after_join.has_value()); + Void::Testing::expect(async_code(after_join.error()) == AsyncErrorCode::invalid_argument); +} + +Void::Testing::Test thread_executor_reservation_across_close_binding() +{ + std::atomic ran{0}; + std::atomic joined{false}; + std::atomic join_ok{false}; + std::atomic job_on_joiner{false}; + + // (1) Workers running: a reservation taken before close() stays binding. + { + auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + Void::Testing::require(exec.start().has_value()); + Void::Testing::require(exec.try_reserve_slot().has_value()); + // A reserved slot counts in admitted() and in the bound. + Void::Testing::expect_eq(exec.admitted(), std::size_t{1}); + Void::Testing::require(exec.try_reserve_slot().has_value()); + const auto full = exec.try_reserve_slot(); + Void::Testing::expect(!full.has_value()); + Void::Testing::expect(full.error() == AdmissionError::overloaded); + exec.release_reserved(); + Void::Testing::expect_eq(exec.admitted(), std::size_t{1}); + + exec.close(); + const auto after_close = exec.try_reserve_slot(); + Void::Testing::expect(!after_close.has_value()); + Void::Testing::expect(after_close.error() == AdmissionError::stopped); + Void::Testing::expect_eq(exec.admitted(), std::size_t{1}); + + std::thread joiner([&] { + join_ok.store(exec.join().has_value()); + joined.store(true); + }); + // join() also waits until no reservation is outstanding. + std::this_thread::sleep_for(60ms); + Void::Testing::expect(!joined.load()); + + auto job = make_job([&ran] { ran.fetch_add(1); }); + exec.commit_reserved(job.handle); // binding: enqueues normally after close() + joiner.join(); + Void::Testing::expect(joined.load()); + Void::Testing::expect(join_ok.load()); + Void::Testing::expect_eq(ran.load(), 1); + Void::Testing::expect_eq(exec.admitted(), std::size_t{0}); + } + + // (2) A released reservation also lets join() finish (no workers: the + // joiner drains inline, but still waits for the reservation). + { + joined.store(false); + join_ok.store(false); + auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + Void::Testing::require(exec.try_reserve_slot().has_value()); + std::thread joiner([&] { + join_ok.store(exec.join().has_value()); + joined.store(true); + }); + std::this_thread::sleep_for(60ms); + Void::Testing::expect(!joined.load()); + exec.release_reserved(); + joiner.join(); + Void::Testing::expect(joined.load()); + Void::Testing::expect(join_ok.load()); + } + + // (3) No workers + a commit after join() began: the committed handle is + // drained by the joining thread. + { + joined.store(false); + join_ok.store(false); + const auto joiner_id = std::make_shared>(); + auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + Void::Testing::require(exec.try_reserve_slot().has_value()); + std::thread joiner([&] { + joiner_id->store(std::this_thread::get_id()); + join_ok.store(exec.join().has_value()); + joined.store(true); + }); + std::this_thread::sleep_for(60ms); + auto job = make_job([&] { + job_on_joiner.store(std::this_thread::get_id() == joiner_id->load()); + ran.fetch_add(1); + }); + exec.commit_reserved(job.handle); + joiner.join(); + Void::Testing::expect(join_ok.load()); + Void::Testing::expect(job_on_joiner.load()); + Void::Testing::expect_eq(ran.load(), 2); + } +} + +Void::Testing::Test thread_executor_stress_tsan() +{ + constexpr int kPosters = 4; + constexpr int kPerPoster = 1200; + std::atomic accepted{0}; + std::atomic executed{0}; + std::atomic posted_failed_unexpectedly{0}; + std::atomic snapshot_inconsistent{0}; + std::vector posters; + + auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 3, .max_admitted = 32}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + Void::Testing::require(exec.start().has_value()); + + for (int p = 0; p < kPosters; ++p) { + posters.emplace_back([&, p] { + for (int k = 0; k < kPerPoster; ++k) { + const int kind = (p + k) % 4; + auto job = make_job([&executed] { executed.fetch_add(1, std::memory_order_relaxed); }); + if (post_one(exec, kind, job)) { + accepted.fetch_add(1, std::memory_order_relaxed); + } else { + posted_failed_unexpectedly.fetch_add(1); + } + if ((k & 63) == 0) { + const auto stats = exec.stats(); + if (stats.running > 3) { + snapshot_inconsistent.fetch_add(1); + } + (void)exec.idle(); + } + } + }); + } + for (auto& poster : posters) { + poster.join(); + } + // Repeated and concurrent join(): every caller returns success and the + // worker threads are joined exactly once. + std::atomic concurrent_join_failures{0}; + std::vector joiners; + for (int j = 0; j < 3; ++j) { + joiners.emplace_back([&] { + if (!exec.join().has_value()) { + concurrent_join_failures.fetch_add(1); + } + }); + } + const bool main_join_ok = exec.join().has_value(); + for (auto& joiner : joiners) { + joiner.join(); + } + Void::Testing::require(main_join_ok); + Void::Testing::expect_eq(concurrent_join_failures.load(), 0); + + Void::Testing::expect_eq(posted_failed_unexpectedly.load(), std::uint64_t{0}); + Void::Testing::expect_eq(snapshot_inconsistent.load(), std::uint64_t{0}); + Void::Testing::expect_eq(accepted.load(), static_cast(kPosters) * kPerPoster); + Void::Testing::expect_eq(executed.load(), accepted.load()); + Void::Testing::expect(exec.idle()); + Void::Testing::expect_eq(exec.admitted(), std::size_t{0}); +} + +// Regression (W11): spawn() from a foreign thread onto a multi-worker executor +// must not race with the worker that resumes and destroys the detached frame. +namespace +{ +Void::Coro::Task spawn_bump(std::atomic* counter) +{ + counter->fetch_add(1, std::memory_order_relaxed); + co_return; +} +} // namespace + +Void::Testing::Test thread_executor_spawn_from_foreign_thread_multi_worker_tsan() +{ + auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 4, .max_admitted = 64}); + Void::Testing::require(created.has_value()); + auto& exec = **created; + Void::Testing::require(exec.start().has_value()); + + constexpr int kSpawns = 2000; + std::atomic counter{0}; + for (int i = 0; i < kSpawns; ++i) { + spawn(exec, spawn_bump(&counter)); + } + Void::Testing::require(exec.join().has_value()); + Void::Testing::expect_eq(counter.load(std::memory_order_relaxed), kSpawns); +}