feat(Async): add OperationOptions, OperationState, ResumeTicket, TaskScope, and bounded executor tickets (M-ASYNC-02, M-ASYNC-03)

This commit is contained in:
faumaray committed 2026-11-24 03:48:55 +03:00
1 parent 4369fde867
commit c75056fe07
6 files changed
+2229 -4

No files matched your search

+138
View File
@@ -0,0 +1,138 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <cstdint>
#include <optional>
#include <stop_token>
#include <string>
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<Void::Time::MonotonicClock::time_point> 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<std::int32_t>(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
+248 -2
View File
@@ -1,15 +1,56 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Task.hpp>
#include <atomic>
#include <coroutine>
#include <cstddef>
#include <exception>
#include <expected>
#include <optional>
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<void, AdmissionError>
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<void, AdmissionError> 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<void, AdmissionError>
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<void, AdmissionError> 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<std::coroutine_handle<>> queue_;
std::size_t max_queue_{0};
std::atomic<std::size_t> pending_normal_{0};
std::atomic<bool> accepting_{true};
MpscQueue<std::coroutine_handle<>> queue_{};
MpscQueue<std::coroutine_handle<>> completion_queue_{};
};
// ── schedule_on ───────────────────────────────────────────────────────────────
@@ -112,4 +301,61 @@ inline void spawn(Executor& executor, Coro::Task<void> 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<void> 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<void> 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
+410
View File
@@ -0,0 +1,410 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <atomic>
#include <coroutine>
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <type_traits>
#include <utility>
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<bool>(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 <typename T = void>
class OperationState : public std::enable_shared_from_this<OperationState<T>>
{
public:
using OutcomeType = std::expected<T, Void::Result::Error>;
struct Awaitable {
std::shared_ptr<OperationState<T>> 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<OperationState<T>> create(
OperationOptions options = {},
Executor* resume_executor = nullptr,
StopBehavior stop_behavior = StopBehavior::notify_only)
{
auto ptr = std::shared_ptr<OperationState<T>>(
new OperationState<T>(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<Void::Time::MonotonicClock::time_point>&
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<ResumeTicket> 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 <typename U = T>
requires (!std::is_void_v<U>)
[[nodiscard]] std::optional<ResumeTicket> try_commit_value(U value)
{
return settle_with(DomainOutcomeKind::succeeded,
[&](std::optional<OutcomeType>& slot) {
slot.emplace(std::in_place, std::move(value));
});
}
template <typename U = T>
requires (std::is_void_v<U>)
[[nodiscard]] std::optional<ResumeTicket> try_commit_value()
{
return settle_with(DomainOutcomeKind::succeeded,
[](std::optional<OutcomeType>& slot) {
slot.emplace();
});
}
[[nodiscard]] std::optional<ResumeTicket> try_commit_error(
Void::Result::Error err,
DomainOutcomeKind kind = DomainOutcomeKind::failed)
{
return settle_with(kind, [&](std::optional<OutcomeType>& slot) {
slot.emplace(std::unexpected{std::move(err)});
});
}
[[nodiscard]] std::optional<ResumeTicket> 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<ResumeTicket> 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<ResumeTicket> 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<ResumeTicket> 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<Void::Time::MonotonicClock::time_point> deadline) noexcept
: stop_behavior_(stop_behavior)
, deadline_(deadline)
, resume_executor_(resume_executor)
{
}
template <typename InitFn>
[[nodiscard]] std::optional<ResumeTicket> 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<ResumeTicket> 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<Void::Time::MonotonicClock::time_point> deadline_{};
std::atomic<std::uint64_t> sync_{0};
std::atomic<bool> outcome_claimed_{false};
std::atomic<DomainOutcomeKind> domain_outcome_{DomainOutcomeKind::pending};
std::optional<OutcomeType> 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<std::stop_callback<StopForwarder>> stop_cb_{};
};
} // namespace Void::Async
+798
View File
@@ -0,0 +1,798 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <concepts>
#include <condition_variable>
#include <coroutine>
#include <cstddef>
#include <exception>
#include <expected>
#include <functional>
#include <limits>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
#include <thread>
#include <type_traits>
#include <utility>
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<std::size_t>::max(),
parent_stop,
stop_on_first_error};
}
};
namespace detail
{
class ScopeControl;
class ChildTaskControl : public std::enable_shared_from_this<ChildTaskControl>
{
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<void> take_outcome() const
{
std::lock_guard lk{mu_};
if (error_.has_value()) {
return std::unexpected{*error_};
}
return {};
}
[[nodiscard]] Void::Result::Result<void> 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<Void::Result::Error> error_{};
std::coroutine_handle<> async_waiter_{};
// MUST stay LAST so stop callbacks synchronize before members destruct.
std::optional<std::stop_callback<StopForwarder>> scope_stop_cb_{};
std::optional<std::stop_callback<StopForwarder>> option_stop_cb_{};
};
class ScopeControl : public std::enable_shared_from_this<ScopeControl>
{
public:
[[nodiscard]] static std::shared_ptr<ScopeControl> create(
Executor& executor, TaskScopeOptions options)
{
auto ptr = std::shared_ptr<ScopeControl>(
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<void, AdmissionError> 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<void> finish_outcome() const
{
std::lock_guard lk{mu_};
if (first_error_.has_value()) {
return std::unexpected{*first_error_};
}
return {};
}
[[nodiscard]] Void::Result::Result<void> 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<bool>(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<Void::Result::Error> first_error_{};
std::coroutine_handle<> async_join_waiter_{};
// MUST stay LAST: waits for any active parent stop callback on destruction.
std::optional<std::stop_callback<StopForwarder>> parent_stop_cb_{};
};
struct TakePromiseTaskTag {};
struct GetScopePtrTag {};
struct GetChildPtrTag {};
struct ScopeRunner {
struct promise_type {
std::shared_ptr<ScopeControl> scope{};
std::shared_ptr<ChildTaskControl> child{};
std::optional<Coro::Task<void>> task{};
ScopeRunner get_return_object() noexcept
{
return ScopeRunner{
std::coroutine_handle<promise_type>::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<promise_type> 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<void> 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<ScopeControl> 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<ChildTaskControl> await_resume() noexcept
{
return p->child;
}
};
return Awaiter{this};
}
template <typename A>
decltype(auto) await_transform(A&& awaitable) noexcept
{
return std::forward<A>(awaitable);
}
};
std::coroutine_handle<promise_type> 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<detail::ChildTaskControl> 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<detail::ChildTaskControl> 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<void> await_resume() const
{
return control ? control->take_outcome() : Void::Result::Result<void>{};
}
};
[[nodiscard]] JoinAwaiter join() const noexcept
{
return JoinAwaiter{control_};
}
[[nodiscard]] JoinAwaiter operator co_await() const noexcept
{
return join();
}
[[nodiscard]] Void::Result::Result<void> join_blocking() const
{
return control_ ? control_->join_blocking() : Void::Result::Result<void>{};
}
private:
std::shared_ptr<detail::ChildTaskControl> 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<ManualExecutor*>(&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<JoinHandle, AdmissionError>
spawn(Coro::Task<void>&& task, OperationOptions options = {})
{
if (!task.handle() || task.done()) {
return std::unexpected{AdmissionError::invalid_argument};
}
return admit_and_launch(options, &task, nullptr);
}
template <typename F>
requires (!std::same_as<std::remove_cvref_t<F>, Coro::Task<void>>) &&
std::invocable<F, std::stop_token> &&
std::same_as<std::invoke_result_t<F, std::stop_token>, Coro::Task<void>>
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
spawn(F&& factory, OperationOptions options = {})
{
return admit_and_launch(
options,
nullptr,
[&](std::stop_token st) -> Coro::Task<void> {
return std::invoke(std::forward<F>(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<detail::ScopeControl> 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<void> await_resume() const
{
return control->finish_outcome();
}
};
[[nodiscard]] ScopeJoinAwaiter join() noexcept
{
return ScopeJoinAwaiter{control_};
}
[[nodiscard]] Void::Result::Result<void> join_blocking()
{
return control_->join_blocking();
}
[[nodiscard]] Void::Result::Result<void> 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<void> join_pumping()
{
auto* manual = dynamic_cast<ManualExecutor*>(&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 <typename FactoryFn = std::nullptr_t>
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
admit_and_launch(const OperationOptions& options,
Coro::Task<void>* 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<detail::ChildTaskControl>(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<std::decay_t<FactoryFn>>) {
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<detail::ScopeControl> 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<JoinHandle, AdmissionError>
spawn(Coro::Task<void>&& task, OperationOptions options = {})
{
return scope_.spawn(std::move(task), std::move(options));
}
template <typename F>
requires (!std::same_as<std::remove_cvref_t<F>, Coro::Task<void>>) &&
std::invocable<F, std::stop_token> &&
std::same_as<std::invoke_result_t<F, std::stop_token>, Coro::Task<void>>
[[nodiscard]] std::expected<JoinHandle, AdmissionError>
spawn(F&& factory, OperationOptions options = {})
{
return scope_.spawn(std::forward<F>(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<void> drain_blocking() { return scope_.join_blocking(); }
[[nodiscard]] Void::Result::Result<void> drain_pumping() { return scope_.join_pumping(); }
[[nodiscard]] Void::Result::Result<void> drain_pumping(ManualExecutor& manual)
{
return scope_.join_pumping(manual);
}
private:
TaskScope scope_;
};
} // namespace Void::Async
+2 -2
View File
@@ -1,3 +1,3 @@
void_add_module(Async
INTERNAL_DEPS LogState
)
INTERNAL_DEPS Functional Time LogState
)
+633
View File
@@ -0,0 +1,633 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <mutex>
#include <queue>
#include <stdexcept>
#include <stop_token>
#include <thread>
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<void, AdmissionError>
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<std::thread::id> worker_id_{};
std::mutex mu_{};
std::condition_variable cv_{};
std::queue<std::coroutine_handle<>> completions_{};
std::queue<std::coroutine_handle<>> 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<void, AdmissionError>
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<void> increment_task(int* counter)
{
++(*counter);
co_return;
}
Void::Coro::Task<void> await_op_u64_task(
std::shared_ptr<OperationState<std::uint64_t>> op,
int* resumes,
DomainOutcomeKind* observed_kind,
std::optional<AsyncErrorCode>* 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<AsyncErrorCode>(res.error().code().value);
}
}
Void::Coro::Task<void> await_op_void_task(
std::shared_ptr<OperationState<void>> 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<void> await_op_int_task(
std::shared_ptr<OperationState<int>> 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<void> schedule_with_options_task(
Executor* exec,
OperationOptions opts,
const Void::Time::MonotonicClock* clock,
Void::Result::Result<void>* 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<bool>(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<bool>(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<bool>(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<bool>(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<bool>(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<bool>(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<bool>(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<std::uint64_t>::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<AsyncErrorCode> 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<std::uint64_t>::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<std::uint64_t>::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<AsyncErrorCode> 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<void>::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<int>::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<void> sched_timeout_res{};
Void::Result::Result<void> 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<std::int32_t>(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<std::int32_t>(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<void> nested_join_status{};
auto parent_task = [](Executor* ex,
bool* saw_stop_out,
Void::Result::Result<void>* join_status_out) -> Void::Coro::Task<void> {
TaskScope inner{*ex};
auto op = OperationState<void>::create(
OperationOptions{.stop = inner.stop_token()},
ex,
StopBehavior::settle_cancelled);
auto wait_stop = [](std::shared_ptr<OperationState<void>> s, bool* out) -> Void::Coro::Task<void> {
const auto res = co_await *s;
*out = !res.has_value();
};
auto throw_child = []() -> Void::Coro::Task<void> {
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<void> self_res{};
auto self_joiner = [](Executor* ex, Void::Result::Result<void>* out) -> Void::Coro::Task<void> {
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<std::int32_t>(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<void> {
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<int>::create(
OperationOptions{.stop = stop_src.get_token()},
&exec,
(i % 2 == 0) ? StopBehavior::notify_only : StopBehavior::settle_cancelled);
op->acquire_backend_ref();
std::atomic<int> resumes{0};
TaskScope scope{exec};
auto awaiter = [](std::shared_ptr<OperationState<int>> state,
std::atomic<int>* count) -> Void::Coro::Task<void> {
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);
}
}