Files
Library/tests/standalone/Async/OperationScope.cpp
T

633 lines
22 KiB
C++

#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);
}
}