From c75056fe07078a6704721a390a49ea86578f6bec Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 03:48:55 +0300 Subject: [PATCH] feat(Async): add OperationOptions, OperationState, ResumeTicket, TaskScope, and bounded executor tickets (M-ASYNC-02, M-ASYNC-03) --- include/Void/Async/Detail/Types.hpp | 138 ++++ include/Void/Async/Executor.hpp | 250 ++++++- include/Void/Async/Operation.hpp | 410 +++++++++++ include/Void/Async/TaskScope.hpp | 798 ++++++++++++++++++++++ src/Async/module.cmake | 4 +- tests/standalone/Async/OperationScope.cpp | 633 +++++++++++++++++ 6 files changed, 2229 insertions(+), 4 deletions(-) create mode 100644 include/Void/Async/Detail/Types.hpp create mode 100644 include/Void/Async/Operation.hpp create mode 100644 include/Void/Async/TaskScope.hpp create mode 100644 tests/standalone/Async/OperationScope.cpp diff --git a/include/Void/Async/Detail/Types.hpp b/include/Void/Async/Detail/Types.hpp new file mode 100644 index 0000000..d5512a3 --- /dev/null +++ b/include/Void/Async/Detail/Types.hpp @@ -0,0 +1,138 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::Async +{ + +enum class AdmissionError { + overloaded, + stopped, + deadline_expired, + invalid_argument, + self_join +}; + +enum class AsyncErrorCode : std::int32_t { + none = 0, + cancelled = 1, + timeout = 2, + overloaded = 3, + stopped = 4, + invalid_argument = 5, + self_join = 6, + backend_error = 7, + limit_exceeded = 8 +}; + +enum class DomainOutcomeKind { + pending, + succeeded, + not_committed, + unknown, + failed, + cancelled +}; + +struct OperationOptions { + std::stop_token stop{}; + std::optional deadline{}; +}; + +[[nodiscard]] inline bool is_deadline_expired( + const OperationOptions& options, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()) noexcept +{ + return options.deadline.has_value() && clock.now() >= *options.deadline; +} + +[[nodiscard]] inline Void::Result::Error + make_async_error(AsyncErrorCode code, std::string message = {}) +{ + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case AsyncErrorCode::none: + kind = ErrorKind::internal; + break; + case AsyncErrorCode::cancelled: + case AsyncErrorCode::stopped: + kind = ErrorKind::cancelled; + break; + case AsyncErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case AsyncErrorCode::overloaded: + kind = ErrorKind::overloaded; + break; + case AsyncErrorCode::invalid_argument: + kind = ErrorKind::invalid_argument; + break; + case AsyncErrorCode::self_join: + kind = ErrorKind::conflict; + break; + case AsyncErrorCode::backend_error: + kind = ErrorKind::internal; + break; + case AsyncErrorCode::limit_exceeded: + kind = ErrorKind::exhausted; + break; + } + + const ErrorCode domain_code{ + Void::Result::kAsyncErrorDomain, + static_cast(code)}; + return Error{kind, std::move(message), domain_code}; +} + +[[nodiscard]] inline Void::Result::Error + make_async_error(AdmissionError adm, std::string message = {}) +{ + AsyncErrorCode code = AsyncErrorCode::invalid_argument; + switch (adm) { + case AdmissionError::overloaded: + code = AsyncErrorCode::overloaded; + if (message.empty()) { + message = "Async executor or scope capacity exceeded"; + } + break; + case AdmissionError::stopped: + code = AsyncErrorCode::stopped; + if (message.empty()) { + message = "Async executor or scope is stopped"; + } + break; + case AdmissionError::deadline_expired: + code = AsyncErrorCode::timeout; + if (message.empty()) { + message = "Async operation deadline expired"; + } + break; + case AdmissionError::invalid_argument: + code = AsyncErrorCode::invalid_argument; + if (message.empty()) { + message = "Invalid async admission argument"; + } + break; + case AdmissionError::self_join: + code = AsyncErrorCode::self_join; + if (message.empty()) { + message = "Cannot blocking-join from inside the active executor thread"; + } + break; + } + return make_async_error(code, std::move(message)); +} + +} // namespace Void::Async \ No newline at end of file diff --git a/include/Void/Async/Executor.hpp b/include/Void/Async/Executor.hpp index f3866ba..e8d6497 100644 --- a/include/Void/Async/Executor.hpp +++ b/include/Void/Async/Executor.hpp @@ -1,15 +1,56 @@ #pragma once +#include #include #include +#include #include #include #include +#include +#include namespace Void::Async { +class Executor; + +namespace detail +{ +struct ActiveExecutorFrame { + const Executor* exec{nullptr}; + const ActiveExecutorFrame* prev{nullptr}; + + [[nodiscard]] static inline const ActiveExecutorFrame*& head() noexcept + { + thread_local const ActiveExecutorFrame* slot = nullptr; + return slot; + } +}; + +class ExecutorThreadGuard +{ +public: + explicit ExecutorThreadGuard(const Executor* exec) noexcept + : frame_{exec, ActiveExecutorFrame::head()} + { + ActiveExecutorFrame::head() = &frame_; + } + + ~ExecutorThreadGuard() + { + ActiveExecutorFrame::head() = frame_.prev; + } + + ExecutorThreadGuard(const ExecutorThreadGuard&) = delete; + ExecutorThreadGuard& operator=(const ExecutorThreadGuard&) = delete; + +private: + ActiveExecutorFrame frame_; +}; +} // namespace detail + // ── Executor ────────────────────────────────────────────────────────────────── // Minimal scheduling interface bridging Coro::Task to a driving thread. // post() must be safe to call from any thread. @@ -21,6 +62,54 @@ public: // Schedule a coroutine for resumption on this executor. Thread-safe. virtual void post(std::coroutine_handle<> handle) = 0; + + // Bounded non-blocking admission. Subclasses may override with queue caps. + [[nodiscard]] virtual std::expected + try_post(std::coroutine_handle<> handle) + { + if (!handle) { + return std::unexpected{AdmissionError::invalid_argument}; + } + post(handle); + return {}; + } + + // Reserved lane for resuming waiting/joining continuations without normal + // work-queue backpressure rejections. + virtual void post_completion(std::coroutine_handle<> handle) + { + if (handle) { + post(handle); + } + } + + [[nodiscard]] virtual bool is_executor_thread() const noexcept + { + for (const auto* f = detail::ActiveExecutorFrame::head(); + f != nullptr; + f = f->prev) { + if (f->exec == this) { + return true; + } + } + return false; + } + + [[nodiscard]] virtual bool supports_reservation() const noexcept { return false; } + + [[nodiscard]] virtual std::expected try_reserve_slot() + { + return {}; + } + + virtual void commit_reserved(std::coroutine_handle<> handle) + { + post_completion(handle); + } + + virtual void release_reserved() noexcept {} + + [[nodiscard]] virtual bool has_background_workers() const noexcept { return true; } }; // ── ManualExecutor ──────────────────────────────────────────────────────────── @@ -31,18 +120,111 @@ public: class ManualExecutor final : public Executor { public: + explicit ManualExecutor(std::size_t max_queue = 0) noexcept + : max_queue_(max_queue) + { + } + void post(std::coroutine_handle<> handle) override { + if (!handle) { + return; + } + pending_normal_.fetch_add(1, std::memory_order_acq_rel); queue_.push(handle); } + [[nodiscard]] std::expected + try_post(std::coroutine_handle<> handle) override + { + if (!handle) { + return std::unexpected{AdmissionError::invalid_argument}; + } + auto reserved = try_reserve_slot(); + if (!reserved.has_value()) { + return reserved; + } + queue_.push(handle); + return {}; + } + + void post_completion(std::coroutine_handle<> handle) override + { + if (!handle) { + return; + } + completion_queue_.push(handle); + } + + [[nodiscard]] bool supports_reservation() const noexcept override { return true; } + + [[nodiscard]] std::expected try_reserve_slot() override + { + std::size_t cur = pending_normal_.load(std::memory_order_acquire); + for (;;) { + if (!accepting_.load(std::memory_order_acquire)) { + return std::unexpected{AdmissionError::stopped}; + } + if (max_queue_ != 0 && cur >= max_queue_) { + return std::unexpected{AdmissionError::overloaded}; + } + if (pending_normal_.compare_exchange_weak( + cur, + cur + 1, + std::memory_order_acq_rel, + std::memory_order_acquire)) { + return {}; + } + } + } + + void commit_reserved(std::coroutine_handle<> handle) override + { + if (!handle) { + pending_normal_.fetch_sub(1, std::memory_order_acq_rel); + return; + } + queue_.push(handle); + } + + void release_reserved() noexcept override + { + pending_normal_.fetch_sub(1, std::memory_order_acq_rel); + } + + [[nodiscard]] bool has_background_workers() const noexcept override { return false; } + + void shutdown() noexcept + { + accepting_.store(false, std::memory_order_release); + } + + [[nodiscard]] bool is_accepting() const noexcept + { + return accepting_.load(std::memory_order_acquire); + } + + [[nodiscard]] std::size_t pending_normal() const noexcept + { + return pending_normal_.load(std::memory_order_acquire); + } + + [[nodiscard]] std::size_t max_queue() const noexcept { return max_queue_; } + // Resume one pending coroutine. Returns false if none was pending. bool run_one() { + if (auto c = completion_queue_.try_pop(); c.has_value()) { + detail::ExecutorThreadGuard guard{this}; + c->resume(); + return true; + } auto h = queue_.try_pop(); if (!h) { return false; } + pending_normal_.fetch_sub(1, std::memory_order_acq_rel); + detail::ExecutorThreadGuard guard{this}; h->resume(); return true; } @@ -58,10 +240,17 @@ public: return count; } - [[nodiscard]] bool empty() const noexcept { return queue_.empty(); } + [[nodiscard]] bool empty() const noexcept + { + return completion_queue_.empty() && queue_.empty(); + } private: - MpscQueue> queue_; + std::size_t max_queue_{0}; + std::atomic pending_normal_{0}; + std::atomic accepting_{true}; + MpscQueue> queue_{}; + MpscQueue> completion_queue_{}; }; // ── schedule_on ─────────────────────────────────────────────────────────────── @@ -112,4 +301,61 @@ inline void spawn(Executor& executor, Coro::Task task) Detail::spawn_impl(executor, std::move(task)); } +struct ScheduleStatusAwaiter { + Executor& executor; + OperationOptions options{}; + const Void::Time::MonotonicClock* clock{&Void::Time::SystemMonotonicClock::instance()}; + Void::Result::Result pre_outcome{}; + + [[nodiscard]] bool await_ready() noexcept + { + if (options.stop.stop_requested()) { + pre_outcome = std::unexpected{make_async_error( + AsyncErrorCode::cancelled, "schedule_on cancelled before scheduling")}; + return true; + } + if (is_deadline_expired(options, *clock)) { + pre_outcome = std::unexpected{make_async_error( + AsyncErrorCode::timeout, "schedule_on deadline expired before scheduling")}; + return true; + } + return false; + } + + [[nodiscard]] bool await_suspend(std::coroutine_handle<> handle) + { + const auto post_res = executor.try_post(handle); + if (!post_res.has_value()) { + pre_outcome = std::unexpected{make_async_error( + post_res.error(), "schedule_on rejected by executor")}; + return false; + } + return true; + } + + [[nodiscard]] Void::Result::Result await_resume() noexcept + { + if (!pre_outcome.has_value()) { + return pre_outcome; + } + if (options.stop.stop_requested()) { + return std::unexpected{make_async_error( + AsyncErrorCode::cancelled, "schedule_on cancelled before execution")}; + } + if (is_deadline_expired(options, *clock)) { + return std::unexpected{make_async_error( + AsyncErrorCode::timeout, "schedule_on deadline expired before execution")}; + } + return {}; + } +}; + +[[nodiscard]] inline ScheduleStatusAwaiter schedule_on( + Executor& executor, + OperationOptions options, + const Void::Time::MonotonicClock& clock = Void::Time::SystemMonotonicClock::instance()) noexcept +{ + return ScheduleStatusAwaiter{executor, std::move(options), &clock}; +} + } // namespace Void::Async diff --git a/include/Void/Async/Operation.hpp b/include/Void/Async/Operation.hpp new file mode 100644 index 0000000..81bbc02 --- /dev/null +++ b/include/Void/Async/Operation.hpp @@ -0,0 +1,410 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Async +{ + +enum class StopBehavior { + notify_only, + settle_cancelled +}; + +// Move-only, single-delivery handle for resuming a suspended continuation on +// its bound completion lane (or inline when no executor was supplied). +class ResumeTicket +{ +public: + ResumeTicket() noexcept = default; + + explicit ResumeTicket(std::coroutine_handle<> handle, + Executor* executor = nullptr) noexcept + : handle_(handle) + , executor_(executor) + { + } + + ResumeTicket(ResumeTicket&& other) noexcept + : handle_(std::exchange(other.handle_, {})) + , executor_(std::exchange(other.executor_, nullptr)) + { + } + + ResumeTicket& operator=(ResumeTicket&& other) noexcept + { + if (this != &other) { + handle_ = std::exchange(other.handle_, {}); + executor_ = std::exchange(other.executor_, nullptr); + } + return *this; + } + + ResumeTicket(const ResumeTicket&) = delete; + ResumeTicket& operator=(const ResumeTicket&) = delete; + + [[nodiscard]] explicit operator bool() const noexcept + { + return static_cast(handle_); + } + + [[nodiscard]] std::coroutine_handle<> handle() const noexcept { return handle_; } + [[nodiscard]] Executor* executor() const noexcept { return executor_; } + + void dispatch() + { + auto h = std::exchange(handle_, {}); + auto* ex = std::exchange(executor_, nullptr); + if (!h) { + return; + } + if (ex != nullptr) { + ex->post_completion(h); + } else { + h.resume(); + } + } + + void resume_inline() + { + auto h = std::exchange(handle_, {}); + executor_ = nullptr; + if (h) { + h.resume(); + } + } + + [[nodiscard]] std::coroutine_handle<> release() noexcept + { + executor_ = nullptr; + return std::exchange(handle_, {}); + } + +private: + std::coroutine_handle<> handle_{}; + Executor* executor_{nullptr}; +}; + +// Thread-safe shared operation state arbitrating backend work refs, external +// stop intent, single-winner outcome selection, and post-backend-release +// continuation delivery. +template +class OperationState : public std::enable_shared_from_this> +{ +public: + using OutcomeType = std::expected; + + struct Awaitable { + std::shared_ptr> state; + Executor* resume_executor{nullptr}; + + [[nodiscard]] bool await_ready() const noexcept { return false; } + + [[nodiscard]] bool await_suspend(std::coroutine_handle<> handle) noexcept + { + return state->try_arm_suspend(handle, resume_executor); + } + + [[nodiscard]] OutcomeType await_resume() + { + return state->take_result(); + } + }; + + [[nodiscard]] static std::shared_ptr> create( + OperationOptions options = {}, + Executor* resume_executor = nullptr, + StopBehavior stop_behavior = StopBehavior::notify_only) + { + auto ptr = std::shared_ptr>( + new OperationState(resume_executor, stop_behavior, options.deadline)); + if (options.stop.stop_possible()) { + ptr->stop_cb_.emplace(options.stop, StopForwarder{ptr.get()}); + } + return ptr; + } + + OperationState(const OperationState&) = delete; + OperationState& operator=(const OperationState&) = delete; + OperationState(OperationState&&) = delete; + OperationState& operator=(OperationState&&) = delete; + + [[nodiscard]] std::stop_token stop_token() const noexcept + { + return stop_source_.get_token(); + } + + [[nodiscard]] bool stop_requested() const noexcept + { + return (sync_.load(std::memory_order_acquire) & kStopRequestedFlag) != 0 || + stop_source_.stop_requested(); + } + + [[nodiscard]] const std::optional& + deadline() const noexcept + { + return deadline_; + } + + [[nodiscard]] bool is_deadline_expired( + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()) const noexcept + { + return deadline_.has_value() && clock.now() >= *deadline_; + } + + bool request_stop() noexcept + { + sync_.fetch_or(kStopRequestedFlag, std::memory_order_acq_rel); + const bool triggered = stop_source_.request_stop(); + if (stop_behavior_ == StopBehavior::settle_cancelled) { + if (auto ticket = try_commit_cancelled("Operation cancelled"); + ticket.has_value()) { + ticket->dispatch(); + } + } + return triggered; + } + + void acquire_backend_ref() noexcept + { + sync_.fetch_add(kRefStep, std::memory_order_acq_rel); + } + + [[nodiscard]] std::optional release_backend_ref() noexcept + { + const std::uint64_t prev = sync_.fetch_sub(kRefStep, std::memory_order_acq_rel); + const std::uint64_t cur = prev - kRefStep; + if ((cur >> kRefShift) != 0) { + return std::nullopt; + } + return maybe_claim_ticket(); + } + + void release_backend_ref_and_dispatch() + { + if (auto ticket = release_backend_ref(); ticket.has_value()) { + ticket->dispatch(); + } + } + + template + requires (!std::is_void_v) + [[nodiscard]] std::optional try_commit_value(U value) + { + return settle_with(DomainOutcomeKind::succeeded, + [&](std::optional& slot) { + slot.emplace(std::in_place, std::move(value)); + }); + } + + template + requires (std::is_void_v) + [[nodiscard]] std::optional try_commit_value() + { + return settle_with(DomainOutcomeKind::succeeded, + [](std::optional& slot) { + slot.emplace(); + }); + } + + [[nodiscard]] std::optional try_commit_error( + Void::Result::Error err, + DomainOutcomeKind kind = DomainOutcomeKind::failed) + { + return settle_with(kind, [&](std::optional& slot) { + slot.emplace(std::unexpected{std::move(err)}); + }); + } + + [[nodiscard]] std::optional try_commit_not_committed( + std::string message = "Operation stopped before commit") + { + return try_commit_error( + make_async_error(AsyncErrorCode::cancelled, std::move(message)), + DomainOutcomeKind::not_committed); + } + + [[nodiscard]] std::optional try_commit_unknown( + std::string message = "Commit state unknown after backend failure") + { + return try_commit_error( + make_async_error(AsyncErrorCode::backend_error, std::move(message)), + DomainOutcomeKind::unknown); + } + + [[nodiscard]] std::optional try_commit_cancelled( + std::string message = "Operation cancelled") + { + return try_commit_error( + make_async_error(AsyncErrorCode::cancelled, std::move(message)), + DomainOutcomeKind::cancelled); + } + + [[nodiscard]] std::optional try_commit_timeout( + std::string message = "Operation deadline expired") + { + return try_commit_error( + make_async_error(AsyncErrorCode::timeout, std::move(message)), + DomainOutcomeKind::failed); + } + + [[nodiscard]] bool try_arm_suspend(std::coroutine_handle<> continuation, + Executor* resume_exec = nullptr) noexcept + { + continuation_ = continuation; + if (resume_exec != nullptr) { + resume_executor_ = resume_exec; + } + + std::uint64_t cur = sync_.load(std::memory_order_acquire); + for (;;) { + if ((cur & kSettledFlag) != 0 && + (cur >> kRefShift) == 0 && + (cur & kDispatchedFlag) == 0) { + if (sync_.compare_exchange_weak( + cur, + cur | kSuspendedFlag | kDispatchedFlag, + std::memory_order_acq_rel, + std::memory_order_acquire)) { + continuation_ = {}; + resume_executor_ = nullptr; + return false; + } + } else { + if (sync_.compare_exchange_weak( + cur, + cur | kSuspendedFlag, + std::memory_order_acq_rel, + std::memory_order_acquire)) { + return true; + } + } + } + } + + [[nodiscard]] bool is_settled() const noexcept + { + return (sync_.load(std::memory_order_acquire) & kSettledFlag) != 0; + } + + [[nodiscard]] std::uint64_t backend_ref_count() const noexcept + { + return sync_.load(std::memory_order_acquire) >> kRefShift; + } + + [[nodiscard]] DomainOutcomeKind outcome_kind() const noexcept + { + return domain_outcome_.load(std::memory_order_acquire); + } + + [[nodiscard]] OutcomeType take_result() + { + // Acquire on sync_ ensures visibility of the winner's write to outcome_. + (void)sync_.load(std::memory_order_acquire); + if (!outcome_.has_value()) { + return std::unexpected{make_async_error( + AsyncErrorCode::backend_error, + "OperationState result accessed before settlement")}; + } + return std::move(*outcome_); + } + + [[nodiscard]] Awaitable awaitable(Executor* resume_exec = nullptr) noexcept + { + return Awaitable{this->shared_from_this(), resume_exec}; + } + + [[nodiscard]] Awaitable operator co_await() noexcept + { + return awaitable(nullptr); + } + +private: + static constexpr std::uint64_t kSettledFlag = 1ULL << 0; + static constexpr std::uint64_t kSuspendedFlag = 1ULL << 1; + static constexpr std::uint64_t kDispatchedFlag = 1ULL << 2; + static constexpr std::uint64_t kStopRequestedFlag = 1ULL << 3; + static constexpr std::uint64_t kRefShift = 4; + static constexpr std::uint64_t kRefStep = 1ULL << kRefShift; + + struct StopForwarder { + OperationState* self{nullptr}; + void operator()() const noexcept + { + if (self != nullptr) { + self->request_stop(); + } + } + }; + + OperationState(Executor* resume_executor, + StopBehavior stop_behavior, + std::optional deadline) noexcept + : stop_behavior_(stop_behavior) + , deadline_(deadline) + , resume_executor_(resume_executor) + { + } + + template + [[nodiscard]] std::optional settle_with( + DomainOutcomeKind kind, InitFn&& init_fn) + { + if (outcome_claimed_.exchange(true, std::memory_order_acq_rel)) { + return std::nullopt; + } + init_fn(outcome_); + domain_outcome_.store(kind, std::memory_order_release); + sync_.fetch_or(kSettledFlag, std::memory_order_acq_rel); + return maybe_claim_ticket(); + } + + [[nodiscard]] std::optional maybe_claim_ticket() noexcept + { + std::uint64_t cur = sync_.load(std::memory_order_acquire); + for (;;) { + if ((cur & kSettledFlag) == 0 || + (cur & kSuspendedFlag) == 0 || + (cur & kDispatchedFlag) != 0 || + (cur >> kRefShift) != 0) { + return std::nullopt; + } + if (sync_.compare_exchange_weak( + cur, + cur | kDispatchedFlag, + std::memory_order_acq_rel, + std::memory_order_acquire)) { + return ResumeTicket{ + std::exchange(continuation_, {}), + std::exchange(resume_executor_, nullptr)}; + } + } + } + + std::stop_source stop_source_{}; + StopBehavior stop_behavior_{StopBehavior::notify_only}; + std::optional deadline_{}; + std::atomic sync_{0}; + std::atomic outcome_claimed_{false}; + std::atomic domain_outcome_{DomainOutcomeKind::pending}; + std::optional outcome_{}; + std::coroutine_handle<> continuation_{}; + Executor* resume_executor_{nullptr}; + // MUST stay LAST: destroyed first in ~OperationState() to synchronize any + // in-flight external stop callback before members above are torn down. + std::optional> stop_cb_{}; +}; + +} // namespace Void::Async \ No newline at end of file diff --git a/include/Void/Async/TaskScope.hpp b/include/Void/Async/TaskScope.hpp new file mode 100644 index 0000000..4e2c834 --- /dev/null +++ b/include/Void/Async/TaskScope.hpp @@ -0,0 +1,798 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Async +{ + +struct TaskScopeOptions { + std::size_t max_tasks{1024}; + std::stop_token parent_stop{}; + bool stop_on_first_error{true}; + + [[nodiscard]] static constexpr TaskScopeOptions unlimited( + std::stop_token parent_stop = {}, + bool stop_on_first_error = true) noexcept + { + return TaskScopeOptions{ + std::numeric_limits::max(), + parent_stop, + stop_on_first_error}; + } +}; + +namespace detail +{ + +class ScopeControl; + +class ChildTaskControl : public std::enable_shared_from_this +{ +public: + explicit ChildTaskControl(Executor& executor) noexcept + : executor_(executor) + { + } + + ChildTaskControl(const ChildTaskControl&) = delete; + ChildTaskControl& operator=(const ChildTaskControl&) = delete; + + [[nodiscard]] std::stop_token stop_token() const noexcept + { + return stop_source_.get_token(); + } + + bool request_stop() noexcept + { + return stop_source_.request_stop(); + } + + void attach_stops(std::stop_token scope_stop, std::stop_token option_stop) + { + if (scope_stop.stop_possible()) { + scope_stop_cb_.emplace(scope_stop, StopForwarder{this}); + } + if (option_stop.stop_possible()) { + option_stop_cb_.emplace(option_stop, StopForwarder{this}); + } + } + + void set_error(Void::Result::Error err) + { + std::lock_guard lk{mu_}; + error_ = std::move(err); + } + + void mark_finished() + { + std::coroutine_handle<> waiter{}; + { + std::lock_guard lk{mu_}; + finished_ = true; + waiter = std::exchange(async_waiter_, {}); + } + cv_.notify_all(); + if (waiter) { + executor_.post_completion(waiter); + } + } + + [[nodiscard]] bool done() const + { + std::lock_guard lk{mu_}; + return finished_; + } + + [[nodiscard]] bool try_register_waiter(std::coroutine_handle<> waiter) + { + std::lock_guard lk{mu_}; + if (finished_) { + return false; + } + async_waiter_ = waiter; + return true; + } + + [[nodiscard]] Void::Result::Result take_outcome() const + { + std::lock_guard lk{mu_}; + if (error_.has_value()) { + return std::unexpected{*error_}; + } + return {}; + } + + [[nodiscard]] Void::Result::Result join_blocking() + { + if (executor_.is_executor_thread()) { + return std::unexpected{make_async_error( + AdmissionError::self_join, + "JoinHandle::join_blocking called on active executor thread")}; + } + std::unique_lock lk{mu_}; + cv_.wait(lk, [this] { return finished_; }); + if (error_.has_value()) { + return std::unexpected{*error_}; + } + return {}; + } + +private: + struct StopForwarder { + ChildTaskControl* self{nullptr}; + void operator()() const noexcept + { + if (self != nullptr) { + self->request_stop(); + } + } + }; + + Executor& executor_; + std::stop_source stop_source_{}; + mutable std::mutex mu_{}; + std::condition_variable cv_{}; + bool finished_{false}; + std::optional error_{}; + std::coroutine_handle<> async_waiter_{}; + // MUST stay LAST so stop callbacks synchronize before members destruct. + std::optional> scope_stop_cb_{}; + std::optional> option_stop_cb_{}; +}; + +class ScopeControl : public std::enable_shared_from_this +{ +public: + [[nodiscard]] static std::shared_ptr create( + Executor& executor, TaskScopeOptions options) + { + auto ptr = std::shared_ptr( + new ScopeControl(executor, options)); + if (options.parent_stop.stop_possible()) { + ptr->parent_stop_cb_.emplace(options.parent_stop, StopForwarder{ptr.get()}); + } + return ptr; + } + + ScopeControl(const ScopeControl&) = delete; + ScopeControl& operator=(const ScopeControl&) = delete; + + [[nodiscard]] Executor& executor() noexcept { return executor_; } + + [[nodiscard]] std::stop_token stop_token() const noexcept + { + return stop_source_.get_token(); + } + + bool request_stop() noexcept + { + return stop_source_.request_stop(); + } + + void close() noexcept + { + std::lock_guard lk{mu_}; + closed_ = true; + } + + [[nodiscard]] std::expected try_reserve( + const OperationOptions& op, + const Void::Time::MonotonicClock& clock) + { + if (max_tasks_ == 0) { + return std::unexpected{AdmissionError::invalid_argument}; + } + if (op.stop.stop_requested()) { + return std::unexpected{AdmissionError::stopped}; + } + if (is_deadline_expired(op, clock)) { + return std::unexpected{AdmissionError::deadline_expired}; + } + std::lock_guard lk{mu_}; + if (closed_ || stop_source_.stop_requested()) { + return std::unexpected{AdmissionError::stopped}; + } + if (active_tasks_ >= max_tasks_) { + return std::unexpected{AdmissionError::overloaded}; + } + ++active_tasks_; + return {}; + } + + void release_reservation() + { + on_task_finished(); + } + + void record_exception(std::exception_ptr ex, std::string_view what) + { + bool trigger_stop = false; + { + std::lock_guard lk{mu_}; + ++failure_count_; + if (!first_exception_) { + first_exception_ = ex; + first_error_ = make_async_error( + AsyncErrorCode::backend_error, + what.empty() + ? std::string{"Unhandled exception in TaskScope task"} + : std::string{what}); + trigger_stop = stop_on_first_error_; + } + } + if (trigger_stop) { + request_stop(); + } + } + + void on_task_finished() + { + std::coroutine_handle<> waiter{}; + bool notify = false; + { + std::lock_guard lk{mu_}; + --active_tasks_; + if (active_tasks_ == 0) { + notify = true; + waiter = std::exchange(async_join_waiter_, {}); + } + } + if (notify) { + cv_.notify_all(); + if (waiter) { + executor_.post_completion(waiter); + } + } + } + + [[nodiscard]] bool try_begin_async_join(std::coroutine_handle<> waiter) + { + std::lock_guard lk{mu_}; + closed_ = true; + if (active_tasks_ == 0) { + return false; + } + async_join_waiter_ = waiter; + return true; + } + + [[nodiscard]] Void::Result::Result finish_outcome() const + { + std::lock_guard lk{mu_}; + if (first_error_.has_value()) { + return std::unexpected{*first_error_}; + } + return {}; + } + + [[nodiscard]] Void::Result::Result join_blocking() + { + if (executor_.is_executor_thread()) { + return std::unexpected{make_async_error( + AdmissionError::self_join, + "TaskScope::join_blocking called on active executor thread")}; + } + std::unique_lock lk{mu_}; + closed_ = true; + cv_.wait(lk, [this] { return active_tasks_ == 0; }); + if (first_error_.has_value()) { + return std::unexpected{*first_error_}; + } + return {}; + } + + [[nodiscard]] std::size_t active_count() const + { + std::lock_guard lk{mu_}; + return active_tasks_; + } + + [[nodiscard]] std::size_t failure_count() const + { + std::lock_guard lk{mu_}; + return failure_count_; + } + + [[nodiscard]] bool has_exception() const + { + std::lock_guard lk{mu_}; + return static_cast(first_exception_); + } + + [[nodiscard]] std::exception_ptr first_exception() const + { + std::lock_guard lk{mu_}; + return first_exception_; + } + +private: + struct StopForwarder { + ScopeControl* self{nullptr}; + void operator()() const noexcept + { + if (self != nullptr) { + self->request_stop(); + } + } + }; + + ScopeControl(Executor& executor, TaskScopeOptions options) noexcept + : executor_(executor) + , max_tasks_(options.max_tasks) + , stop_on_first_error_(options.stop_on_first_error) + { + } + + Executor& executor_; + std::size_t max_tasks_{1024}; + bool stop_on_first_error_{true}; + std::stop_source stop_source_{}; + mutable std::mutex mu_{}; + std::condition_variable cv_{}; + std::size_t active_tasks_{0}; + std::size_t failure_count_{0}; + bool closed_{false}; + std::exception_ptr first_exception_{}; + std::optional first_error_{}; + std::coroutine_handle<> async_join_waiter_{}; + // MUST stay LAST: waits for any active parent stop callback on destruction. + std::optional> parent_stop_cb_{}; +}; + +struct TakePromiseTaskTag {}; +struct GetScopePtrTag {}; +struct GetChildPtrTag {}; + +struct ScopeRunner { + struct promise_type { + std::shared_ptr scope{}; + std::shared_ptr child{}; + std::optional> task{}; + + ScopeRunner get_return_object() noexcept + { + return ScopeRunner{ + std::coroutine_handle::from_promise(*this)}; + } + + std::suspend_always initial_suspend() noexcept { return {}; } + + struct FinalAwaiter { + bool await_ready() const noexcept { return false; } + void await_suspend(std::coroutine_handle h) noexcept + { + auto sc = std::move(h.promise().scope); + auto ch = std::move(h.promise().child); + h.promise().task.reset(); + // Destroy the coroutine frame completely before decrementing active + // task counters or waking any join waiter. + h.destroy(); + if (ch) { + ch->mark_finished(); + } + if (sc) { + sc->on_task_finished(); + } + } + void await_resume() const noexcept {} + }; + + FinalAwaiter final_suspend() noexcept { return {}; } + void return_void() noexcept {} + void unhandled_exception() noexcept {} + + auto await_transform(TakePromiseTaskTag) noexcept + { + struct Awaiter { + promise_type* p; + bool await_ready() const noexcept { return true; } + void await_suspend(std::coroutine_handle<>) noexcept {} + Coro::Task await_resume() noexcept + { + auto t = std::move(*p->task); + p->task.reset(); + return t; + } + }; + return Awaiter{this}; + } + + auto await_transform(GetScopePtrTag) noexcept + { + struct Awaiter { + promise_type* p; + bool await_ready() const noexcept { return true; } + void await_suspend(std::coroutine_handle<>) noexcept {} + std::shared_ptr await_resume() noexcept + { + return p->scope; + } + }; + return Awaiter{this}; + } + + auto await_transform(GetChildPtrTag) noexcept + { + struct Awaiter { + promise_type* p; + bool await_ready() const noexcept { return true; } + void await_suspend(std::coroutine_handle<>) noexcept {} + std::shared_ptr await_resume() noexcept + { + return p->child; + } + }; + return Awaiter{this}; + } + + template + decltype(auto) await_transform(A&& awaitable) noexcept + { + return std::forward(awaitable); + } + }; + + std::coroutine_handle handle{}; +}; + +inline ScopeRunner make_scope_runner() +{ + auto task = co_await TakePromiseTaskTag{}; + auto scope = co_await GetScopePtrTag{}; + auto child = co_await GetChildPtrTag{}; + try { + co_await std::move(task); + } catch (const std::exception& ex) { + if (child) { + child->set_error(make_async_error(AsyncErrorCode::backend_error, ex.what())); + } + if (scope) { + scope->record_exception(std::current_exception(), ex.what()); + } + } catch (...) { + constexpr std::string_view kUnknown = + "Unhandled non-std exception in TaskScope task"; + if (child) { + child->set_error( + make_async_error(AsyncErrorCode::backend_error, std::string{kUnknown})); + } + if (scope) { + scope->record_exception(std::current_exception(), kUnknown); + } + } +} + +} // namespace detail + +class JoinHandle +{ +public: + explicit JoinHandle(std::shared_ptr control) noexcept + : control_(std::move(control)) + { + } + + [[nodiscard]] bool done() const + { + return !control_ || control_->done(); + } + + bool request_stop() noexcept + { + return control_ ? control_->request_stop() : false; + } + + [[nodiscard]] std::stop_token stop_token() const noexcept + { + return control_ ? control_->stop_token() : std::stop_token{}; + } + + struct JoinAwaiter { + std::shared_ptr control; + + [[nodiscard]] bool await_ready() const noexcept + { + return !control || control->done(); + } + + [[nodiscard]] bool await_suspend(std::coroutine_handle<> waiter) + { + return control->try_register_waiter(waiter); + } + + [[nodiscard]] Void::Result::Result await_resume() const + { + return control ? control->take_outcome() : Void::Result::Result{}; + } + }; + + [[nodiscard]] JoinAwaiter join() const noexcept + { + return JoinAwaiter{control_}; + } + + [[nodiscard]] JoinAwaiter operator co_await() const noexcept + { + return join(); + } + + [[nodiscard]] Void::Result::Result join_blocking() const + { + return control_ ? control_->join_blocking() : Void::Result::Result{}; + } + +private: + std::shared_ptr control_{}; +}; + +class TaskScope +{ +public: + explicit TaskScope( + Executor& executor, + TaskScopeOptions options = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()) + : control_(detail::ScopeControl::create(executor, options)) + , clock_(clock) + { + } + + ~TaskScope() + { + control_->request_stop(); + control_->close(); + if (control_->active_count() > 0) { + if (!control_->executor().has_background_workers()) { + if (auto* manual = dynamic_cast(&control_->executor())) { + (void)join_pumping(*manual); + } + } else if (!control_->executor().is_executor_thread()) { + (void)control_->join_blocking(); + } + } + } + + TaskScope(const TaskScope&) = delete; + TaskScope& operator=(const TaskScope&) = delete; + TaskScope(TaskScope&&) = delete; + TaskScope& operator=(TaskScope&&) = delete; + + // Reserve-then-transfer spawn: failed admission preserves `task` intact in + // the caller without destroying or losing its coroutine frame. + [[nodiscard]] std::expected + spawn(Coro::Task&& task, OperationOptions options = {}) + { + if (!task.handle() || task.done()) { + return std::unexpected{AdmissionError::invalid_argument}; + } + return admit_and_launch(options, &task, nullptr); + } + + template + requires (!std::same_as, Coro::Task>) && + std::invocable && + std::same_as, Coro::Task> + [[nodiscard]] std::expected + spawn(F&& factory, OperationOptions options = {}) + { + return admit_and_launch( + options, + nullptr, + [&](std::stop_token st) -> Coro::Task { + return std::invoke(std::forward(factory), st); + }); + } + + bool request_stop() noexcept { return control_->request_stop(); } + void close() noexcept { control_->close(); } + [[nodiscard]] std::stop_token stop_token() const noexcept { return control_->stop_token(); } + [[nodiscard]] std::size_t active_count() const { return control_->active_count(); } + [[nodiscard]] std::size_t failure_count() const { return control_->failure_count(); } + [[nodiscard]] bool has_exception() const { return control_->has_exception(); } + [[nodiscard]] std::exception_ptr first_exception() const { return control_->first_exception(); } + + struct ScopeJoinAwaiter { + std::shared_ptr control; + + [[nodiscard]] bool await_ready() const noexcept + { + return false; + } + + [[nodiscard]] bool await_suspend(std::coroutine_handle<> waiter) + { + return control->try_begin_async_join(waiter); + } + + [[nodiscard]] Void::Result::Result await_resume() const + { + return control->finish_outcome(); + } + }; + + [[nodiscard]] ScopeJoinAwaiter join() noexcept + { + return ScopeJoinAwaiter{control_}; + } + + [[nodiscard]] Void::Result::Result join_blocking() + { + return control_->join_blocking(); + } + + [[nodiscard]] Void::Result::Result join_pumping(ManualExecutor& manual) + { + control_->close(); + while (control_->active_count() > 0) { + if (manual.drain() == 0 && control_->active_count() > 0) { + std::this_thread::yield(); + } + } + return control_->finish_outcome(); + } + + [[nodiscard]] Void::Result::Result join_pumping() + { + auto* manual = dynamic_cast(&control_->executor()); + if (manual == nullptr) { + return std::unexpected{make_async_error( + AsyncErrorCode::invalid_argument, + "TaskScope::join_pumping requires ManualExecutor")}; + } + return join_pumping(*manual); + } + +private: + template + [[nodiscard]] std::expected + admit_and_launch(const OperationOptions& options, + Coro::Task* existing_task, + FactoryFn&& factory) + { + if (auto sr = control_->try_reserve(options, clock_); !sr.has_value()) { + return std::unexpected{sr.error()}; + } + + Executor& exec = control_->executor(); + const bool use_reserved = exec.supports_reservation(); + if (use_reserved) { + if (auto er = exec.try_reserve_slot(); !er.has_value()) { + control_->release_reservation(); + return std::unexpected{er.error()}; + } + } + + auto child = std::make_shared(exec); + child->attach_stops(control_->stop_token(), options.stop); + + detail::ScopeRunner runner{}; + try { + runner = detail::make_scope_runner(); + auto& prom = runner.handle.promise(); + prom.scope = control_; + prom.child = child; + if (existing_task != nullptr) { + prom.task.emplace(std::move(*existing_task)); + } else if constexpr (!std::is_null_pointer_v>) { + prom.task.emplace(factory(child->stop_token())); + } + } catch (...) { + if (runner.handle) { + if (existing_task != nullptr && runner.handle.promise().task.has_value()) { + *existing_task = std::move(*runner.handle.promise().task); + } + runner.handle.promise().scope.reset(); + runner.handle.promise().child.reset(); + runner.handle.destroy(); + } + if (use_reserved) { + exec.release_reserved(); + } + control_->release_reservation(); + throw; + } + + auto rollback_unstarted = [&]() { + if (existing_task != nullptr && runner.handle.promise().task.has_value()) { + *existing_task = std::move(*runner.handle.promise().task); + } + runner.handle.promise().scope.reset(); + runner.handle.promise().child.reset(); + runner.handle.destroy(); + if (use_reserved) { + exec.release_reserved(); + } + control_->release_reservation(); + }; + + if (use_reserved) { + try { + exec.commit_reserved(runner.handle); + } catch (...) { + rollback_unstarted(); + return std::unexpected{AdmissionError::overloaded}; + } + } else { + auto post_res = exec.try_post(runner.handle); + if (!post_res.has_value()) { + rollback_unstarted(); + return std::unexpected{post_res.error()}; + } + } + + return JoinHandle{std::move(child)}; + } + + std::shared_ptr control_; + const Void::Time::MonotonicClock& clock_; +}; + +// Explicit structured lifetime owner for detached/background fire-and-forget work. +class DetachedOwner +{ +public: + explicit DetachedOwner( + Executor& executor, + TaskScopeOptions options = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()) + : scope_(executor, options, clock) + { + } + + [[nodiscard]] std::expected + spawn(Coro::Task&& task, OperationOptions options = {}) + { + return scope_.spawn(std::move(task), std::move(options)); + } + + template + requires (!std::same_as, Coro::Task>) && + std::invocable && + std::same_as, Coro::Task> + [[nodiscard]] std::expected + spawn(F&& factory, OperationOptions options = {}) + { + return scope_.spawn(std::forward(factory), std::move(options)); + } + + bool request_stop() noexcept { return scope_.request_stop(); } + void close() noexcept { scope_.close(); } + [[nodiscard]] std::stop_token stop_token() const noexcept { return scope_.stop_token(); } + [[nodiscard]] std::size_t active_count() const { return scope_.active_count(); } + [[nodiscard]] std::size_t failure_count() const { return scope_.failure_count(); } + + [[nodiscard]] Void::Result::Result drain_blocking() { return scope_.join_blocking(); } + [[nodiscard]] Void::Result::Result drain_pumping() { return scope_.join_pumping(); } + [[nodiscard]] Void::Result::Result drain_pumping(ManualExecutor& manual) + { + return scope_.join_pumping(manual); + } + +private: + TaskScope scope_; +}; + +} // namespace Void::Async \ No newline at end of file diff --git a/src/Async/module.cmake b/src/Async/module.cmake index 8267522..a7835e3 100644 --- a/src/Async/module.cmake +++ b/src/Async/module.cmake @@ -1,3 +1,3 @@ void_add_module(Async - INTERNAL_DEPS LogState -) + INTERNAL_DEPS Functional Time LogState +) \ No newline at end of file diff --git a/tests/standalone/Async/OperationScope.cpp b/tests/standalone/Async/OperationScope.cpp new file mode 100644 index 0000000..3105329 --- /dev/null +++ b/tests/standalone/Async/OperationScope.cpp @@ -0,0 +1,633 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using namespace Void::Async; + +class ThreadedWorkerExecutor final : public Executor +{ +public: + ThreadedWorkerExecutor() + { + worker_ = std::thread([this] { run_loop(); }); + } + + ~ThreadedWorkerExecutor() override + { + shutdown(); + if (worker_.joinable()) { + worker_.join(); + } + } + + void post(std::coroutine_handle<> handle) override + { + if (!handle) { + return; + } + { + std::lock_guard lk{mu_}; + if (stop_) { + return; + } + normal_.push(handle); + } + cv_.notify_one(); + } + + [[nodiscard]] std::expected + try_post(std::coroutine_handle<> handle) override + { + if (!handle) { + return std::unexpected{AdmissionError::invalid_argument}; + } + { + std::lock_guard lk{mu_}; + if (stop_) { + return std::unexpected{AdmissionError::stopped}; + } + normal_.push(handle); + } + cv_.notify_one(); + return {}; + } + + void post_completion(std::coroutine_handle<> handle) override + { + if (!handle) { + return; + } + { + std::lock_guard lk{mu_}; + completions_.push(handle); + } + cv_.notify_one(); + } + + [[nodiscard]] bool is_executor_thread() const noexcept override + { + return std::this_thread::get_id() == worker_id_.load(std::memory_order_acquire); + } + + void shutdown() + { + { + std::lock_guard lk{mu_}; + stop_ = true; + } + cv_.notify_all(); + } + +private: + void run_loop() + { + worker_id_.store(std::this_thread::get_id(), std::memory_order_release); + for (;;) { + std::coroutine_handle<> next{}; + { + std::unique_lock lk{mu_}; + cv_.wait(lk, [this] { + return !completions_.empty() || !normal_.empty() || stop_; + }); + if (!completions_.empty()) { + next = completions_.front(); + completions_.pop(); + } else if (!normal_.empty()) { + next = normal_.front(); + normal_.pop(); + } else if (stop_) { + return; + } + } + if (next) { + next.resume(); + } + } + } + + std::atomic worker_id_{}; + std::mutex mu_{}; + std::condition_variable cv_{}; + std::queue> completions_{}; + std::queue> normal_{}; + bool stop_{false}; + std::thread worker_; +}; + +class NonReservingBoundedExecutor final : public Executor +{ +public: + explicit NonReservingBoundedExecutor(std::size_t cap) : cap_(cap) {} + + void post(std::coroutine_handle<> h) override { inner_.post(h); } + + [[nodiscard]] std::expected + try_post(std::coroutine_handle<> h) override + { + if (inner_.pending_normal() >= cap_) { + return std::unexpected{AdmissionError::overloaded}; + } + return inner_.try_post(h); + } + + void post_completion(std::coroutine_handle<> h) override { inner_.post_completion(h); } + [[nodiscard]] bool is_executor_thread() const noexcept override { return inner_.is_executor_thread(); } + [[nodiscard]] bool has_background_workers() const noexcept override { return false; } + + std::size_t drain() { return inner_.drain(); } + +private: + std::size_t cap_; + ManualExecutor inner_; +}; + +Void::Coro::Task increment_task(int* counter) +{ + ++(*counter); + co_return; +} + +Void::Coro::Task await_op_u64_task( + std::shared_ptr> op, + int* resumes, + DomainOutcomeKind* observed_kind, + std::optional* err_code, + std::uint64_t* receipt) +{ + const auto res = co_await *op; + ++(*resumes); + *observed_kind = op->outcome_kind(); + if (res.has_value()) { + if (receipt != nullptr) { + *receipt = *res; + } + } else if (err_code != nullptr) { + *err_code = static_cast(res.error().code().value); + } +} + +Void::Coro::Task await_op_void_task( + std::shared_ptr> op, + int* resumes, + DomainOutcomeKind* observed_kind, + bool* has_val) +{ + const auto res = co_await *op; + ++(*resumes); + *observed_kind = op->outcome_kind(); + if (has_val != nullptr) { + *has_val = res.has_value(); + } +} + +Void::Coro::Task await_op_int_task( + std::shared_ptr> op, + int expected, + int* waiter_resumed) +{ + const auto res = co_await *op; + Void::Testing::require(res.has_value()); + Void::Testing::expect_eq(*res, expected); + ++(*waiter_resumed); +} + +Void::Coro::Task schedule_with_options_task( + Executor* exec, + OperationOptions opts, + const Void::Time::MonotonicClock* clock, + Void::Result::Result* out) +{ + *out = co_await schedule_on(*exec, std::move(opts), *clock); +} + +} // namespace + +Void::Testing::Test operation_scope_failed_spawn_preserves_task_ownership() +{ + ManualExecutor bounded_exec{1}; + TaskScope scope{bounded_exec, TaskScopeOptions{.max_tasks = 1}}; + + int ran_first = 0; + const auto h1 = scope.spawn(increment_task(&ran_first)); + Void::Testing::require(h1.has_value()); + + // 1. Scope capacity exhausted -> task preserved intact! + int ran_preserved = 0; + auto preserved = increment_task(&ran_preserved); + const auto full_scope = scope.spawn(std::move(preserved)); + Void::Testing::expect(!full_scope.has_value()); + Void::Testing::expect(full_scope.error() == AdmissionError::overloaded); + Void::Testing::expect(static_cast(preserved.handle())); + Void::Testing::expect(!preserved.done()); + + // 2. Bounded executor queue full (reserve-then-transfer rollback) + TaskScope roomier_scope{bounded_exec, TaskScopeOptions{.max_tasks = 4}}; + const auto full_exec = roomier_scope.spawn(std::move(preserved)); + Void::Testing::expect(!full_exec.has_value()); + Void::Testing::expect(full_exec.error() == AdmissionError::overloaded); + Void::Testing::expect(static_cast(preserved.handle())); + Void::Testing::expect(!preserved.done()); + + // 3. Non-reserving executor try_post failure also restores task via rollback + NonReservingBoundedExecutor non_res_exec{0}; + TaskScope non_res_scope{non_res_exec}; + const auto non_res_reject = non_res_scope.spawn(std::move(preserved)); + Void::Testing::expect(!non_res_reject.has_value()); + Void::Testing::expect(non_res_reject.error() == AdmissionError::overloaded); + Void::Testing::expect(static_cast(preserved.handle())); + Void::Testing::expect(!preserved.done()); + + // 4. Stopped options and expired clock deadline reject without consuming task + std::stop_source ssrc; + ssrc.request_stop(); + const auto stopped_res = roomier_scope.spawn( + std::move(preserved), OperationOptions{.stop = ssrc.get_token()}); + Void::Testing::expect(!stopped_res.has_value()); + Void::Testing::expect(stopped_res.error() == AdmissionError::stopped); + Void::Testing::expect(static_cast(preserved.handle())); + + Void::Time::ManualClock clock{Void::Time::MonotonicClock::time_point{std::chrono::seconds{50}}}; + TaskScope clocked_scope{bounded_exec, TaskScopeOptions{.max_tasks = 4}, clock}; + const auto expired_res = clocked_scope.spawn( + std::move(preserved), + OperationOptions{.deadline = Void::Time::MonotonicClock::time_point{std::chrono::seconds{50}}}); + Void::Testing::expect(!expired_res.has_value()); + Void::Testing::expect(expired_res.error() == AdmissionError::deadline_expired); + Void::Testing::expect(static_cast(preserved.handle())); + + // 5. Invalid max_tasks == 0 + TaskScope zero_scope{bounded_exec, TaskScopeOptions{.max_tasks = 0}}; + const auto zero_res = zero_scope.spawn(std::move(preserved)); + Void::Testing::expect(!zero_res.has_value()); + Void::Testing::expect(zero_res.error() == AdmissionError::invalid_argument); + Void::Testing::expect(static_cast(preserved.handle())); + + // Drain `scope` (closes `scope`), then prove caller still owns `preserved` via `roomier_scope`! + Void::Testing::require(scope.join_pumping().has_value()); + Void::Testing::expect_eq(ran_first, 1); + + // Closed `scope` rejects spawn cleanly while still preserving `preserved` + const auto closed_res = scope.spawn(std::move(preserved)); + Void::Testing::expect(!closed_res.has_value()); + Void::Testing::expect(closed_res.error() == AdmissionError::stopped); + Void::Testing::expect(static_cast(preserved.handle())); + + const auto ok_after = roomier_scope.spawn(std::move(preserved)); + Void::Testing::require(ok_after.has_value()); + Void::Testing::require(roomier_scope.join_pumping().has_value()); + Void::Testing::expect_eq(ran_preserved, 1); +} + +Void::Testing::Test operation_scope_committing_adapter_races_and_backend_refs() +{ + ManualExecutor exec; + TaskScope scope{exec}; + + // Scenario A: stop-before-append -> NotCommitted after backend ref releases + { + std::stop_source stop_src; + auto op = OperationState::create( + OperationOptions{.stop = stop_src.get_token()}, + &exec, + StopBehavior::notify_only); + op->acquire_backend_ref(); + + int resumes = 0; + DomainOutcomeKind observed_kind = DomainOutcomeKind::pending; + std::optional err_code{}; + + Void::Testing::require( + scope.spawn(await_op_u64_task(op, &resumes, &observed_kind, &err_code, nullptr)) + .has_value()); + + exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + stop_src.request_stop(); + Void::Testing::expect(op->stop_requested()); + Void::Testing::expect(op->stop_token().stop_requested()); + exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + if (op->stop_token().stop_requested()) { + if (auto t = op->try_commit_not_committed(); t.has_value()) { + t->dispatch(); + } + } + exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + op->release_backend_ref_and_dispatch(); + exec.drain(); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::expect(observed_kind == DomainOutcomeKind::not_committed); + Void::Testing::expect(err_code == AsyncErrorCode::cancelled); + } + + // Scenario B: stop-during-sync + sync succeeds -> receipt preserved, never cancelled + { + std::stop_source stop_src; + auto op = OperationState::create( + OperationOptions{.stop = stop_src.get_token()}, + &exec, + StopBehavior::notify_only); + op->acquire_backend_ref(); + + int resumes = 0; + std::uint64_t receipt = 0; + DomainOutcomeKind observed_kind = DomainOutcomeKind::pending; + + Void::Testing::require( + scope.spawn(await_op_u64_task(op, &resumes, &observed_kind, nullptr, &receipt)) + .has_value()); + + exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + stop_src.request_stop(); + Void::Testing::expect(op->stop_requested()); + + auto t1 = op->try_commit_value(std::uint64_t{9001}); + Void::Testing::expect(!t1.has_value()); + auto t_dup = op->try_commit_cancelled("late cancel"); + Void::Testing::expect(!t_dup.has_value()); + + op->release_backend_ref_and_dispatch(); + exec.drain(); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::expect(observed_kind == DomainOutcomeKind::succeeded); + Void::Testing::expect_eq(receipt, std::uint64_t{9001}); + } + + // Scenario C: stop-during-sync + sync failure -> Unknown outcome after release + { + std::stop_source stop_src; + auto op = OperationState::create( + OperationOptions{.stop = stop_src.get_token()}, + &exec, + StopBehavior::notify_only); + op->acquire_backend_ref(); + + int resumes = 0; + DomainOutcomeKind observed_kind = DomainOutcomeKind::pending; + std::optional err_code{}; + + Void::Testing::require( + scope.spawn(await_op_u64_task(op, &resumes, &observed_kind, &err_code, nullptr)) + .has_value()); + + exec.drain(); + stop_src.request_stop(); + if (auto t = op->try_commit_unknown("fsync EIO"); t.has_value()) { + t->dispatch(); + } + Void::Testing::expect_eq(resumes, 0); + + op->release_backend_ref_and_dispatch(); + exec.drain(); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::expect(err_code == AsyncErrorCode::backend_error); + Void::Testing::expect(observed_kind == DomainOutcomeKind::unknown); + } + + // Scenario D: Side-effect-free StopBehavior::settle_cancelled waits for backend_ref == 0 + { + std::stop_source stop_src; + auto op = OperationState::create( + OperationOptions{.stop = stop_src.get_token()}, + &exec, + StopBehavior::settle_cancelled); + op->acquire_backend_ref(); + + int resumes = 0; + DomainOutcomeKind observed_kind = DomainOutcomeKind::pending; + bool has_val = true; + Void::Testing::require( + scope.spawn(await_op_void_task(op, &resumes, &observed_kind, &has_val)) + .has_value()); + + exec.drain(); + stop_src.request_stop(); + exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + op->release_backend_ref_and_dispatch(); + exec.drain(); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::expect(!has_val); + Void::Testing::expect(observed_kind == DomainOutcomeKind::cancelled); + } + + Void::Testing::require(scope.join_pumping().has_value()); +} + +Void::Testing::Test operation_scope_reserved_completion_lane_and_schedule_on_clock() +{ + ManualExecutor exec{1}; + TaskScope scope{exec}; + + auto op = OperationState::create({}, &exec); + int waiter_resumed = 0; + Void::Testing::require( + scope.spawn(await_op_int_task(op, 77, &waiter_resumed)).has_value()); + + // Advance waiter until it suspends on `op`. + Void::Testing::expect(exec.run_one()); + Void::Testing::expect_eq(waiter_resumed, 0); + + // Fill the normal queue capacity (max_queue = 1) completely! + std::coroutine_handle<> dummy_h = std::noop_coroutine(); + Void::Testing::require(exec.try_post(dummy_h).has_value()); + Void::Testing::expect(exec.try_post(dummy_h).error() == AdmissionError::overloaded); + + // Even with normal queue 100% saturated, reserved completion lane wakes `op`! + if (auto ticket = op->try_commit_value(77); ticket.has_value()) { + ticket->dispatch(); + } + Void::Testing::require(scope.join_pumping().has_value()); + Void::Testing::expect_eq(waiter_resumed, 1); + + // Cancellable clock-aware schedule_on tests + Void::Time::ManualClock clock{Void::Time::MonotonicClock::time_point{std::chrono::seconds{10}}}; + const auto t_dl = clock.now() + std::chrono::seconds{5}; + Void::Result::Result sched_timeout_res{}; + Void::Result::Result sched_cancel_res{}; + std::stop_source cancel_src; + + TaskScope sched_scope{exec, TaskScopeOptions{.max_tasks = 4}, clock}; + Void::Testing::require( + sched_scope.spawn( + schedule_with_options_task( + &exec, OperationOptions{.deadline = t_dl}, &clock, &sched_timeout_res)) + .has_value()); + + // First run enters coroutine body and suspends inside schedule_on(exec, opts, clock) + Void::Testing::expect(exec.run_one()); + // Advance clock past deadline WHILE queued! + Void::Testing::require(clock.advance(std::chrono::seconds{5}).has_value()); + Void::Testing::require(sched_scope.join_pumping().has_value()); + Void::Testing::expect(!sched_timeout_res.has_value()); + Void::Testing::expect( + sched_timeout_res.error().code().value == + static_cast(AsyncErrorCode::timeout)); + + // Pre-cancelled schedule_on in fresh scope + cancel_src.request_stop(); + TaskScope cancel_scope{exec, TaskScopeOptions{.max_tasks = 4}, clock}; + Void::Testing::require( + cancel_scope.spawn( + schedule_with_options_task( + &exec, OperationOptions{.stop = cancel_src.get_token()}, &clock, &sched_cancel_res)) + .has_value()); + Void::Testing::require(cancel_scope.join_pumping().has_value()); + Void::Testing::expect(!sched_cancel_res.has_value()); + Void::Testing::expect( + sched_cancel_res.error().code().value == + static_cast(AsyncErrorCode::cancelled)); +} + +Void::Testing::Test operation_scope_join_exceptions_self_join_and_detached_owner() +{ + // 1. Nested co_await scope.join(), exception sink + stop_on_first_error + { + ManualExecutor exec; + TaskScope parent{exec}; + bool child1_saw_stop = false; + Void::Result::Result nested_join_status{}; + + auto parent_task = [](Executor* ex, + bool* saw_stop_out, + Void::Result::Result* join_status_out) -> Void::Coro::Task { + TaskScope inner{*ex}; + auto op = OperationState::create( + OperationOptions{.stop = inner.stop_token()}, + ex, + StopBehavior::settle_cancelled); + + auto wait_stop = [](std::shared_ptr> s, bool* out) -> Void::Coro::Task { + const auto res = co_await *s; + *out = !res.has_value(); + }; + auto throw_child = []() -> Void::Coro::Task { + throw std::runtime_error{"boom inside inner"}; + co_return; + }; + + Void::Testing::require(inner.spawn(wait_stop(op, saw_stop_out)).has_value()); + Void::Testing::require(inner.spawn(throw_child()).has_value()); + + *join_status_out = co_await inner.join(); + Void::Testing::expect(inner.has_exception()); + Void::Testing::expect_eq(inner.failure_count(), std::size_t{1}); + }; + + Void::Testing::require( + parent.spawn(parent_task(&exec, &child1_saw_stop, &nested_join_status)).has_value()); + Void::Testing::require(parent.join_pumping().has_value()); + Void::Testing::expect(child1_saw_stop); + Void::Testing::expect(!nested_join_status.has_value()); + } + + // 2. self_join detection when join_blocking() called inside active executor thread + { + ManualExecutor exec; + TaskScope scope{exec}; + Void::Result::Result self_res{}; + + auto self_joiner = [](Executor* ex, Void::Result::Result* out) -> Void::Coro::Task { + TaskScope dummy{*ex}; + *out = dummy.join_blocking(); + co_return; + }; + Void::Testing::require(scope.spawn(self_joiner(&exec, &self_res)).has_value()); + + Void::Testing::require(scope.join_pumping().has_value()); + Void::Testing::expect(!self_res.has_value()); + Void::Testing::expect( + self_res.error().code().value == + static_cast(AsyncErrorCode::self_join)); + } + + // 3. Individual JoinHandle co_await + DetachedOwner bounded drain + { + ManualExecutor exec; + DetachedOwner owner{exec, TaskScopeOptions{.max_tasks = 8}}; + int completed = 0; + + auto h = owner.spawn(increment_task(&completed)); + Void::Testing::require(h.has_value()); + + bool awaited_ok = false; + auto await_child = [](JoinHandle handle, bool* ok_out) -> Void::Coro::Task { + const auto res = co_await handle; + *ok_out = res.has_value(); + }; + Void::Testing::require(owner.spawn(await_child(*h, &awaited_ok)).has_value()); + + Void::Testing::require(owner.drain_pumping().has_value()); + Void::Testing::expect_eq(completed, 1); + Void::Testing::expect(h->done()); + Void::Testing::expect(awaited_ok); + } +} + +Void::Testing::Test operation_scope_concurrent_stress_tsan() +{ + ThreadedWorkerExecutor exec; + constexpr int kRounds = 64; + + for (int i = 0; i < kRounds; ++i) { + std::stop_source stop_src; + auto op = OperationState::create( + OperationOptions{.stop = stop_src.get_token()}, + &exec, + (i % 2 == 0) ? StopBehavior::notify_only : StopBehavior::settle_cancelled); + op->acquire_backend_ref(); + + std::atomic resumes{0}; + TaskScope scope{exec}; + auto awaiter = [](std::shared_ptr> state, + std::atomic* count) -> Void::Coro::Task { + const auto r = co_await *state; + (void)r; + count->fetch_add(1, std::memory_order_acq_rel); + }; + auto jh = scope.spawn(awaiter(op, &resumes)); + Void::Testing::require(jh.has_value()); + + std::thread cancel_thr([&] { + if (i % 3 != 0) { + stop_src.request_stop(); + } + }); + std::thread backend_thr([&] { + if (auto t = op->try_commit_value(i); t.has_value()) { + t->dispatch(); + } + op->release_backend_ref_and_dispatch(); + }); + + cancel_thr.join(); + backend_thr.join(); + Void::Testing::require(scope.join_blocking().has_value()); + Void::Testing::expect_eq(resumes.load(std::memory_order_acquire), 1); + } +} \ No newline at end of file