#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Assertions run on the test thread only (the assertion context is // thread_local); coroutines resumed by pool workers write into probes or // atomics. Race loops count violations and assert once after the loop (the // runner keeps only the first 1,000 assertions per test). namespace { using namespace Void::Async; using namespace std::chrono_literals; using Chan = AsyncChannel; using TimePoint = Void::Time::MonotonicClock::time_point; using Void::Time::ManualClock; using SendResult = std::expected>; using ReceiveResult = std::expected; struct SendProbe { std::optional result{}; int resumes{0}; [[nodiscard]] bool succeeded() const { return result.has_value() && result->has_value(); } [[nodiscard]] std::optional error() const { if (!result.has_value() || result->has_value()) { return std::nullopt; } return result->error().error; } [[nodiscard]] std::optional returned_value() const { if (!result.has_value() || result->has_value()) { return std::nullopt; } return result->error().value; } }; struct ReceiveProbe { std::optional result{}; int resumes{0}; [[nodiscard]] bool received() const { return result.has_value() && result->has_value(); } [[nodiscard]] std::optional value() const { if (!received()) { return std::nullopt; } return **result; } [[nodiscard]] std::optional error() const { if (!result.has_value() || result->has_value()) { return std::nullopt; } return result->error(); } }; Void::Coro::Task run_send(std::shared_ptr channel, int value, OperationOptions options, SendProbe* probe) { auto result = co_await channel->send(value, std::move(options)); probe->result = std::move(result); ++probe->resumes; } Void::Coro::Task run_receive(std::shared_ptr channel, OperationOptions options, ReceiveProbe* probe) { auto result = co_await channel->receive(std::move(options)); probe->result = std::move(result); ++probe->resumes; } void start(Void::Coro::Task& task) { task.handle().resume(); } std::shared_ptr make_channel(Executor& exec, ChannelOptions options = {}) { auto created = Chan::create(exec, options); Void::Testing::require(created.has_value()); return std::move(*created); } std::unique_ptr make_timers(Executor& exec, const Void::Time::MonotonicClock& clock, std::size_t max_timers = 64) { auto created = TimerQueue::create(exec, clock, TimerQueueOptions{.max_timers = max_timers}); Void::Testing::require(created.has_value()); return std::move(*created); } void advance_clock(ManualClock& clock, std::chrono::nanoseconds delta) { Void::Testing::require(clock.advance(delta).has_value()); } std::optional async_code(const Void::Result::Error& error) { if (error.code().domain != Void::Result::kAsyncErrorDomain) { return std::nullopt; } return static_cast(error.code().value); } // Starts `task` on `exec` through a lazily created detached frame. The // library's spawn() is deliberately not used here: ThreadSanitizer reports a // data race in Executor.hpp's spawn_impl (lines 292/296) when spawn() is called // from a thread other than the executor's workers onto a multi-worker // executor. That is independent of ThreadExecutor and is escalated to the root. struct DetachedRun { struct promise_type { DetachedRun get_return_object() noexcept { return DetachedRun{std::coroutine_handle::from_promise(*this)}; } std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_void() noexcept {} void unhandled_exception() noexcept { std::terminate(); } }; std::coroutine_handle handle{}; }; DetachedRun run_detached(Void::Coro::Task task) { co_await std::move(task); } void launch(Executor& exec, Void::Coro::Task task) { exec.post(run_detached(std::move(task)).handle); } template bool wait_until(Pred pred, std::chrono::milliseconds timeout = 10000ms) { const auto end = std::chrono::steady_clock::now() + timeout; while (!pred()) { if (std::chrono::steady_clock::now() >= end) { return false; } std::this_thread::yield(); } return true; } } // namespace Void::Testing::Test channel_zero_capacity_invalid() { ManualExecutor exec; const auto zero_capacity = Chan::create(exec, ChannelOptions{.capacity = 0}); Void::Testing::require(!zero_capacity.has_value()); Void::Testing::expect(async_code(zero_capacity.error()) == AsyncErrorCode::invalid_argument); Void::Testing::expect(zero_capacity.error().kind() == Void::Result::ErrorKind::invalid_argument); const auto zero_waiters = Chan::create(exec, ChannelOptions{.max_waiters = 0}); Void::Testing::require(!zero_waiters.has_value()); Void::Testing::expect(async_code(zero_waiters.error()) == AsyncErrorCode::invalid_argument); const auto ok = Chan::create(exec, ChannelOptions{.capacity = 1, .max_waiters = 1}); Void::Testing::require(ok.has_value()); Void::Testing::expect_eq((*ok)->size(), std::size_t{0}); Void::Testing::expect(!(*ok)->is_closed()); // ChannelError maps into the async error domain via the existing codes. Void::Testing::expect(async_code(make_async_error(ChannelError::closed)) == AsyncErrorCode::closed); Void::Testing::expect(make_async_error(ChannelError::closed).kind() == Void::Result::ErrorKind::cancelled); Void::Testing::expect(async_code(make_async_error(ChannelError::cancelled)) == AsyncErrorCode::cancelled); Void::Testing::expect(async_code(make_async_error(ChannelError::timed_out)) == AsyncErrorCode::timeout); Void::Testing::expect(async_code(make_async_error(ChannelError::overloaded)) == AsyncErrorCode::overloaded); Void::Testing::expect(async_code(make_async_error(ChannelError::full)) == AsyncErrorCode::overloaded); Void::Testing::expect(async_code(make_async_error(ChannelError::empty)) == AsyncErrorCode::invalid_argument); Void::Testing::expect(async_code(make_async_error(ChannelError::invalid_argument, "custom")) == AsyncErrorCode::invalid_argument); Void::Testing::expect_eq(make_async_error(ChannelError::invalid_argument, "custom").message(), std::string{"custom"}); } Void::Testing::Test channel_try_send_full_returns_value() { ManualExecutor exec; auto string_channel = AsyncChannel::create(exec, ChannelOptions{.capacity = 2}); Void::Testing::require(string_channel.has_value()); auto& channel = **string_channel; Void::Testing::require(channel.try_send("a").has_value()); Void::Testing::require(channel.try_send("b").has_value()); Void::Testing::expect_eq(channel.size(), std::size_t{2}); // A full channel hands the value back, untouched. const auto full = channel.try_send(std::string(64, 'x')); Void::Testing::require(!full.has_value()); Void::Testing::expect(full.error().error == ChannelError::full); Void::Testing::expect_eq(full.error().value, std::string(64, 'x')); Void::Testing::expect_eq(channel.size(), std::size_t{2}); const auto first = channel.try_receive(); Void::Testing::require(first.has_value()); Void::Testing::expect_eq(*first, std::string{"a"}); const auto second = channel.try_receive(); Void::Testing::require(second.has_value()); Void::Testing::expect_eq(*second, std::string{"b"}); const auto empty = channel.try_receive(); Void::Testing::require(!empty.has_value()); Void::Testing::expect(empty.error() == ChannelError::empty); // Closed channel: send returns the value with `closed`; receive reports // `closed` only once the buffer is drained. Void::Testing::require(channel.try_send("kept").has_value()); channel.close(); Void::Testing::expect(channel.is_closed()); const auto closed = channel.try_send("late"); Void::Testing::require(!closed.has_value()); Void::Testing::expect(closed.error().error == ChannelError::closed); Void::Testing::expect_eq(closed.error().value, std::string{"late"}); const auto drained = channel.try_receive(); Void::Testing::require(drained.has_value()); Void::Testing::expect_eq(*drained, std::string{"kept"}); const auto done = channel.try_receive(); Void::Testing::require(!done.has_value()); Void::Testing::expect(done.error() == ChannelError::closed); } Void::Testing::Test channel_send_waits_resumes_on_receive() { ManualExecutor exec; auto channel = make_channel(exec, ChannelOptions{.capacity = 1}); Void::Testing::require(channel->try_send(1).has_value()); // The buffer is full: the sender suspends. SendProbe send_probe; auto sender = run_send(channel, 2, {}, &send_probe); start(sender); Void::Testing::expect_eq(send_probe.resumes, 0); Void::Testing::expect_eq(exec.drain(), std::size_t{0}); // Receiving frees a slot: the waiting sender's value moves into the // buffer, the sender is claimed and resumed through the completion lane. const auto first = channel->try_receive(); Void::Testing::require(first.has_value()); Void::Testing::expect_eq(*first, 1); Void::Testing::expect_eq(send_probe.resumes, 0); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect_eq(send_probe.resumes, 1); Void::Testing::expect(send_probe.succeeded()); Void::Testing::expect(sender.done()); Void::Testing::expect_eq(channel->size(), std::size_t{1}); const auto second = channel->try_receive(); Void::Testing::require(second.has_value()); Void::Testing::expect_eq(*second, 2); // A waiting receiver gets a directly handed-off value. ReceiveProbe receive_probe; auto receiver = run_receive(channel, {}, &receive_probe); start(receiver); Void::Testing::expect_eq(receive_probe.resumes, 0); Void::Testing::require(channel->try_send(3).has_value()); // The value went straight to the receiver, not into the buffer. Void::Testing::expect_eq(channel->size(), std::size_t{0}); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect_eq(receive_probe.resumes, 1); Void::Testing::expect(receive_probe.value() == std::optional{3}); // The coroutine fast paths do not suspend. SendProbe immediate_send; auto fast_sender = run_send(channel, 4, {}, &immediate_send); start(fast_sender); Void::Testing::expect_eq(immediate_send.resumes, 1); Void::Testing::expect(immediate_send.succeeded()); ReceiveProbe immediate_receive; auto fast_receiver = run_receive(channel, {}, &immediate_receive); start(fast_receiver); Void::Testing::expect_eq(immediate_receive.resumes, 1); Void::Testing::expect(immediate_receive.value() == std::optional{4}); } Void::Testing::Test channel_producer_stop_returns_value_cancelled_once() { ManualExecutor exec; auto channel = make_channel(exec, ChannelOptions{.capacity = 1}); Void::Testing::require(channel->try_send(1).has_value()); std::stop_source stop; SendProbe probe; auto sender = run_send(channel, 2, OperationOptions{.stop = stop.get_token()}, &probe); start(sender); Void::Testing::expect_eq(probe.resumes, 0); // stop: unlink + cancelled, value returned, resumed via the completion lane. Void::Testing::expect(stop.request_stop()); Void::Testing::expect_eq(probe.resumes, 0); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect_eq(probe.resumes, 1); Void::Testing::expect(probe.error() == std::optional{ChannelError::cancelled}); Void::Testing::expect(probe.returned_value() == std::optional{2}); // Exactly once: a second stop request and further traffic change nothing, // and the cancelled value never reaches the buffer. Void::Testing::expect(!stop.request_stop()); const auto received = channel->try_receive(); Void::Testing::require(received.has_value()); Void::Testing::expect_eq(*received, 1); Void::Testing::expect_eq(exec.drain(), std::size_t{0}); Void::Testing::expect_eq(probe.resumes, 1); Void::Testing::expect_eq(channel->size(), std::size_t{0}); // Stop already requested: refused before any state change, value returned. SendProbe pre_stopped; auto refused = run_send(channel, 9, OperationOptions{.stop = stop.get_token()}, &pre_stopped); start(refused); Void::Testing::expect_eq(pre_stopped.resumes, 1); Void::Testing::expect(pre_stopped.error() == std::optional{ChannelError::cancelled}); Void::Testing::expect(pre_stopped.returned_value() == std::optional{9}); Void::Testing::expect_eq(channel->size(), std::size_t{0}); // A receiver cancelled by stop leaves the channel intact. std::stop_source receive_stop; ReceiveProbe receive_probe; auto receiver = run_receive(channel, OperationOptions{.stop = receive_stop.get_token()}, &receive_probe); start(receiver); Void::Testing::expect(receive_stop.request_stop()); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect_eq(receive_probe.resumes, 1); Void::Testing::expect(receive_probe.error() == std::optional{ChannelError::cancelled}); Void::Testing::require(channel->try_send(5).has_value()); Void::Testing::expect_eq(channel->size(), std::size_t{1}); } Void::Testing::Test channel_receiver_stop_after_claim_delivers_value_no_loss() { ManualExecutor exec; auto channel = make_channel(exec, ChannelOptions{.capacity = 1}); std::stop_source stop; ReceiveProbe probe; auto receiver = run_receive(channel, OperationOptions{.stop = stop.get_token()}, &probe); start(receiver); Void::Testing::expect_eq(probe.resumes, 0); // A sender claims the waiting receiver: the value is already in its slot. Void::Testing::require(channel->try_send(77).has_value()); // The stop request arrives after the claim and before the resume ran: the // callback finds a claimed waiter and does nothing. Void::Testing::expect(stop.request_stop()); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect_eq(probe.resumes, 1); Void::Testing::expect(probe.value() == std::optional{77}); Void::Testing::expect_eq(channel->size(), std::size_t{0}); // Same for a sender claimed by a receive before the stop callback ran. auto full = make_channel(exec, ChannelOptions{.capacity = 1}); Void::Testing::require(full->try_send(1).has_value()); std::stop_source send_stop; SendProbe send_probe; auto sender = run_send(full, 2, OperationOptions{.stop = send_stop.get_token()}, &send_probe); start(sender); const auto taken = full->try_receive(); Void::Testing::require(taken.has_value()); Void::Testing::expect_eq(*taken, 1); Void::Testing::expect(send_stop.request_stop()); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect_eq(send_probe.resumes, 1); Void::Testing::expect(send_probe.succeeded()); const auto delivered = full->try_receive(); Void::Testing::require(delivered.has_value()); Void::Testing::expect_eq(*delivered, 2); } namespace { // Busy delay used to sweep the relative timing of the two racing threads. void spin_for(int rounds) { std::atomic sink{0}; for (int k = 0; k < rounds; ++k) { sink.fetch_add(1, std::memory_order_relaxed); } } // Reusable two-party barrier that spins (with yield) instead of sleeping on a // futex, so both racing threads leave it at nearly the same instant. class SpinBarrier { public: explicit SpinBarrier(unsigned parties) noexcept : parties_(parties) {} void arrive_and_wait() noexcept { const unsigned target = (count_.fetch_add(1, std::memory_order_acq_rel) / parties_ + 1) * parties_; while (count_.load(std::memory_order_acquire) < target) { std::this_thread::yield(); } } private: const unsigned parties_; std::atomic count_{0}; }; } // namespace Void::Testing::Test channel_sender_stop_vs_receive_race_exactly_once_tsan() { constexpr int kIterations = 10000; auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 64}); Void::Testing::require(created.has_value()); auto& exec = **created; Void::Testing::require(exec.start().has_value()); SpinBarrier go{2}; SpinBarrier finished{2}; std::shared_ptr current; std::optional helper_value; int helper_delay = 0; std::atomic stop_loop{false}; // Persistent helper: receives once per iteration, racing the stop request. std::thread helper([&] { for (;;) { go.arrive_and_wait(); if (stop_loop.load(std::memory_order_acquire)) { return; } spin_for(helper_delay); auto got = current->try_receive(); helper_value = got.has_value() ? std::optional{*got} : std::nullopt; finished.arrive_and_wait(); } }); int violations = 0; int timeouts = 0; std::uint64_t cancelled_sends = 0; std::uint64_t completed_sends = 0; for (int i = 0; i < kIterations; ++i) { const int sentinel = 2 * i; const int sent = 2 * i + 1; // No assertion (and no throw) while the helper thread is joinable. auto created_channel = Chan::create(exec, ChannelOptions{.capacity = 1, .max_waiters = 4}); if (!created_channel.has_value()) { ++violations; break; } auto channel = std::move(*created_channel); (void)channel->try_send(sentinel); std::stop_source stop; SendProbe probe; std::atomic done{false}; launch(exec, [](std::shared_ptr ch, int v, std::stop_token token, SendProbe* out, std::atomic* flag) -> Void::Coro::Task { auto result = co_await ch->send(v, OperationOptions{.stop = token}); out->result = std::move(result); flag->store(true, std::memory_order_release); }(channel, sent, stop.get_token(), &probe, &done)); // Three of four iterations race a stop against a receive while the // sender is already linked (the executor is idle once the sender // suspended, since the buffer is full); the rest race the stop against // the sender's own start. if (i % 4 != 0) { (void)wait_until([&] { return exec.idle(); }); } const int skew = (i % 41) - 20; // < 0: delay the stop, > 0: delay the receive helper_delay = skew > 0 ? skew * 12 : 0; current = channel; go.arrive_and_wait(); spin_for(skew < 0 ? -skew * 12 : 0); stop.request_stop(); finished.arrive_and_wait(); if (!wait_until([&] { return done.load(std::memory_order_acquire); })) { ++timeouts; break; } // Every value must be in exactly one place: received by the helper, // returned to the sender, or still buffered. int seen[2] = {0, 0}; const auto note = [&](int value) { if (value == sentinel) { ++seen[0]; } else if (value == sent) { ++seen[1]; } else { ++violations; } }; if (helper_value.has_value()) { note(*helper_value); } if (probe.returned_value().has_value()) { note(*probe.returned_value()); ++cancelled_sends; } else if (probe.succeeded()) { ++completed_sends; } else { ++violations; } for (;;) { auto rest = channel->try_receive(); if (!rest.has_value()) { break; } note(*rest); } if (seen[0] != 1 || seen[1] != 1) { ++violations; } current.reset(); } stop_loop.store(true, std::memory_order_release); go.arrive_and_wait(); helper.join(); Void::Testing::require(exec.join().has_value()); Void::Testing::expect_eq(timeouts, 0); Void::Testing::expect_eq(violations, 0); // Whichever side won each race, the sender settled exactly once. Void::Testing::expect_eq(cancelled_sends + completed_sends, static_cast(kIterations)); } Void::Testing::Test channel_close_wakes_senders_with_value_and_drains_receivers() { ManualExecutor exec; auto channel = make_channel(exec, ChannelOptions{.capacity = 2}); Void::Testing::require(channel->try_send(1).has_value()); Void::Testing::require(channel->try_send(2).has_value()); SendProbe first_sender; SendProbe second_sender; auto sender_a = run_send(channel, 3, {}, &first_sender); auto sender_b = run_send(channel, 4, {}, &second_sender); start(sender_a); start(sender_b); Void::Testing::expect_eq(first_sender.resumes + second_sender.resumes, 0); channel->close(); Void::Testing::expect(channel->is_closed()); Void::Testing::expect_eq(first_sender.resumes + second_sender.resumes, 0); Void::Testing::expect_eq(exec.drain(), std::size_t{2}); // Waiting senders: `closed` plus their own value back, each exactly once. Void::Testing::expect_eq(first_sender.resumes, 1); Void::Testing::expect_eq(second_sender.resumes, 1); Void::Testing::expect(first_sender.error() == std::optional{ChannelError::closed}); Void::Testing::expect(second_sender.error() == std::optional{ChannelError::closed}); Void::Testing::expect(first_sender.returned_value() == std::optional{3}); Void::Testing::expect(second_sender.returned_value() == std::optional{4}); // close() is idempotent and wakes nobody twice. channel->close(); Void::Testing::expect_eq(exec.drain(), std::size_t{0}); // Receivers drain the buffer in FIFO order, then get `closed`. ReceiveProbe r1; ReceiveProbe r2; ReceiveProbe r3; auto rt1 = run_receive(channel, {}, &r1); auto rt2 = run_receive(channel, {}, &r2); auto rt3 = run_receive(channel, {}, &r3); start(rt1); start(rt2); start(rt3); Void::Testing::expect(r1.value() == std::optional{1}); Void::Testing::expect(r2.value() == std::optional{2}); Void::Testing::expect(r3.error() == std::optional{ChannelError::closed}); // Receivers that are already waiting when close() runs get `closed`. auto empty = make_channel(exec, ChannelOptions{.capacity = 2}); ReceiveProbe w1; ReceiveProbe w2; auto wt1 = run_receive(empty, {}, &w1); auto wt2 = run_receive(empty, {}, &w2); start(wt1); start(wt2); Void::Testing::expect_eq(w1.resumes + w2.resumes, 0); empty->close(); Void::Testing::expect_eq(exec.drain(), std::size_t{2}); Void::Testing::expect(w1.error() == std::optional{ChannelError::closed}); Void::Testing::expect(w2.error() == std::optional{ChannelError::closed}); Void::Testing::expect_eq(w1.resumes + w2.resumes, 2); // send() after close(): closed, value returned, without suspending. SendProbe late; auto late_sender = run_send(empty, 8, {}, &late); start(late_sender); Void::Testing::expect(late.error() == std::optional{ChannelError::closed}); Void::Testing::expect(late.returned_value() == std::optional{8}); } Void::Testing::Test channel_deadline_requires_timers() { ManualExecutor exec; auto channel = make_channel(exec, ChannelOptions{.capacity = 1}); const OperationOptions with_deadline{.deadline = TimePoint{std::chrono::seconds{5}}}; // No `timers`: a deadline cannot be judged -> invalid_argument, value back. SendProbe send_probe; auto sender = run_send(channel, 6, with_deadline, &send_probe); start(sender); Void::Testing::expect_eq(send_probe.resumes, 1); Void::Testing::expect(send_probe.error() == std::optional{ChannelError::invalid_argument}); Void::Testing::expect(send_probe.returned_value() == std::optional{6}); // ... before any state change: nothing was buffered. Void::Testing::expect_eq(channel->size(), std::size_t{0}); ReceiveProbe receive_probe; auto receiver = run_receive(channel, with_deadline, &receive_probe); start(receiver); Void::Testing::expect_eq(receive_probe.resumes, 1); Void::Testing::expect(receive_probe.error() == std::optional{ChannelError::invalid_argument}); // Even when the channel could serve the request immediately. Void::Testing::require(channel->try_send(1).has_value()); ReceiveProbe still_invalid; auto second_receiver = run_receive(channel, with_deadline, &still_invalid); start(second_receiver); Void::Testing::expect(still_invalid.error() == std::optional{ChannelError::invalid_argument}); Void::Testing::expect_eq(channel->size(), std::size_t{1}); Void::Testing::expect_eq(exec.drain(), std::size_t{0}); } Void::Testing::Test channel_deadline_times_out_once_manual_clock_poll() { ManualExecutor exec; ManualClock clock; auto timers = make_timers(exec, clock); auto channel = make_channel(exec, ChannelOptions{.capacity = 1, .timers = timers.get()}); Void::Testing::require(channel->try_send(1).has_value()); const TimePoint deadline = clock.now() + 100ms; SendProbe send_probe; auto sender = run_send(channel, 2, OperationOptions{.deadline = deadline}, &send_probe); start(sender); Void::Testing::expect_eq(send_probe.resumes, 0); Void::Testing::expect_eq(timers->active_timers(), std::size_t{1}); advance_clock(clock, 99ms); Void::Testing::expect_eq(timers->poll_expired(), std::size_t{0}); Void::Testing::expect_eq(exec.drain(), std::size_t{0}); Void::Testing::expect_eq(send_probe.resumes, 0); advance_clock(clock, 1ms); Void::Testing::expect_eq(timers->poll_expired(), std::size_t{1}); Void::Testing::expect_eq(send_probe.resumes, 0); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect_eq(send_probe.resumes, 1); Void::Testing::expect(send_probe.error() == std::optional{ChannelError::timed_out}); Void::Testing::expect(send_probe.returned_value() == std::optional{2}); // Exactly once: later polls and traffic never touch the settled sender. advance_clock(clock, 1s); Void::Testing::expect_eq(timers->poll_expired(), std::size_t{0}); Void::Testing::expect_eq(exec.drain(), std::size_t{0}); Void::Testing::expect_eq(send_probe.resumes, 1); Void::Testing::expect_eq(timers->active_timers(), std::size_t{0}); const auto kept = channel->try_receive(); Void::Testing::require(kept.has_value()); Void::Testing::expect_eq(*kept, 1); Void::Testing::expect_eq(channel->size(), std::size_t{0}); // A receiver times out the same way. ReceiveProbe receive_probe; auto receiver = run_receive(channel, OperationOptions{.deadline = clock.now() + 10ms}, &receive_probe); start(receiver); Void::Testing::expect_eq(timers->active_timers(), std::size_t{1}); advance_clock(clock, 10ms); Void::Testing::expect_eq(timers->poll_expired(), std::size_t{1}); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect(receive_probe.error() == std::optional{ChannelError::timed_out}); Void::Testing::expect_eq(receive_probe.resumes, 1); // A deadline that is already reached is refused before any state change. SendProbe expired; auto expired_sender = run_send(channel, 3, OperationOptions{.deadline = clock.now()}, &expired); start(expired_sender); Void::Testing::expect_eq(expired.resumes, 1); Void::Testing::expect(expired.error() == std::optional{ChannelError::timed_out}); Void::Testing::expect(expired.returned_value() == std::optional{3}); Void::Testing::expect_eq(channel->size(), std::size_t{0}); Void::Testing::expect_eq(timers->active_timers(), std::size_t{0}); // A wait that is satisfied before the deadline cancels its timer. SendProbe satisfied; Void::Testing::require(channel->try_send(10).has_value()); auto early_sender = run_send(channel, 11, OperationOptions{.deadline = clock.now() + 1s}, &satisfied); start(early_sender); Void::Testing::expect_eq(timers->active_timers(), std::size_t{1}); const auto early = channel->try_receive(); Void::Testing::require(early.has_value()); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect(satisfied.succeeded()); Void::Testing::expect_eq(timers->active_timers(), std::size_t{0}); } Void::Testing::Test channel_timer_close_settles_waiter_cancelled() { ManualExecutor exec; ManualClock clock; auto timers = make_timers(exec, clock, 2); auto channel = make_channel(exec, ChannelOptions{.capacity = 1, .timers = timers.get()}); Void::Testing::require(channel->try_send(1).has_value()); const OperationOptions options{.deadline = clock.now() + 1s}; SendProbe send_probe; auto sender = run_send(channel, 2, options, &send_probe); start(sender); ReceiveProbe receive_probe; auto other = make_channel(exec, ChannelOptions{.capacity = 1, .timers = timers.get()}); auto receiver = run_receive(other, options, &receive_probe); start(receiver); Void::Testing::expect_eq(timers->active_timers(), std::size_t{2}); // The timer queue is at max_timers: a third deadline wait is refused with // overloaded and the value comes back. SendProbe overloaded; auto third = run_send(channel, 3, options, &overloaded); start(third); Void::Testing::expect_eq(overloaded.resumes, 1); Void::Testing::expect(overloaded.error() == std::optional{ChannelError::overloaded}); Void::Testing::expect(overloaded.returned_value() == std::optional{3}); // TimerEvent::closed settles every pending channel wait `cancelled`. timers->close(); Void::Testing::expect_eq(send_probe.resumes, 0); Void::Testing::expect_eq(exec.drain(), std::size_t{2}); Void::Testing::expect_eq(send_probe.resumes, 1); Void::Testing::expect_eq(receive_probe.resumes, 1); Void::Testing::expect(send_probe.error() == std::optional{ChannelError::cancelled}); Void::Testing::expect(send_probe.returned_value() == std::optional{2}); Void::Testing::expect(receive_probe.error() == std::optional{ChannelError::cancelled}); // A closed timer queue refuses new deadline waits: stopped -> cancelled. SendProbe after_close; auto fourth = run_send(channel, 4, options, &after_close); start(fourth); Void::Testing::expect_eq(after_close.resumes, 1); Void::Testing::expect(after_close.error() == std::optional{ChannelError::cancelled}); Void::Testing::expect(after_close.returned_value() == std::optional{4}); // The channel itself is untouched. Void::Testing::expect_eq(channel->size(), std::size_t{1}); } Void::Testing::Test channel_timer_fire_after_waiter_destroyed_safe() { ManualExecutor exec; ManualClock clock; auto timers = make_timers(exec, clock); auto channel = make_channel(exec, ChannelOptions{.capacity = 1, .timers = timers.get()}); Void::Testing::require(channel->try_send(1).has_value()); const TimePoint deadline = clock.now() + 50ms; SendProbe probe; std::unique_ptr> task; int gate_received = -1; int gate_runs = 0; // poll_expired() claims every due timer before running any callback, in // (deadline, seq) order. The gate timer (lower seq) runs first: it lets the // waiting sender complete, destroys its task and drops the last reference // to the channel, so the sender's own timer callback then runs against a // dead waiter and channel. auto gate = timers->schedule_at( deadline, TimerCallback{[&](TimerEvent) noexcept { ++gate_runs; const auto got = channel->try_receive(); gate_received = got.has_value() ? *got : -1; (void)exec.drain(); task.reset(); channel.reset(); }}); Void::Testing::require(gate.has_value()); task = std::make_unique>( run_send(channel, 2, OperationOptions{.deadline = deadline}, &probe)); start(*task); Void::Testing::expect_eq(timers->active_timers(), std::size_t{2}); Void::Testing::expect_eq(probe.resumes, 0); advance_clock(clock, 50ms); Void::Testing::expect_eq(timers->poll_expired(), std::size_t{2}); Void::Testing::expect_eq(gate_runs, 1); Void::Testing::expect_eq(gate_received, 1); // The sender completed exactly once with success (no late timeout). Void::Testing::expect_eq(probe.resumes, 1); Void::Testing::expect(probe.succeeded()); Void::Testing::expect(channel == nullptr); Void::Testing::expect(task == nullptr); Void::Testing::expect_eq(exec.drain(), std::size_t{0}); } Void::Testing::Test channel_waiter_bound_overloaded() { ManualExecutor exec; auto channel = make_channel(exec, ChannelOptions{.capacity = 1, .max_waiters = 2}); Void::Testing::require(channel->try_send(0).has_value()); SendProbe s1; SendProbe s2; SendProbe s3; auto t1 = run_send(channel, 1, {}, &s1); auto t2 = run_send(channel, 2, {}, &s2); auto t3 = run_send(channel, 3, {}, &s3); start(t1); start(t2); start(t3); // Two senders wait; the third exceeds max_waiters and gets its value back. Void::Testing::expect_eq(s1.resumes + s2.resumes, 0); Void::Testing::expect_eq(s3.resumes, 1); Void::Testing::expect(s3.error() == std::optional{ChannelError::overloaded}); Void::Testing::expect(s3.returned_value() == std::optional{3}); // The bound is per direction: receivers have their own budget. auto empty = make_channel(exec, ChannelOptions{.capacity = 1, .max_waiters = 1}); ReceiveProbe r1; ReceiveProbe r2; auto rt1 = run_receive(empty, {}, &r1); auto rt2 = run_receive(empty, {}, &r2); start(rt1); start(rt2); Void::Testing::expect_eq(r1.resumes, 0); Void::Testing::expect_eq(r2.resumes, 1); Void::Testing::expect(r2.error() == std::optional{ChannelError::overloaded}); // A freed waiter slot can be reused: drain the waiting senders in order. for (int expected : {0, 1, 2}) { const auto got = channel->try_receive(); Void::Testing::require(got.has_value()); Void::Testing::expect_eq(*got, expected); (void)exec.drain(); } Void::Testing::expect_eq(s1.resumes, 1); Void::Testing::expect_eq(s2.resumes, 1); Void::Testing::expect(s1.succeeded()); Void::Testing::expect(s2.succeeded()); Void::Testing::require(empty->try_send(5).has_value()); (void)exec.drain(); Void::Testing::expect(r1.value() == std::optional{5}); } namespace { using Ptr = std::unique_ptr; using PtrChannel = AsyncChannel; using PtrSendResult = std::expected>; using PtrReceiveResult = std::expected; Void::Coro::Task ptr_sender(std::shared_ptr channel, Ptr value, std::optional* out, int* resumes) { auto result = co_await channel->send(std::move(value)); *out = std::move(result); ++*resumes; } Void::Coro::Task ptr_receiver(std::shared_ptr channel, std::optional* out, int* resumes) { auto result = co_await channel->receive(); *out = std::move(result); ++*resumes; } } // namespace Void::Testing::Test channel_move_only_values() { ManualExecutor exec; auto created = PtrChannel::create(exec, ChannelOptions{.capacity = 1}); Void::Testing::require(created.has_value()); auto channel = std::move(*created); Ptr first = std::make_unique(10); int* const first_raw = first.get(); Void::Testing::require(channel->try_send(std::move(first)).has_value()); // A rejected move-only value comes back intact (the same object). Ptr second = std::make_unique(20); int* const second_raw = second.get(); auto full = channel->try_send(std::move(second)); Void::Testing::require(!full.has_value()); Void::Testing::expect(full.error().error == ChannelError::full); Void::Testing::expect(full.error().value.get() == second_raw); auto received = channel->try_receive(); Void::Testing::require(received.has_value()); Void::Testing::expect(received->get() == first_raw); // A suspended coroutine send keeps ownership until the value is delivered. Void::Testing::require(channel->try_send(std::make_unique(30)).has_value()); Ptr third = std::make_unique(40); int* const third_raw = third.get(); std::optional send_result; int resumes = 0; auto sender = ptr_sender(channel, std::move(third), &send_result, &resumes); start(sender); Void::Testing::expect_eq(resumes, 0); auto drained = channel->try_receive(); Void::Testing::require(drained.has_value()); Void::Testing::expect_eq(**drained, 30); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect_eq(resumes, 1); Void::Testing::require(send_result.has_value()); Void::Testing::expect(send_result->has_value()); auto buffered = channel->try_receive(); Void::Testing::require(buffered.has_value()); Void::Testing::expect(buffered->get() == third_raw); // A cancelled move-only send returns the pointer. Void::Testing::require(channel->try_send(std::make_unique(50)).has_value()); std::stop_source stop; Ptr fourth = std::make_unique(60); int* const fourth_raw = fourth.get(); std::optional cancelled_result; int cancelled_resumes = 0; auto stoppable = [](std::shared_ptr ch, Ptr value, std::stop_token token, std::optional* out, int* counter) -> Void::Coro::Task { auto result = co_await ch->send(std::move(value), OperationOptions{.stop = token}); *out = std::move(result); ++*counter; }(channel, std::move(fourth), stop.get_token(), &cancelled_result, &cancelled_resumes); start(stoppable); Void::Testing::expect(stop.request_stop()); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect_eq(cancelled_resumes, 1); Void::Testing::require(cancelled_result.has_value()); Void::Testing::require(!cancelled_result->has_value()); Void::Testing::expect(cancelled_result->error().error == ChannelError::cancelled); Void::Testing::expect(cancelled_result->error().value.get() == fourth_raw); // A waiting move-only receiver gets the handed-off pointer. auto emptied = channel->try_receive(); Void::Testing::require(emptied.has_value()); std::optional receive_result; int receive_resumes = 0; auto receiver = ptr_receiver(channel, &receive_result, &receive_resumes); start(receiver); Void::Testing::expect_eq(receive_resumes, 0); Ptr handed = std::make_unique(70); int* const handed_raw = handed.get(); Void::Testing::require(channel->try_send(std::move(handed)).has_value()); Void::Testing::expect_eq(exec.drain(), std::size_t{1}); Void::Testing::expect_eq(receive_resumes, 1); Void::Testing::require(receive_result.has_value()); Void::Testing::require(receive_result->has_value()); Void::Testing::expect((*receive_result)->get() == handed_raw); } namespace { constexpr std::uint64_t kProducerStride = 1'000'000; Void::Coro::Task producer_task(std::shared_ptr> channel, std::uint64_t producer, int items, std::atomic* producers_done, std::atomic* send_errors) { for (int k = 0; k < items; ++k) { auto result = co_await channel->send(producer * kProducerStride + static_cast(k)); if (!result.has_value()) { send_errors->fetch_add(1); } } producers_done->fetch_add(1); } Void::Coro::Task consumer_task(std::shared_ptr> channel, std::vector* sink, std::atomic* consumers_done) { for (;;) { auto result = co_await channel->receive(); if (!result.has_value()) { break; } sink->push_back(*result); } consumers_done->fetch_add(1); } } // namespace Void::Testing::Test channel_mpmc_fifo_tsan() { constexpr int kProducers = 3; constexpr int kConsumers = 3; constexpr int kItems = 1500; auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 4}); Void::Testing::require(created.has_value()); auto& exec = **created; Void::Testing::require(exec.start().has_value()); auto channel_result = AsyncChannel::create( exec, ChannelOptions{.capacity = 8, .max_waiters = 64}); Void::Testing::require(channel_result.has_value()); auto channel = std::move(*channel_result); std::atomic producers_done{0}; std::atomic consumers_done{0}; std::atomic send_errors{0}; std::vector sinks[kConsumers]; for (int c = 0; c < kConsumers; ++c) { launch(exec, consumer_task(channel, &sinks[c], &consumers_done)); } for (int p = 0; p < kProducers; ++p) { launch(exec, producer_task(channel, static_cast(p), kItems, &producers_done, &send_errors)); } const bool producers_finished = wait_until([&] { return producers_done.load() == kProducers; }); // close() unblocks every remaining waiter, so the joins below cannot hang. channel->close(); const bool consumers_finished = wait_until([&] { return consumers_done.load() == kConsumers; }); Void::Testing::require(exec.join().has_value()); Void::Testing::expect(producers_finished); Void::Testing::expect(consumers_finished); std::size_t total = 0; std::uint64_t order_violations = 0; std::vector seen(static_cast(kProducers) * kItems, 0); std::uint64_t unknown_values = 0; for (const auto& sink : sinks) { total += sink.size(); std::int64_t last[kProducers]; for (auto& l : last) { l = -1; } for (const std::uint64_t value : sink) { const std::uint64_t producer = value / kProducerStride; const std::uint64_t index = value % kProducerStride; if (producer >= static_cast(kProducers) || index >= static_cast(kItems)) { ++unknown_values; continue; } // Per-producer FIFO: one consumer sees a producer's items in order. if (static_cast(index) <= last[producer]) { ++order_violations; } last[producer] = static_cast(index); ++seen[static_cast(producer) * kItems + static_cast(index)]; } } std::uint64_t not_exactly_once = 0; for (const int count : seen) { if (count != 1) { ++not_exactly_once; } } Void::Testing::expect_eq(send_errors.load(), 0); Void::Testing::expect_eq(total, static_cast(kProducers) * kItems); Void::Testing::expect_eq(unknown_values, std::uint64_t{0}); Void::Testing::expect_eq(order_violations, std::uint64_t{0}); Void::Testing::expect_eq(not_exactly_once, std::uint64_t{0}); Void::Testing::expect_eq(channel->size(), std::size_t{0}); } Void::Testing::Test channel_deadline_check_order_returns_value() { ManualExecutor exec; ManualClock clock; auto timers = make_timers(exec, clock, 1); auto with_timers = make_channel(exec, ChannelOptions{.capacity = 2, .timers = timers.get()}); auto without_timers = make_channel(exec, ChannelOptions{.capacity = 2}); const TimePoint expired = clock.now(); const TimePoint future = clock.now() + 1s; std::stop_source requested; requested.request_stop(); // 1. stop wins over an expired deadline, a missing timer queue and a // closed channel. SendProbe stop_vs_deadline; auto t1 = run_send(with_timers, 1, OperationOptions{.stop = requested.get_token(), .deadline = expired}, &stop_vs_deadline); start(t1); Void::Testing::expect(stop_vs_deadline.error() == std::optional{ChannelError::cancelled}); Void::Testing::expect(stop_vs_deadline.returned_value() == std::optional{1}); SendProbe stop_vs_no_timers; auto t2 = run_send(without_timers, 2, OperationOptions{.stop = requested.get_token(), .deadline = future}, &stop_vs_no_timers); start(t2); Void::Testing::expect(stop_vs_no_timers.error() == std::optional{ChannelError::cancelled}); Void::Testing::expect(stop_vs_no_timers.returned_value() == std::optional{2}); without_timers->close(); SendProbe stop_vs_closed; auto t3 = run_send(without_timers, 3, OperationOptions{.stop = requested.get_token()}, &stop_vs_closed); start(t3); Void::Testing::expect(stop_vs_closed.error() == std::optional{ChannelError::cancelled}); Void::Testing::expect(stop_vs_closed.returned_value() == std::optional{3}); // 2. An expired deadline (judged by the TimerQueue's clock) beats the // channel state: nothing is buffered even though there was room. SendProbe expired_probe; auto t4 = run_send(with_timers, 4, OperationOptions{.deadline = expired}, &expired_probe); start(t4); Void::Testing::expect(expired_probe.error() == std::optional{ChannelError::timed_out}); Void::Testing::expect(expired_probe.returned_value() == std::optional{4}); Void::Testing::expect_eq(with_timers->size(), std::size_t{0}); // 3. A deadline without timers is invalid_argument, also before `closed`. SendProbe closed_no_timers; auto t5 = run_send(without_timers, 5, OperationOptions{.deadline = future}, &closed_no_timers); start(t5); Void::Testing::expect(closed_no_timers.error() == std::optional{ChannelError::invalid_argument}); Void::Testing::expect(closed_no_timers.returned_value() == std::optional{5}); // 4. A closed channel (no options) reports closed with the value. SendProbe closed_plain; auto t6 = run_send(without_timers, 6, {}, &closed_plain); start(t6); Void::Testing::expect(closed_plain.error() == std::optional{ChannelError::closed}); Void::Testing::expect(closed_plain.returned_value() == std::optional{6}); // 5. A future deadline with room succeeds on the fast path and leaves no // timer behind. SendProbe fast; auto t7 = run_send(with_timers, 7, OperationOptions{.deadline = future}, &fast); start(t7); Void::Testing::expect(fast.succeeded()); Void::Testing::expect_eq(timers->active_timers(), std::size_t{0}); Void::Testing::expect_eq(with_timers->size(), std::size_t{1}); // 6. When the timer queue refuses the timer the value comes back and no // waiter is left behind: fill the channel, occupy the single timer slot. Void::Testing::require(with_timers->try_send(8).has_value()); auto foreign = timers->schedule_at(future, TimerCallback{[](TimerEvent) noexcept {}}); Void::Testing::require(foreign.has_value()); SendProbe refused; auto t8 = run_send(with_timers, 9, OperationOptions{.deadline = future}, &refused); start(t8); Void::Testing::expect(refused.error() == std::optional{ChannelError::overloaded}); Void::Testing::expect(refused.returned_value() == std::optional{9}); Void::Testing::expect_eq(with_timers->size(), std::size_t{2}); Void::Testing::expect(foreign->cancel()); Void::Testing::expect_eq(exec.drain(), std::size_t{0}); }