diff --git a/include/Void/Async/Timer.hpp b/include/Void/Async/Timer.hpp new file mode 100644 index 0000000..115e0a1 --- /dev/null +++ b/include/Void/Async/Timer.hpp @@ -0,0 +1,686 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ── TimerQueue ──────────────────────────────────────────────────────────────── +// Injected-clock timer queue for Async code (C-03/C-04). +// +// * Deadlines are interpreted ONLY in the injected `MonotonicClock` domain. The +// host clock is never consulted, so a `ManualClock` starting at epoch 0 (or at +// a far-future point) behaves deterministically. +// * Nothing fires on its own: there is no background thread. A timer expires +// only when an owner calls `poll_expired()` after the injected clock reached +// its deadline. `next_deadline()` / `wait_duration()` tell a driver how long +// it may block before the next poll. +// * Timers are kept in a stable min-heap ordered by `(deadline, submission +// seq)`, so equal deadlines fire in submission order. +// * Callbacks run exactly once, with `TimerEvent::expired` (from +// `poll_expired()`) or `TimerEvent::closed` (from `close()` / destruction), +// or never when `TimerHandle::cancel()` returned true. They are always +// invoked on the polling/closing thread OUTSIDE the queue's internal lock, so +// a callback may schedule, cancel, poll or close without deadlocking. +// * `cancel() == false` means the callback has fired or is firing; it does +// NOT mean the callback has finished running. Callbacks referencing state +// that may be destroyed concurrently must capture shared ownership (or look +// the target up under the owner's lock), never a raw pointer into a frame. +// * `sleep_until` / `sleep_for` suspend a coroutine until the timer fires and +// resume it through `executor().post_completion(...)`, never inline from +// `poll_expired()`, `close()` or a stop callback. +// +// Lifetime: the completion executor and the clock must outlive the queue, and +// the executor must keep accepting completions until every sleeper settled by +// `close()` / `~TimerQueue()` has been resumed. A `TimerHandle` may safely +// outlive the queue. A suspended sleep task may be destroyed only while its +// timer is still pending and the destruction is serialized with poll, close +// and stop; once its timer has been settled (fired, cancelled or closed) the +// task must stay alive until its posted resume has run. Shutdown order: +// `close()`, then drain the completion executor, then destroy sleep tasks. +// `close()` does not wait for callbacks already claimed by a concurrent +// `poll_expired()` or for a stop callback mid-settle; they may still post +// after `close()` returns. + +namespace Void::Async +{ + +struct TimerQueueOptions { + // Maximum number of simultaneously pending timers (sleepers included). + // Zero is rejected by TimerQueue::create with invalid_argument. + std::size_t max_timers{1024}; +}; + +enum class TimerEvent : std::uint8_t { + expired, + closed +}; + +using TimerCallback = std::move_only_function; + +class TimerHandle; +class TimerQueue; + +namespace detail +{ + +enum class TimerEntryState : std::uint8_t { + pending, + fired, + cancelled +}; + +class TimerCore; + +// Shared per-timer state. The single atomic pending -> {fired, cancelled} +// transition decides the timer's fate; the transition winner exclusively owns +// `callback` afterwards (fire/close: invoke then destroy; cancel: destroy). +struct TimerEntry { + TimerEntry(TimerCallback cb, std::weak_ptr owner) noexcept + : callback(std::move(cb)) + , core(std::move(owner)) + { + } + + TimerEntry(const TimerEntry&) = delete; + TimerEntry& operator=(const TimerEntry&) = delete; + + [[nodiscard]] bool try_leave_pending(TimerEntryState to) noexcept + { + TimerEntryState expected = TimerEntryState::pending; + return state.compare_exchange_strong( + expected, to, std::memory_order_acq_rel, std::memory_order_acquire); + } + + [[nodiscard]] bool is_pending() const noexcept + { + return state.load(std::memory_order_acquire) == TimerEntryState::pending; + } + + std::atomic state{TimerEntryState::pending}; + TimerCallback callback; + // Weak: the heap owns entries, so a strong back-reference would form a + // core -> heap -> entry -> core cycle. + std::weak_ptr core; +}; + +struct TimerNode { + Void::Time::MonotonicClock::time_point deadline{}; + std::uint64_t seq{0}; + std::shared_ptr entry{}; +}; + +// Heap comparator: std::*_heap build max-heaps, so "later" yields a min-heap +// on (deadline, seq). +struct TimerNodeLater { + [[nodiscard]] bool operator()(const TimerNode& a, const TimerNode& b) const noexcept + { + if (a.deadline != b.deadline) { + return a.deadline > b.deadline; + } + return a.seq > b.seq; + } +}; + +// Shared queue core. Owned by the TimerQueue and by in-flight sleep frames; +// referenced weakly by entries so TimerHandle::cancel() stays valid after the +// queue is gone. +// +// Invariants (under mu_): every pending entry is in heap_; heap_ holds only +// pending entries and cancelled tombstones; heap_.size() == live_ + +// tombstones_; live_ <= max_timers_; tombstones are compacted away before an +// admission whenever they exceed max_timers_, so heap_.size() <= 2*max_timers_. +// No user code (callbacks, callback destructors, clock reads) runs under mu_. +class TimerCore : public std::enable_shared_from_this +{ +public: + using time_point = Void::Time::MonotonicClock::time_point; + + TimerCore(Executor& executor, + const Void::Time::MonotonicClock& clock, + std::size_t max_timers) noexcept + : executor_(executor) + , clock_(clock) + , max_timers_(max_timers) + { + } + + TimerCore(const TimerCore&) = delete; + TimerCore& operator=(const TimerCore&) = delete; + + [[nodiscard]] Executor& executor() noexcept { return executor_; } + [[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept { return clock_; } + + [[nodiscard]] bool is_closed() const noexcept + { + return closed_.load(std::memory_order_acquire); + } + + [[nodiscard]] std::size_t live() const noexcept + { + return live_.load(std::memory_order_acquire); + } + + [[nodiscard]] std::expected, AdmissionError> + admit(time_point when, TimerCallback callback) + { + if (closed_.load(std::memory_order_acquire)) { + return std::unexpected{AdmissionError::stopped}; + } + // Declared before the lock: on rejection the entry (and the caller's + // callback inside it) is destroyed after the lock is released. + auto entry = std::make_shared(std::move(callback), weak_from_this()); + std::lock_guard lk{mu_}; + if (closed_.load(std::memory_order_relaxed)) { + return std::unexpected{AdmissionError::stopped}; + } + if (live_.load(std::memory_order_relaxed) >= max_timers_) { + return std::unexpected{AdmissionError::overloaded}; + } + if (tombstones_ > max_timers_) { + compact_locked(); + } + heap_.push_back(TimerNode{when, next_seq_, entry}); + std::push_heap(heap_.begin(), heap_.end(), TimerNodeLater{}); + ++next_seq_; + live_.fetch_add(1, std::memory_order_acq_rel); + return entry; + } + + // pending -> cancelled under the lock (serialized with poll/close/compact). + [[nodiscard]] bool cancel_transition(TimerEntry& entry) noexcept + { + std::lock_guard lk{mu_}; + if (!entry.try_leave_pending(TimerEntryState::cancelled)) { + return false; + } + live_.fetch_sub(1, std::memory_order_acq_rel); + ++tombstones_; + return true; + } + + [[nodiscard]] std::size_t poll_expired() + { + const time_point now = clock_.now(); + std::vector> due; + { + std::lock_guard lk{mu_}; + while (!heap_.empty() && !(now < heap_.front().deadline)) { + if (due.size() == due.capacity()) { + // Reserve before popping so a fired entry always has a + // slot; under allocation failure the rest stays queued for + // the next poll instead of being lost. + try { + due.reserve(due.empty() ? std::size_t{8} : due.size() * 2); + } catch (...) { + break; + } + } + std::pop_heap(heap_.begin(), heap_.end(), TimerNodeLater{}); + std::shared_ptr entry = std::move(heap_.back().entry); + heap_.pop_back(); + if (entry->try_leave_pending(TimerEntryState::fired)) { + live_.fetch_sub(1, std::memory_order_acq_rel); + due.push_back(std::move(entry)); + } else { + // Cancelled tombstone; cancel() already took its callback. + --tombstones_; + } + } + } + for (auto& entry : due) { + invoke_and_release(*entry, TimerEvent::expired); + } + return due.size(); + } + + [[nodiscard]] std::optional next_deadline() + { + std::lock_guard lk{mu_}; + prune_top_locked(); + if (heap_.empty()) { + return std::nullopt; + } + return heap_.front().deadline; + } + + void close() noexcept + { + std::vector drained; + { + std::lock_guard lk{mu_}; + if (closed_.load(std::memory_order_relaxed)) { + return; + } + closed_.store(true, std::memory_order_release); + drained.swap(heap_); + tombstones_ = 0; + std::size_t kept = 0; + for (auto& node : drained) { + if (node.entry->try_leave_pending(TimerEntryState::fired)) { + if (&drained[kept] != &node) { + drained[kept] = std::move(node); + } + ++kept; + } + } + drained.erase(drained.begin() + static_cast(kept), + drained.end()); + live_.store(0, std::memory_order_release); + } + std::sort(drained.begin(), drained.end(), + [](const TimerNode& a, const TimerNode& b) noexcept { + return TimerNodeLater{}(b, a); + }); + for (auto& node : drained) { + invoke_and_release(*node.entry, TimerEvent::closed); + } + } + +private: + static void invoke_and_release(TimerEntry& entry, TimerEvent event) noexcept + { + // Move the callback to this stack frame so it outlives anything the + // invocation may destroy, and is released after it returns. + TimerCallback callback{std::move(entry.callback)}; + entry.callback = nullptr; + if (callback) { + callback(event); + } + } + + void prune_top_locked() noexcept + { + while (!heap_.empty() && !heap_.front().entry->is_pending()) { + std::pop_heap(heap_.begin(), heap_.end(), TimerNodeLater{}); + heap_.pop_back(); + --tombstones_; + } + } + + void compact_locked() noexcept + { + std::erase_if(heap_, [](const TimerNode& node) noexcept { + return !node.entry->is_pending(); + }); + std::make_heap(heap_.begin(), heap_.end(), TimerNodeLater{}); + tombstones_ = 0; + } + + Executor& executor_; + const Void::Time::MonotonicClock& clock_; + const std::size_t max_timers_; + std::mutex mu_{}; + std::vector heap_{}; + std::uint64_t next_seq_{0}; + std::size_t tombstones_{0}; + std::atomic live_{0}; + std::atomic closed_{false}; +}; + +[[nodiscard]] inline bool cancel_timer_entry(TimerEntry& entry) noexcept +{ + bool won = false; + if (auto core = entry.core.lock()) { + won = core->cancel_transition(entry); + } else { + // The core is gone only after close() moved every pending entry to + // `fired`, so this transition is expected to fail; it is still the + // authoritative check. + won = entry.try_leave_pending(TimerEntryState::cancelled); + } + if (won) { + // The cancel winner owns the callback: release it now, outside the + // queue lock, so a cancelled tombstone retains no user state. + TimerCallback discarded{std::move(entry.callback)}; + entry.callback = nullptr; + } + return won; +} + +} // namespace detail + +// Move-only reference to one scheduled timer. Destroying or overwriting a +// handle does NOT cancel the timer (the timer is detached and still fires). +class TimerHandle +{ +public: + TimerHandle() noexcept = default; + TimerHandle(TimerHandle&&) noexcept = default; + TimerHandle& operator=(TimerHandle&&) noexcept = default; + TimerHandle(const TimerHandle&) = delete; + TimerHandle& operator=(const TimerHandle&) = delete; + ~TimerHandle() = default; + + // Returns true when this call moved the timer from pending to cancelled: + // the callback will never run and has already been destroyed (released + // outside the queue lock) when cancel() returns. + // + // Returns false when the handle is empty, the timer was already cancelled, + // or the callback has fired / is firing (expired or closed). false does + // NOT mean the callback has finished running: it may still be executing on + // the polling or closing thread. A callback that touches state which may + // be destroyed after a failed cancel() (e.g. a waiter node inside a + // coroutine frame) must capture shared ownership of that state, or look it + // up under the owner's own lock; it must never hold a raw pointer into a + // frame. Safe to call after the TimerQueue was destroyed (returns false, + // since destruction already delivered TimerEvent::closed). + // + // WARNING: when cancel() returns true (and when schedule_at() rejects a + // timer) the callback object is destroyed synchronously on the caller's + // thread. Do not call cancel() while holding a lock L if the callback may + // hold the last reference to something whose destructor takes or waits on + // L (e.g. a std::stop_callback whose callback blocks on L): move the + // handle out under the lock and cancel after unlocking, or make the + // callback hold only a weak/non-last reference. + bool cancel() noexcept + { + return entry_ ? detail::cancel_timer_entry(*entry_) : false; + } + + // True when the handle refers to a timer (i.e. it was returned by + // schedule_at and not moved from); unaffected by the timer's state. + [[nodiscard]] bool valid() const noexcept { return entry_ != nullptr; } + +private: + friend class TimerQueue; + + explicit TimerHandle(std::shared_ptr entry) noexcept + : entry_(std::move(entry)) + { + } + + std::shared_ptr entry_{}; +}; + +namespace detail +{ + +struct TimerSleepTarget { + bool relative{false}; + Void::Time::MonotonicClock::time_point when{}; + std::chrono::nanoseconds delta{}; +}; + +// Stop callback for a pending sleep. The entry's pending -> cancelled +// transition is the arbiter: the sleep settles `cancelled` only when this +// callback won it; otherwise the timer callback (expired/closed) settles it. +class TimerSleepStop +{ +public: + TimerSleepStop(std::shared_ptr entry, + std::shared_ptr> state) noexcept + : entry_(std::move(entry)) + , state_(std::move(state)) + { + } + + void operator()() const noexcept + { + // Copy first: once the continuation is dispatched, the frame that + // owns this callback object may resume and be destroyed. + auto entry = entry_; + auto state = state_; + if (cancel_timer_entry(*entry)) { + if (auto ticket = state->try_commit_cancelled("TimerQueue sleep cancelled"); + ticket.has_value()) { + ticket->dispatch(); + } + } + } + +private: + std::shared_ptr entry_; + std::shared_ptr> state_; +}; + +// Cancels the sleep's timer when the frame ends, including destruction of a +// suspended sleep task, so an abandoned frame is never resumed by a later +// poll or close (unless the timer already fired). +struct TimerSleepGuard { + std::shared_ptr entry{}; + + TimerSleepGuard() noexcept = default; + explicit TimerSleepGuard(std::shared_ptr e) noexcept : entry(std::move(e)) {} + TimerSleepGuard(const TimerSleepGuard&) = delete; + TimerSleepGuard& operator=(const TimerSleepGuard&) = delete; + + ~TimerSleepGuard() + { + if (entry) { + (void)cancel_timer_entry(*entry); + } + } +}; + +[[nodiscard]] inline Void::Result::Error timer_admission_error(AdmissionError error) +{ + if (error == AdmissionError::overloaded) { + return make_async_error(AdmissionError::overloaded, "TimerQueue capacity exceeded"); + } + if (error == AdmissionError::stopped) { + return make_async_error(AdmissionError::stopped, "TimerQueue is closed"); + } + return make_async_error(error); +} + +// The sleep body is a free coroutine holding the core by value: it never +// touches the TimerQueue object, so a lazily started or suspended sleep task +// may outlive the queue. +inline Coro::Task> timer_sleep( + std::shared_ptr core, + TimerSleepTarget target, + OperationOptions options) +{ + using Void::Result::Result; + + if (options.stop.stop_requested()) { + co_return Result{std::unexpect, make_async_error( + AsyncErrorCode::cancelled, "TimerQueue sleep cancelled before admission")}; + } + if (core->is_closed()) { + co_return Result{std::unexpect, timer_admission_error(AdmissionError::stopped)}; + } + + // Single read of the injected clock; the host clock is never consulted. + const auto now = core->clock().now(); + const auto when = + target.relative ? Void::Time::saturating_add(now, target.delta) : target.when; + if (options.deadline.has_value() && now >= *options.deadline) { + co_return Result{std::unexpect, make_async_error( + AsyncErrorCode::timeout, "TimerQueue sleep deadline expired before admission")}; + } + + // One timer per sleeper at min(when, deadline); the outcome is fixed at + // registration: timeout only when the deadline is strictly earlier. + const bool deadline_first = options.deadline.has_value() && *options.deadline < when; + const auto fire_at = deadline_first ? *options.deadline : when; + + // Non-null resume executor: every dispatch goes through post_completion. + auto state = OperationState::create(OperationOptions{}, &core->executor()); + auto admitted = core->admit( + fire_at, + TimerCallback{[state, deadline_first](TimerEvent event) noexcept { + std::optional ticket; + if (event == TimerEvent::closed) { + ticket = state->try_commit_error( + make_async_error(AsyncErrorCode::stopped, "TimerQueue closed while sleeping"), + DomainOutcomeKind::cancelled); + } else if (deadline_first) { + ticket = state->try_commit_timeout("TimerQueue sleep deadline expired"); + } else { + ticket = state->try_commit_value(); + } + if (ticket.has_value()) { + ticket->dispatch(); + } + }}); + if (!admitted.has_value()) { + co_return Result{std::unexpect, timer_admission_error(admitted.error())}; + } + + TimerSleepGuard guard{std::move(*admitted)}; + // Registered after admission so it can cancel the timer. If stop was + // requested meanwhile, the constructor runs the callback inline; the + // state then settles before suspension and the co_await completes + // without suspending (no inline resume of a suspended frame). + std::optional> stop_cb; + if (options.stop.stop_possible()) { + stop_cb.emplace(options.stop, TimerSleepStop{guard.entry, state}); + } + + auto result = co_await state->awaitable(nullptr); + // Waits for a concurrently running stop callback before the frame moves on. + stop_cb.reset(); + co_return result; +} + +} // namespace detail + +class TimerQueue +{ +public: + using time_point = Void::Time::MonotonicClock::time_point; + + // Errors: invalid_argument when options.max_timers == 0. + [[nodiscard]] static Void::Result::Result> + create(Executor& completion_executor, + const Void::Time::MonotonicClock& clock, + TimerQueueOptions options = {}) + { + if (options.max_timers == 0) { + return std::unexpected{make_async_error( + AsyncErrorCode::invalid_argument, + "TimerQueue max_timers must be greater than zero")}; + } + auto core = std::make_shared( + completion_executor, clock, options.max_timers); + return std::unique_ptr(new TimerQueue(std::move(core))); + } + + TimerQueue(const TimerQueue&) = delete; + TimerQueue& operator=(const TimerQueue&) = delete; + TimerQueue(TimerQueue&&) = delete; + TimerQueue& operator=(TimerQueue&&) = delete; + + // Equivalent to close(): pending callbacks receive TimerEvent::closed and + // pending sleepers settle `stopped` (resumed via the completion executor). + ~TimerQueue() { close(); } + + // Suspends until `when` (in the injected clock domain) has been reached + // and observed by poll_expired(). A `when` already in the past still needs + // a poll. Results (exactly one): + // {} — the timer fired at `when`; + // cancelled — options.stop requested (before admission or while pending); + // timeout — options.deadline is already expired at admission, or + // is strictly earlier than `when` and fired first; + // overloaded — max_timers pending timers already; + // stopped — the queue is (or becomes) closed. + // Checks before admission complete without suspending. A suspended sleep + // is always resumed via executor().post_completion. Destroying a suspended + // sleep task cancels its timer only while the timer is still pending (see + // the lifetime rules at the top of this header); after settlement the task + // must outlive its posted resume. + [[nodiscard]] Coro::Task> + sleep_until(time_point when, OperationOptions options = {}) + { + return detail::timer_sleep( + core_, detail::TimerSleepTarget{false, when, {}}, std::move(options)); + } + + // sleep_until(saturating_add(clock().now(), duration)); "now" is read when + // the task starts. Negative or huge durations saturate instead of wrapping. + [[nodiscard]] Coro::Task> + sleep_for(std::chrono::nanoseconds duration, OperationOptions options = {}) + { + return detail::timer_sleep( + core_, detail::TimerSleepTarget{true, {}, duration}, std::move(options)); + } + + // Schedules `on_event` to run exactly once with TimerEvent::expired (from + // poll_expired at or after `when`) or TimerEvent::closed (from close or + // destruction), or never when TimerHandle::cancel() returns true. + // Errors: invalid_argument (empty callback), overloaded (max_timers + // pending), stopped (closed). On error the callback is destroyed unrun. + [[nodiscard]] std::expected + schedule_at(time_point when, TimerCallback on_event) + { + if (!on_event) { + return std::unexpected{AdmissionError::invalid_argument}; + } + auto admitted = core_->admit(when, std::move(on_event)); + if (!admitted.has_value()) { + return std::unexpected{admitted.error()}; + } + return TimerHandle{std::move(*admitted)}; + } + + // Reads clock().now() once, removes every pending timer whose deadline is + // <= now in (deadline, seq) order, then runs their callbacks outside the + // internal lock. Timers scheduled by those callbacks fire on a later poll. + // Returns the number of callbacks fired. + [[nodiscard]] std::size_t poll_expired() { return core_->poll_expired(); } + + // Earliest pending deadline (cancelled timers are skipped). + [[nodiscard]] std::optional next_deadline() const + { + return core_->next_deadline(); + } + + // Time until the next pending deadline measured with the injected clock, + // clamped to [0, max_wait]; 0 when a timer is already due; max_wait when + // nothing is pending. + [[nodiscard]] std::chrono::nanoseconds wait_duration(std::chrono::nanoseconds max_wait) const noexcept + { + const auto cap = max_wait < std::chrono::nanoseconds::zero() + ? std::chrono::nanoseconds::zero() + : max_wait; + const auto next = core_->next_deadline(); + if (!next.has_value()) { + return cap; + } + return std::min(Void::Time::remaining_until(core_->clock(), *next), cap); + } + + // Number of pending timers (sleepers included); cancelled timers excluded. + [[nodiscard]] std::size_t active_timers() const noexcept { return core_->live(); } + + // Idempotent. Marks the queue closed (later schedule_at/sleep_* return + // stopped), then runs every pending callback once with TimerEvent::closed + // in (deadline, seq) order, outside the internal lock. + void close() noexcept { core_->close(); } + + [[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept + { + return core_->clock(); + } + + [[nodiscard]] Executor& executor() noexcept { return core_->executor(); } + +private: + explicit TimerQueue(std::shared_ptr core) noexcept + : core_(std::move(core)) + { + } + + std::shared_ptr core_; +}; + +} // namespace Void::Async diff --git a/include/Void/Time/Clock.hpp b/include/Void/Time/Clock.hpp index 6b3556b..b680446 100644 --- a/include/Void/Time/Clock.hpp +++ b/include/Void/Time/Clock.hpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include namespace Void::Time { @@ -207,4 +209,46 @@ private: return std::chrono::nanoseconds{dl_ns - now_ns}; } +/// Overflow-safe `point + delta` in the monotonic domain. A result that would +/// leave the representable range clamps to `time_point::max()` (positive +/// overflow) or `time_point::min()` (negative overflow) instead of wrapping. +/// Negative `delta` values are allowed. +[[nodiscard]] inline MonotonicClock::time_point + saturating_add(MonotonicClock::time_point point, + std::chrono::nanoseconds delta) noexcept +{ + using TimePoint = MonotonicClock::time_point; + using Duration = TimePoint::duration; + using Rep = Duration::rep; + static_assert(std::is_integral_v && std::is_signed_v, + "saturating_add requires a signed integral time_point rep"); + static_assert(std::ratio_greater_equal_v && + std::numeric_limits::digits >= + std::numeric_limits::digits, + "saturating_add requires a time_point period of at least " + "one nanosecond and a rep at least as wide as nanoseconds"); + + // Converting to an equal or coarser period only shrinks the magnitude, so + // this cast never overflows. + const Rep step = std::chrono::duration_cast(delta).count(); + const Rep base = point.time_since_epoch().count(); + if (step > 0 && base > std::numeric_limits::max() - step) { + return TimePoint::max(); + } + if (step < 0 && base < std::numeric_limits::min() - step) { + return TimePoint::min(); + } + return TimePoint{Duration{base + step}}; +} + +/// Deadline `timeout` after `clock.now()`, computed in `clock`'s own domain +/// with `saturating_add` (so a huge or `nanoseconds::max()` timeout yields +/// `time_point::max()` rather than an overflowed, already-expired deadline). +[[nodiscard]] inline MonotonicClock::time_point + deadline_after(const MonotonicClock& clock, + std::chrono::nanoseconds timeout) noexcept +{ + return saturating_add(clock.now(), timeout); +} + } // namespace Void::Time diff --git a/tests/standalone/Async/DeadlineDomains.cpp b/tests/standalone/Async/DeadlineDomains.cpp new file mode 100644 index 0000000..cbedc86 --- /dev/null +++ b/tests/standalone/Async/DeadlineDomains.cpp @@ -0,0 +1,244 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace +{ + +using namespace Void::Async; +using namespace std::chrono_literals; +using TimePoint = Void::Time::MonotonicClock::time_point; +using Void::Time::ManualClock; + +TimePoint at(std::chrono::nanoseconds offset) +{ + return TimePoint{std::chrono::duration_cast(offset)}; +} + +void advance_clock(ManualClock& clock, std::chrono::nanoseconds delta) +{ + Void::Testing::require(clock.advance(delta).has_value()); +} + +std::optional code_of(const Void::Result::Result& res) +{ + if (res.has_value()) { + return std::nullopt; + } + return static_cast(res.error().code().value); +} + +Void::Coro::Task schedule_into(Executor* exec, + OperationOptions options, + const Void::Time::MonotonicClock* clock, + std::optional>* out) +{ + *out = co_await schedule_on(*exec, std::move(options), *clock); +} + +Void::Coro::Task schedule_host_into(Executor* exec, + OperationOptions options, + std::optional>* out) +{ + *out = co_await schedule_on(*exec, std::move(options)); +} + +Void::Coro::Task increment_task(int* counter) +{ + ++(*counter); + co_return; +} + +struct SleepProbe { + int resumes{0}; + std::optional> result{}; +}; + +Void::Coro::Task await_sleep(Void::Coro::Task> sleep, + SleepProbe* probe) +{ + auto res = co_await sleep; + probe->result = std::move(res); + ++probe->resumes; +} + +void start(Void::Coro::Task& task) +{ + task.handle().resume(); +} + +} // namespace + +Void::Testing::Test deadline_domain_schedule_on_and_scope_admission_injected_clock() +{ + // Precondition: the host steady clock is far past the manual-domain + // deadline used below, so host comparisons treat it as expired. + Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms); + + ManualExecutor exec; + ManualClock clock; // epoch 0 + const OperationOptions opts{.deadline = at(5ms)}; + + // One deadline value, two domains. + Void::Testing::expect(is_deadline_expired(opts)); + Void::Testing::expect(!is_deadline_expired(opts, clock)); + auto op = OperationState::create(opts); + Void::Testing::expect(op->is_deadline_expired()); + Void::Testing::expect(!op->is_deadline_expired(clock)); + + // schedule_on in the manual domain is admitted and runs. + std::optional> admitted; + auto t1 = schedule_into(&exec, opts, &clock, &admitted); + start(t1); + Void::Testing::expect(!admitted.has_value()); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::require(admitted.has_value()); + Void::Testing::expect(admitted->has_value()); + + // The default (host) clock rejects the same manual-domain deadline. + std::optional> host_rejected; + auto t2 = schedule_host_into(&exec, opts, &host_rejected); + start(t2); + Void::Testing::require(host_rejected.has_value()); + Void::Testing::expect(code_of(*host_rejected) == AsyncErrorCode::timeout); + Void::Testing::expect(exec.empty()); + + // Expiry in the manual domain happens only when the manual clock advances. + advance_clock(clock, 4ms); + std::optional> still_ok; + auto t3 = schedule_into(&exec, opts, &clock, &still_ok); + start(t3); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::require(still_ok.has_value()); + Void::Testing::expect(still_ok->has_value()); + + advance_clock(clock, 1ms); + std::optional> expired; + auto t4 = schedule_into(&exec, opts, &clock, &expired); + start(t4); + Void::Testing::require(expired.has_value()); + Void::Testing::expect(code_of(*expired) == AsyncErrorCode::timeout); + Void::Testing::expect(exec.empty()); + + // Expiry observed between admission and execution is reported on resume. + ManualClock hop_clock; + std::optional> hop; + auto t5 = schedule_into(&exec, opts, &hop_clock, &hop); + start(t5); + Void::Testing::expect(!hop.has_value()); + advance_clock(hop_clock, 5ms); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::require(hop.has_value()); + Void::Testing::expect(code_of(*hop) == AsyncErrorCode::timeout); + + // TaskScope admission uses the scope's injected clock. + ManualClock scope_clock; + int ran = 0; + { + TaskScope scope{exec, TaskScopeOptions{}, scope_clock}; + auto first = scope.spawn(increment_task(&ran), opts); + Void::Testing::expect(first.has_value()); + advance_clock(scope_clock, 5ms); + auto late = scope.spawn(increment_task(&ran), opts); + Void::Testing::require(!late.has_value()); + Void::Testing::expect(late.error() == AdmissionError::deadline_expired); + Void::Testing::expect(scope.join_pumping(exec).has_value()); + } + { + TaskScope host_scope{exec}; + auto host_late = host_scope.spawn(increment_task(&ran), opts); + Void::Testing::require(!host_late.has_value()); + Void::Testing::expect(host_late.error() == AdmissionError::deadline_expired); + Void::Testing::expect(host_scope.join_pumping(exec).has_value()); + } + Void::Testing::expect_eq(ran, 1); +} + +Void::Testing::Test deadline_domain_timer_and_operation_deadline_same_manual_clock() +{ + Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms); + + ManualExecutor exec; + ManualClock clock; // epoch 0 + auto created = TimerQueue::create(exec, clock); + Void::Testing::require(created.has_value()); + auto q = std::move(*created); + Void::Testing::expect(&q->clock() == &clock); + Void::Testing::expect(&q->executor() == &exec); + + // An OperationOptions deadline in the ManualClock domain bounds the sleep. + const OperationOptions opts{.deadline = at(3ms)}; + SleepProbe probe; + auto task = await_sleep(q->sleep_until(at(8ms), opts), &probe); + start(task); + Void::Testing::expect(!task.done()); // the host clock would call it expired + + Void::Testing::require(q->next_deadline().has_value()); + Void::Testing::expect(*q->next_deadline() == at(3ms)); + Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{3ms}); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect(exec.empty()); + + advance_clock(clock, 2ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect(exec.empty()); + Void::Testing::expect_eq(probe.resumes, 0); + + // Advance + explicit poll expires it once; the resume goes through the + // completion executor. + advance_clock(clock, 1ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + 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::require(probe.result.has_value()); + Void::Testing::expect(code_of(*probe.result) == AsyncErrorCode::timeout); + Void::Testing::expect_eq(q->active_timers(), std::size_t{0}); + + // Passing `when` later fires nothing and never produces a second result. + advance_clock(clock, 10ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); + Void::Testing::expect_eq(probe.resumes, 1); + + // The same deadline is expired for schedule_on in the same manual domain. + std::optional> scheduled; + auto sched = schedule_into(&exec, opts, &q->clock(), &scheduled); + start(sched); + Void::Testing::require(scheduled.has_value()); + Void::Testing::expect(code_of(*scheduled) == AsyncErrorCode::timeout); + + // A deadline equal to `when` is not earlier: the sleep completes normally. + SleepProbe equal; + const auto target = Void::Time::deadline_after(clock, 5ms); + auto equal_task = + await_sleep(q->sleep_until(target, OperationOptions{.deadline = target}), &equal); + start(equal_task); + advance_clock(clock, 5ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::require(equal.result.has_value()); + Void::Testing::expect(equal.result->has_value()); + + // A deadline later than `when` does not interfere either. + SleepProbe later; + auto later_task = await_sleep( + q->sleep_for(1ms, OperationOptions{.deadline = Void::Time::deadline_after(clock, 2ms)}), + &later); + start(later_task); + advance_clock(clock, 2ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::require(later.result.has_value()); + Void::Testing::expect(later.result->has_value()); +} diff --git a/tests/standalone/Async/TimerQueue.cpp b/tests/standalone/Async/TimerQueue.cpp new file mode 100644 index 0000000..fc94e54 --- /dev/null +++ b/tests/standalone/Async/TimerQueue.cpp @@ -0,0 +1,1183 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using namespace Void::Async; +using namespace std::chrono_literals; +using TimePoint = Void::Time::MonotonicClock::time_point; +using Void::Time::ManualClock; + +TimePoint at(std::chrono::nanoseconds since_epoch) +{ + return TimePoint{std::chrono::duration_cast(since_epoch)}; +} + +std::chrono::nanoseconds since_epoch(TimePoint tp) +{ + return std::chrono::duration_cast(tp.time_since_epoch()); +} + +void advance_clock(ManualClock& clock, std::chrono::nanoseconds delta) +{ + Void::Testing::require(clock.advance(delta).has_value()); +} + +std::unique_ptr make_queue(Executor& exec, + const Void::Time::MonotonicClock& clock, + std::size_t max_timers = 1024) +{ + auto created = TimerQueue::create(exec, clock, TimerQueueOptions{.max_timers = max_timers}); + Void::Testing::require(created.has_value()); + return std::move(*created); +} + +// Assertion-free variant for tight race loops: the runner retains only the +// first 1,000 assertions per test (X-QA-02), so loops count failures instead. +std::unique_ptr try_make_queue(Executor& exec, + const Void::Time::MonotonicClock& clock) +{ + auto created = TimerQueue::create(exec, clock, TimerQueueOptions{}); + return created.has_value() ? std::move(*created) : nullptr; +} + +struct SleepProbe { + int resumes{0}; + int order{-1}; + std::optional> result{}; + + [[nodiscard]] bool succeeded() const { return result.has_value() && result->has_value(); } + + [[nodiscard]] std::optional code() const + { + if (!result.has_value() || result->has_value()) { + return std::nullopt; + } + return static_cast(result->error().code().value); + } +}; + +// Awaits an already-created sleep task (created while the queue is alive), so +// the wrapper never touches the TimerQueue itself. +Void::Coro::Task await_sleep(Void::Coro::Task> sleep, + SleepProbe* probe, + int* sequence = nullptr) +{ + auto res = co_await sleep; + probe->result = std::move(res); + ++probe->resumes; + if (sequence != nullptr) { + probe->order = (*sequence)++; + } +} + +void start(Void::Coro::Task& task) +{ + task.handle().resume(); +} + +void spin_until(const std::atomic& flag) +{ + while (!flag.load(std::memory_order_acquire)) { + std::this_thread::yield(); + } +} + +// Requests stop whenever it is read: lands a stop between the sleep's +// pre-admission stop check and its suspension, deterministically. +class StopOnReadClock final : public Void::Time::MonotonicClock +{ +public: + explicit StopOnReadClock(std::stop_source source) noexcept + : source_(std::move(source)) + { + } + + [[nodiscard]] time_point now() const noexcept override + { + source_.request_stop(); + return time_point{}; + } + +private: + mutable std::stop_source source_; +}; + +} // namespace + +Void::Testing::Test timer_manual_advance_and_poll_fires_exactly_once() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + + SleepProbe probe; + auto task = await_sleep(q->sleep_until(at(10ms)), &probe); + start(task); + Void::Testing::expect(!task.done()); + Void::Testing::expect_eq(probe.resumes, 0); + + int fired = 0; + TimerEvent seen = TimerEvent::closed; + auto handle = q->schedule_at(at(10ms), [&fired, &seen](TimerEvent event) noexcept { + ++fired; + seen = event; + }); + Void::Testing::require(handle.has_value()); + Void::Testing::expect(handle->valid()); + Void::Testing::expect_eq(q->active_timers(), std::size_t{2}); + + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + advance_clock(clock, 9ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect(exec.empty()); + Void::Testing::expect_eq(fired, 0); + + advance_clock(clock, 1ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{2}); + Void::Testing::expect_eq(fired, 1); + Void::Testing::expect(seen == TimerEvent::expired); + // The sleeper is resumed through post_completion, never inline from poll. + Void::Testing::expect_eq(probe.resumes, 0); + Void::Testing::expect(!exec.empty()); + Void::Testing::expect_eq(q->active_timers(), std::size_t{0}); + + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(probe.resumes, 1); + Void::Testing::expect(probe.succeeded()); + Void::Testing::expect(task.done()); + + // Nothing fires twice, however often the clock advances and polls run. + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + advance_clock(clock, 1h); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); + Void::Testing::expect_eq(fired, 1); + Void::Testing::expect_eq(probe.resumes, 1); + Void::Testing::expect(!handle->cancel()); + Void::Testing::expect(!q->next_deadline().has_value()); +} + +Void::Testing::Test timer_equal_deadlines_fire_in_submission_order() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + + std::vector order; + std::vector handles; + auto add = [&](TimePoint when, int id) { + auto h = q->schedule_at(when, [&order, id](TimerEvent event) noexcept { + if (event == TimerEvent::expired) { + order.push_back(id); + } + }); + Void::Testing::require(h.has_value()); + handles.push_back(std::move(*h)); + }; + + add(at(20ms), 0); + add(at(10ms), 1); + add(at(20ms), 2); + add(at(10ms), 3); + add(at(15ms), 4); + add(at(20ms), 5); + + advance_clock(clock, 20ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{6}); + Void::Testing::expect(order == std::vector{1, 3, 4, 0, 2, 5}); + + // A larger batch at one deadline keeps strict FIFO order. + order.clear(); + for (int id = 0; id < 32; ++id) { + add(at(30ms), id); + } + advance_clock(clock, 10ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{32}); + std::vector expected_fifo; + for (int id = 0; id < 32; ++id) { + expected_fifo.push_back(id); + } + Void::Testing::expect(order == expected_fifo); + + // Sleepers sharing a deadline resume in submission order as well. + int sequence = 0; + SleepProbe s0; + SleepProbe s1; + SleepProbe s2; + auto t0 = await_sleep(q->sleep_until(at(40ms)), &s0, &sequence); + auto t1 = await_sleep(q->sleep_until(at(40ms)), &s1, &sequence); + auto t2 = await_sleep(q->sleep_until(at(40ms)), &s2, &sequence); + start(t0); + start(t1); + start(t2); + advance_clock(clock, 10ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{3}); + Void::Testing::expect_eq(exec.drain(), std::size_t{3}); + Void::Testing::expect_eq(s0.order, 0); + Void::Testing::expect_eq(s1.order, 1); + Void::Testing::expect_eq(s2.order, 2); + Void::Testing::expect(s0.succeeded() && s1.succeeded() && s2.succeeded()); +} + +Void::Testing::Test timer_not_fired_without_explicit_poll() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + advance_clock(clock, 10ms); + + // Both deadlines are already in the past when they are registered. + std::atomic fired{0}; + auto handle = q->schedule_at(at(1ms), [&fired](TimerEvent) noexcept { + fired.fetch_add(1, std::memory_order_relaxed); + }); + Void::Testing::require(handle.has_value()); + + SleepProbe probe; + auto task = await_sleep(q->sleep_until(at(2ms)), &probe); + start(task); + Void::Testing::expect(!task.done()); + + advance_clock(clock, 1h); + // Real time passes as well: there is no background thread. + std::this_thread::sleep_for(20ms); + + Void::Testing::expect_eq(fired.load(), 0); + Void::Testing::expect_eq(probe.resumes, 0); + Void::Testing::expect(exec.empty()); + Void::Testing::expect_eq(q->active_timers(), std::size_t{2}); + Void::Testing::require(q->next_deadline().has_value()); + Void::Testing::expect_eq(since_epoch(*q->next_deadline()), std::chrono::nanoseconds{1ms}); + Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{0}); + + Void::Testing::expect_eq(q->poll_expired(), std::size_t{2}); + Void::Testing::expect_eq(fired.load(), 1); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(probe.resumes, 1); + Void::Testing::expect(probe.succeeded()); +} + +Void::Testing::Test timer_manual_epoch_deadline_not_compared_with_host_clock() +{ + // Precondition: the host steady clock is far past the manual-domain + // instants used below, so any host comparison would expire them at once. + Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms); + + ManualExecutor exec; + ManualClock clock; // epoch 0 + auto q = make_queue(exec, clock); + + const OperationOptions opts{.deadline = at(5ms)}; + Void::Testing::expect(is_deadline_expired(opts)); // host default + Void::Testing::expect(!is_deadline_expired(opts, clock)); // injected domain + + SleepProbe sleeper; + auto sleep_task = await_sleep(q->sleep_until(at(2ms), opts), &sleeper); + start(sleep_task); + Void::Testing::expect(!sleep_task.done()); // not timed out at admission + + int fired = 0; + auto handle = q->schedule_at(at(3ms), [&fired](TimerEvent) noexcept { ++fired; }); + Void::Testing::require(handle.has_value()); + + Void::Testing::require(q->next_deadline().has_value()); + Void::Testing::expect_eq(since_epoch(*q->next_deadline()), std::chrono::nanoseconds{2ms}); + Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{2ms}); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect(exec.empty()); + + advance_clock(clock, 2ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(sleeper.succeeded()); + + advance_clock(clock, 1ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(fired, 1); + + // A manual-domain deadline earlier than `when` wins, once, only after the + // manual clock reaches it. + SleepProbe bounded; + auto bounded_task = + await_sleep(q->sleep_until(at(10ms), OperationOptions{.deadline = at(6ms)}), &bounded); + start(bounded_task); + Void::Testing::expect(!bounded_task.done()); + Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{3ms}); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + advance_clock(clock, 3ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(bounded.code() == AsyncErrorCode::timeout); + advance_clock(clock, 10ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect_eq(bounded.resumes, 1); +} + +Void::Testing::Test timer_manual_clock_far_future_initial_point() +{ + const TimePoint far = TimePoint::max() - 24h; + const TimePoint host_point = std::chrono::steady_clock::now() + 1h; + // host_point is in the future for the host but long past for `clock`. + Void::Testing::require(host_point < far); + + ManualExecutor exec; + ManualClock clock{far}; + auto q = make_queue(exec, clock); + + // A manual-past deadline that the host considers future expires at once. + SleepProbe expired; + auto expired_task = + await_sleep(q->sleep_until(far + 1h, OperationOptions{.deadline = host_point}), &expired); + start(expired_task); + Void::Testing::expect(expired_task.done()); + Void::Testing::expect(expired.code() == AsyncErrorCode::timeout); + Void::Testing::expect(exec.empty()); + + // A manual-past `when` fires on the very next poll. + SleepProbe past; + auto past_task = await_sleep(q->sleep_until(host_point), &past); + start(past_task); + Void::Testing::expect(!past_task.done()); + + // Relative sleeps near the top of the range neither overflow nor wrap. + SleepProbe half_hour; + auto half_hour_task = await_sleep(q->sleep_for(30min), &half_hour); + start(half_hour_task); + SleepProbe saturated; + auto saturated_task = await_sleep(q->sleep_for(48h), &saturated); + start(saturated_task); + int fired = 0; + auto handle = q->schedule_at(far + 1h, [&fired](TimerEvent event) noexcept { + if (event == TimerEvent::expired) { + ++fired; + } + }); + Void::Testing::require(handle.has_value()); + + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(past.succeeded()); + + Void::Testing::require(q->next_deadline().has_value()); + Void::Testing::expect(*q->next_deadline() == far + 30min); + Void::Testing::expect_eq(q->wait_duration(1h), std::chrono::nanoseconds{30min}); + + advance_clock(clock, 30min); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(half_hour.succeeded()); + + advance_clock(clock, 30min); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(fired, 1); + + Void::Testing::require(q->next_deadline().has_value()); + Void::Testing::expect(*q->next_deadline() == TimePoint::max()); + Void::Testing::expect_eq(saturated.resumes, 0); + Void::Testing::require(clock.set(TimePoint::max()).has_value()); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(saturated.succeeded()); + Void::Testing::expect_eq(q->active_timers(), std::size_t{0}); +} + +Void::Testing::Test timer_stop_before_admission_and_pending_cancelled_once() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + + // Stop already requested: cancelled without suspending or registering. + std::stop_source early; + early.request_stop(); + SleepProbe pre; + auto pre_task = + await_sleep(q->sleep_until(at(1ms), OperationOptions{.stop = early.get_token()}), &pre); + start(pre_task); + Void::Testing::expect(pre_task.done()); + Void::Testing::expect_eq(pre.resumes, 1); + Void::Testing::expect(pre.code() == AsyncErrorCode::cancelled); + Void::Testing::expect_eq(q->active_timers(), std::size_t{0}); + Void::Testing::expect(exec.empty()); + + // Deadline already expired in the injected domain: timeout, no suspension. + SleepProbe late; + auto late_task = + await_sleep(q->sleep_until(at(1ms), OperationOptions{.deadline = at(0ns)}), &late); + start(late_task); + Void::Testing::expect(late_task.done()); + Void::Testing::expect(late.code() == AsyncErrorCode::timeout); + Void::Testing::expect_eq(q->active_timers(), std::size_t{0}); + Void::Testing::expect(exec.empty()); + + // Stop landing after the pre-admission check but before suspension: the + // stop callback runs inline at registration, cancels the timer, and the + // sleep completes without suspending or posting anything. + std::stop_source racing; + StopOnReadClock stopping_clock{racing}; + auto racing_q = make_queue(exec, stopping_clock); + SleepProbe raced; + auto raced_task = await_sleep( + racing_q->sleep_until(at(1ms), OperationOptions{.stop = racing.get_token()}), &raced); + start(raced_task); + Void::Testing::expect(racing.stop_requested()); + Void::Testing::expect(raced_task.done()); + Void::Testing::expect_eq(raced.resumes, 1); + Void::Testing::expect(raced.code() == AsyncErrorCode::cancelled); + Void::Testing::expect_eq(racing_q->active_timers(), std::size_t{0}); + Void::Testing::expect(!racing_q->next_deadline().has_value()); + Void::Testing::expect_eq(racing_q->poll_expired(), std::size_t{0}); + Void::Testing::expect(exec.empty()); + + // Pending sleeper: stop cancels the timer once and resumes via the executor. + std::stop_source source; + SleepProbe pending; + auto task = + await_sleep(q->sleep_until(at(5ms), OperationOptions{.stop = source.get_token()}), &pending); + start(task); + Void::Testing::expect(!task.done()); + Void::Testing::expect_eq(q->active_timers(), std::size_t{1}); + + Void::Testing::expect(source.request_stop()); + // The slot is released at once, but the frame is not resumed inline. + Void::Testing::expect_eq(pending.resumes, 0); + Void::Testing::expect(!task.done()); + Void::Testing::expect_eq(q->active_timers(), std::size_t{0}); + Void::Testing::expect(!q->next_deadline().has_value()); + Void::Testing::expect(!exec.empty()); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(pending.resumes, 1); + Void::Testing::expect(pending.code() == AsyncErrorCode::cancelled); + + // The cancelled timer never fires and the single result never changes. + advance_clock(clock, 10ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect(!source.request_stop()); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); + Void::Testing::expect_eq(pending.resumes, 1); + Void::Testing::expect(pending.code() == AsyncErrorCode::cancelled); + + // Stop after the timer fired (before the resume ran) does not change the + // outcome: the timer's fate decides. + std::stop_source after; + SleepProbe fired_first; + auto fired_task = await_sleep( + q->sleep_until(at(11ms), OperationOptions{.stop = after.get_token()}), &fired_first); + start(fired_task); + advance_clock(clock, 1ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect(after.request_stop()); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect_eq(fired_first.resumes, 1); + Void::Testing::expect(fired_first.succeeded()); +} + +Void::Testing::Test timer_stop_vs_poll_race_single_result_tsan() +{ + constexpr int kIterations = 300; + ManualExecutor exec; + + int inline_resumes = 0; + int bad_resume_counts = 0; + int mismatches = 0; + int leftovers = 0; + int ok = 0; + int cancelled = 0; + int stopped = 0; + int setup_failures = 0; + + for (int i = 0; i < kIterations; ++i) { + ManualClock clock; + auto q = try_make_queue(exec, clock); + if (!q) { + ++setup_failures; + continue; + } + std::stop_source source; + SleepProbe probe; + auto task = await_sleep( + q->sleep_until(at(1ms), OperationOptions{.stop = source.get_token()}), &probe); + start(task); + if (task.done() || !clock.advance(1ms).has_value()) { + ++setup_failures; + continue; + } + + const bool with_close = (i % 3) == 2; + const int participants = with_close ? 3 : 2; + std::atomic ready{0}; + std::atomic go{false}; + std::atomic polled{0}; + auto rendezvous = [&ready, &go] { + ready.fetch_add(1, std::memory_order_acq_rel); + spin_until(go); + }; + + std::thread stopper{[&] { + rendezvous(); + source.request_stop(); + }}; + std::thread poller{[&] { + rendezvous(); + // Stagger the poller so every winner is exercised. + for (int k = 0; k < i % 4; ++k) { + std::this_thread::yield(); + } + polled.store(q->poll_expired(), std::memory_order_release); + }}; + std::thread closer; + if (with_close) { + closer = std::thread{[&] { + rendezvous(); + q->close(); + }}; + } + while (ready.load(std::memory_order_acquire) < participants) { + std::this_thread::yield(); + } + go.store(true, std::memory_order_release); + stopper.join(); + poller.join(); + if (closer.joinable()) { + closer.join(); + } + + // Every settlement path posts the continuation; none resumes inline. + if (probe.resumes != 0 || task.done()) { + ++inline_resumes; + } + if (exec.drain() != 1 || probe.resumes != 1 || !task.done()) { + ++bad_resume_counts; + } + const bool fired = polled.load(std::memory_order_acquire) == 1; + if (probe.succeeded()) { + ++ok; + mismatches += fired ? 0 : 1; + } else if (probe.code() == AsyncErrorCode::cancelled) { + ++cancelled; + mismatches += fired ? 1 : 0; + } else if (with_close && probe.code() == AsyncErrorCode::stopped) { + ++stopped; + mismatches += fired ? 1 : 0; + } else { + ++mismatches; + } + if (q->active_timers() != 0 || exec.drain() != 0) { + ++leftovers; + } + } + + Void::Testing::expect_eq(setup_failures, 0); + Void::Testing::expect_eq(inline_resumes, 0); + Void::Testing::expect_eq(bad_resume_counts, 0); + Void::Testing::expect_eq(mismatches, 0); + Void::Testing::expect_eq(leftovers, 0); + Void::Testing::expect_eq(ok + cancelled + stopped, kIterations); +} + +Void::Testing::Test timer_capacity_overloaded_and_tombstone_bounded() +{ + ManualExecutor exec; + ManualClock clock; + + auto invalid = TimerQueue::create(exec, clock, TimerQueueOptions{.max_timers = 0}); + Void::Testing::require(!invalid.has_value()); + Void::Testing::expect(static_cast(invalid.error().code().value) == + AsyncErrorCode::invalid_argument); + + constexpr std::size_t kMax = 4; + auto q = make_queue(exec, clock, kMax); + + int fired = 0; + auto counting = [&fired](TimerEvent event) noexcept { + if (event == TimerEvent::expired) { + ++fired; + } + }; + std::vector handles; + for (std::size_t i = 0; i < kMax; ++i) { + auto h = q->schedule_at(at(1s + std::chrono::milliseconds{static_cast(i)}), + counting); + Void::Testing::require(h.has_value()); + handles.push_back(std::move(*h)); + } + Void::Testing::expect_eq(q->active_timers(), kMax); + + auto over = q->schedule_at(at(1s), counting); + Void::Testing::require(!over.has_value()); + Void::Testing::expect(over.error() == AdmissionError::overloaded); + + // Sleepers share the same budget and fail without suspending. + SleepProbe full; + auto full_task = await_sleep(q->sleep_until(at(2s)), &full); + start(full_task); + Void::Testing::expect(full_task.done()); + Void::Testing::expect(full.code() == AsyncErrorCode::overloaded); + Void::Testing::expect(exec.empty()); + + auto empty = q->schedule_at(at(1s), TimerCallback{}); + Void::Testing::require(!empty.has_value()); + Void::Testing::expect(empty.error() == AdmissionError::invalid_argument); + + // Cancelling frees the slot immediately and releases the callback eagerly, + // so a tombstone retains no user state. + Void::Testing::expect(handles[0].cancel()); + Void::Testing::expect(!handles[0].cancel()); + Void::Testing::expect_eq(q->active_timers(), kMax - 1); + auto token = std::make_shared(7); + auto guarded = q->schedule_at(at(3s), [token](TimerEvent) noexcept { (void)*token; }); + Void::Testing::require(guarded.has_value()); + Void::Testing::expect_eq(token.use_count(), long{2}); + Void::Testing::expect(guarded->cancel()); + Void::Testing::expect_eq(token.use_count(), long{1}); + Void::Testing::expect_eq(q->active_timers(), kMax - 1); + + // Churn far beyond 2 * max_timers cancellations: tombstones never consume + // admission capacity and are compacted (heap <= 2 * max_timers; the heap + // size itself is internal and not observable through the public API). + constexpr int kChurn = 100 * static_cast(kMax); + int churn_fired = 0; + int failures = 0; + for (int i = 0; i < kChurn; ++i) { + auto h = q->schedule_at(at(1h + std::chrono::nanoseconds{i}), + [&churn_fired](TimerEvent) noexcept { ++churn_fired; }); + if (!h.has_value()) { + ++failures; + continue; + } + if (q->active_timers() != kMax) { + ++failures; + } + auto rejected = q->schedule_at(at(1h), counting); + if (rejected.has_value() || rejected.error() != AdmissionError::overloaded) { + ++failures; + } + if (!h->cancel()) { + ++failures; + } + } + Void::Testing::expect_eq(failures, 0); + Void::Testing::expect_eq(q->active_timers(), kMax - 1); + + // The earliest live deadline is unaffected by the tombstones. + Void::Testing::require(q->next_deadline().has_value()); + Void::Testing::expect_eq(since_epoch(*q->next_deadline()), std::chrono::nanoseconds{1001ms}); + + // Advancing past everything fires only the live timers, once each. + advance_clock(clock, 2h); + Void::Testing::expect_eq(q->poll_expired(), kMax - 1); + Void::Testing::expect_eq(fired, static_cast(kMax - 1)); + Void::Testing::expect_eq(churn_fired, 0); + Void::Testing::expect_eq(q->active_timers(), std::size_t{0}); + Void::Testing::expect(!q->next_deadline().has_value()); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); +} + +Void::Testing::Test timer_schedule_at_cancel_vs_fire_exclusive() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + + // Cancel before fire: true once, the callback never runs. + int fired_a = 0; + auto a = q->schedule_at(at(5ms), [&fired_a](TimerEvent) noexcept { ++fired_a; }); + Void::Testing::require(a.has_value()); + Void::Testing::expect(a->cancel()); + Void::Testing::expect(!a->cancel()); + Void::Testing::expect_eq(q->active_timers(), std::size_t{0}); + advance_clock(clock, 5ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect_eq(fired_a, 0); + + // Fire before cancel: cancel reports false, the callback ran once. + int fired_b = 0; + auto b = q->schedule_at(at(5ms), [&fired_b](TimerEvent) noexcept { ++fired_b; }); + Void::Testing::require(b.has_value()); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect(!b->cancel()); + Void::Testing::expect_eq(fired_b, 1); + + // Empty and moved-from handles are inert. + TimerHandle empty_handle; + Void::Testing::expect(!empty_handle.valid()); + Void::Testing::expect(!empty_handle.cancel()); + TimerHandle moved = std::move(*b); + Void::Testing::expect(moved.valid()); + Void::Testing::expect(!b->valid()); + Void::Testing::expect(!b->cancel()); + + // Threaded race: exactly one of {cancel() == true, callback ran}. + constexpr int kIterations = 400; + int violations = 0; + int cancel_wins = 0; + int fire_wins = 0; + int setup_failures = 0; + for (int i = 0; i < kIterations; ++i) { + ManualClock race_clock; + auto rq = try_make_queue(exec, race_clock); + if (!rq) { + ++setup_failures; + continue; + } + std::atomic fired{0}; + auto h = rq->schedule_at(at(1ms), [&fired](TimerEvent event) noexcept { + if (event == TimerEvent::expired) { + fired.fetch_add(1, std::memory_order_relaxed); + } + }); + if (!h.has_value() || !race_clock.advance(1ms).has_value()) { + ++setup_failures; + continue; + } + + std::atomic ready{0}; + std::atomic go{false}; + std::atomic cancel_result{false}; + std::atomic polled{0}; + std::thread canceller{[&] { + ready.fetch_add(1, std::memory_order_acq_rel); + spin_until(go); + cancel_result.store(h->cancel(), std::memory_order_release); + }}; + std::thread poller{[&] { + ready.fetch_add(1, std::memory_order_acq_rel); + spin_until(go); + for (int k = 0; k < i % 4; ++k) { + std::this_thread::yield(); + } + polled.store(rq->poll_expired(), std::memory_order_release); + }}; + while (ready.load(std::memory_order_acquire) < 2) { + std::this_thread::yield(); + } + go.store(true, std::memory_order_release); + canceller.join(); + poller.join(); + + const bool won_cancel = cancel_result.load(std::memory_order_acquire); + const int runs = fired.load(std::memory_order_relaxed); + if (won_cancel == (runs == 1) || runs > 1) { + ++violations; + } + if (polled.load(std::memory_order_acquire) != static_cast(runs)) { + ++violations; + } + if (rq->active_timers() != 0) { + ++violations; + } + cancel_wins += won_cancel ? 1 : 0; + fire_wins += runs; + } + Void::Testing::expect_eq(setup_failures, 0); + Void::Testing::expect_eq(violations, 0); + Void::Testing::expect_eq(cancel_wins + fire_wins, kIterations); +} + +Void::Testing::Test timer_cancel_false_while_callback_running_shared_state() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + + // The callback owns its target through shared ownership, as required when + // the owner may drop its state after a failed cancel(). + struct Target { + std::atomic touched{0}; + }; + auto target = std::make_shared(); + std::weak_ptr observer = target; + std::atomic entered{false}; + std::atomic let_go{false}; + std::atomic finished{false}; + auto handle = q->schedule_at( + at(1ms), [target, &entered, &let_go, &finished](TimerEvent event) noexcept { + entered.store(true, std::memory_order_release); + spin_until(let_go); + target->touched.fetch_add(event == TimerEvent::expired ? 1 : 100, + std::memory_order_relaxed); + finished.store(true, std::memory_order_release); + }); + Void::Testing::require(handle.has_value()); + target.reset(); // only the callback keeps the target alive now + advance_clock(clock, 1ms); + + std::atomic polled{0}; + std::thread poller{[&] { polled.store(q->poll_expired(), std::memory_order_release); }}; + spin_until(entered); + + // The callback is mid-run: cancel() fails, yet the callback has NOT finished. + const bool cancelled = handle->cancel(); + const bool finished_at_cancel = finished.load(std::memory_order_acquire); + const bool alive_at_cancel = !observer.expired(); + let_go.store(true, std::memory_order_release); + poller.join(); + + Void::Testing::expect(!cancelled); + Void::Testing::expect(!finished_at_cancel); + Void::Testing::expect(alive_at_cancel); + Void::Testing::expect(finished.load(std::memory_order_acquire)); + Void::Testing::expect_eq(polled.load(std::memory_order_acquire), std::size_t{1}); + // The callback ran once and its captured state was released afterwards. + Void::Testing::expect(observer.expired()); +} + +Void::Testing::Test timer_close_settles_pending_stopped() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + + SleepProbe a; + SleepProbe b; + auto ta = await_sleep(q->sleep_until(at(5ms)), &a); + auto tb = await_sleep(q->sleep_for(1h), &b); + start(ta); + start(tb); + + std::vector> events; + auto record = [&events](int id) { + return [&events, id](TimerEvent event) noexcept { events.emplace_back(id, event); }; + }; + auto c1 = q->schedule_at(at(3ms), record(1)); + auto c2 = q->schedule_at(at(3ms), record(2)); + auto c3 = q->schedule_at(at(1ms), record(3)); + auto c4 = q->schedule_at(at(2ms), record(4)); + Void::Testing::require(c1.has_value() && c2.has_value() && c3.has_value() && c4.has_value()); + Void::Testing::expect(c4->cancel()); + Void::Testing::expect_eq(q->active_timers(), std::size_t{5}); + + q->close(); + // Pending callbacks get `closed` exactly once, in (deadline, seq) order. + Void::Testing::expect(events == std::vector>{ + {3, TimerEvent::closed}, + {1, TimerEvent::closed}, + {2, TimerEvent::closed}}); + Void::Testing::expect_eq(q->active_timers(), std::size_t{0}); + // Sleepers settle `stopped` but are resumed only through the executor. + Void::Testing::expect_eq(a.resumes, 0); + Void::Testing::expect_eq(b.resumes, 0); + Void::Testing::expect_eq(exec.drain(), std::size_t{2}); + Void::Testing::expect(a.code() == AsyncErrorCode::stopped); + Void::Testing::expect(b.code() == AsyncErrorCode::stopped); + + // Idempotent, and later admissions are rejected with `stopped`. + q->close(); + Void::Testing::expect_eq(events.size(), std::size_t{3}); + auto rejected = q->schedule_at(at(1ms), record(5)); + Void::Testing::require(!rejected.has_value()); + Void::Testing::expect(rejected.error() == AdmissionError::stopped); + SleepProbe after; + auto after_task = await_sleep(q->sleep_for(1ms), &after); + start(after_task); + Void::Testing::expect(after_task.done()); + Void::Testing::expect(after.code() == AsyncErrorCode::stopped); + Void::Testing::expect(exec.empty()); + + advance_clock(clock, 2h); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect(!q->next_deadline().has_value()); + Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{1s}); + Void::Testing::expect(!c1->cancel()); + Void::Testing::expect_eq(events.size(), std::size_t{3}); + Void::Testing::expect_eq(exec.drain(), std::size_t{0}); +} + +Void::Testing::Test timer_wait_duration_uses_injected_now() +{ + // Precondition: with the host clock, every manual-domain deadline below + // would already be due (wait 0). + Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms); + + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + + Void::Testing::expect_eq(q->wait_duration(5s), std::chrono::nanoseconds{5s}); + Void::Testing::expect_eq(q->wait_duration(-1s), std::chrono::nanoseconds{0}); + + auto h1 = q->schedule_at(at(2ms), [](TimerEvent) noexcept {}); + auto h2 = q->schedule_at(at(7ms), [](TimerEvent) noexcept {}); + Void::Testing::require(h1.has_value() && h2.has_value()); + + Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{2ms}); + Void::Testing::expect_eq(q->wait_duration(1ms), std::chrono::nanoseconds{1ms}); + Void::Testing::expect_eq(q->wait_duration(-5ms), std::chrono::nanoseconds{0}); + + advance_clock(clock, 1500us); + Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{500us}); + + // A cancelled head timer is skipped. + Void::Testing::expect(h1->cancel()); + Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{5500us}); + Void::Testing::require(q->next_deadline().has_value()); + Void::Testing::expect_eq(since_epoch(*q->next_deadline()), std::chrono::nanoseconds{7ms}); + + // Due (not yet polled) reports 0, also well past the deadline. + advance_clock(clock, 5500us); + Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{0}); + advance_clock(clock, 1s); + Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{0}); + + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(q->wait_duration(3s), std::chrono::nanoseconds{3s}); +} + +Void::Testing::Test timer_sleep_for_saturates() +{ + ManualExecutor exec; + ManualClock clock{at(1s)}; + auto q = make_queue(exec, clock); + + // nanoseconds::max() saturates to time_point::max() instead of wrapping + // into the past (which would fire immediately). + SleepProbe huge; + auto huge_task = await_sleep(q->sleep_for(std::chrono::nanoseconds::max()), &huge); + start(huge_task); + Void::Testing::expect(!huge_task.done()); + Void::Testing::require(q->next_deadline().has_value()); + Void::Testing::expect(*q->next_deadline() == TimePoint::max()); + Void::Testing::expect_eq(q->wait_duration(1h), std::chrono::nanoseconds{1h}); + advance_clock(clock, 1000h); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + + // Negative and nanoseconds::min() durations are already due. + SleepProbe negative; + auto negative_task = await_sleep(q->sleep_for(-5s), &negative); + start(negative_task); + SleepProbe minimum; + auto minimum_task = await_sleep(q->sleep_for(std::chrono::nanoseconds::min()), &minimum); + start(minimum_task); + Void::Testing::expect(!negative_task.done()); + Void::Testing::expect(!minimum_task.done()); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{2}); + Void::Testing::expect_eq(exec.drain(), std::size_t{2}); + Void::Testing::expect(negative.succeeded()); + Void::Testing::expect(minimum.succeeded()); + + // A deadline earlier than the saturated wake-up still wins as timeout. + SleepProbe capped; + auto capped_task = await_sleep( + q->sleep_for(std::chrono::nanoseconds::max(), + OperationOptions{.deadline = Void::Time::deadline_after(clock, 1s)}), + &capped); + start(capped_task); + advance_clock(clock, 1s); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(capped.code() == AsyncErrorCode::timeout); + + // Reaching the end of the range fires the saturated sleeper exactly once. + Void::Testing::require(clock.set(TimePoint::max()).has_value()); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(huge.succeeded()); + + // At time_point::max() any positive duration saturates and is due. + SleepProbe at_max; + auto at_max_task = await_sleep(q->sleep_for(1ns), &at_max); + start(at_max_task); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(at_max.succeeded()); + + // Low-end saturation: from just above time_point::min(). + ManualClock low_clock{TimePoint::min() + 1ns}; + auto low = make_queue(exec, low_clock); + SleepProbe lowest; + auto lowest_task = await_sleep(low->sleep_for(-1h), &lowest); + start(lowest_task); + Void::Testing::require(low->next_deadline().has_value()); + Void::Testing::expect(*low->next_deadline() == TimePoint::min()); + Void::Testing::expect_eq(low->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(lowest.succeeded()); +} + +Void::Testing::Test timer_handle_cancel_after_queue_destroyed_safe() +{ + ManualExecutor exec; + ManualClock clock; + + TimerHandle pending; + TimerHandle cancelled_early; + std::vector events; + int cancelled_runs = 0; + SleepProbe sleeper; + SleepProbe unstarted; + std::optional> sleeper_task; + std::optional> unstarted_task; + { + auto q = make_queue(exec, clock); + auto p = q->schedule_at(at(1s), [&events](TimerEvent event) noexcept { + events.push_back(event); + }); + Void::Testing::require(p.has_value()); + pending = std::move(*p); + auto c = q->schedule_at(at(2s), [&cancelled_runs](TimerEvent) noexcept { + ++cancelled_runs; + }); + Void::Testing::require(c.has_value()); + cancelled_early = std::move(*c); + Void::Testing::expect(cancelled_early.cancel()); + + sleeper_task.emplace(await_sleep(q->sleep_until(at(3s)), &sleeper)); + start(*sleeper_task); + Void::Testing::expect(!sleeper_task->done()); + // Created while the queue is alive, started only after it is gone. + unstarted_task.emplace(await_sleep(q->sleep_for(1s), &unstarted)); + } // ~TimerQueue == close() + + Void::Testing::expect(events == std::vector{TimerEvent::closed}); + Void::Testing::expect_eq(cancelled_runs, 0); + + // Handles stay usable after the queue is destroyed. + Void::Testing::expect(pending.valid()); + Void::Testing::expect(!pending.cancel()); + Void::Testing::expect(!pending.cancel()); + Void::Testing::expect(!cancelled_early.cancel()); + TimerHandle moved = std::move(pending); + Void::Testing::expect(!pending.valid()); + Void::Testing::expect(moved.valid()); + Void::Testing::expect(!moved.cancel()); + Void::Testing::expect_eq(events.size(), std::size_t{1}); + + // The pending sleeper was settled `stopped` and resumes via the executor. + Void::Testing::expect_eq(sleeper.resumes, 0); + Void::Testing::expect_eq(exec.drain(), std::size_t{1}); + Void::Testing::expect(sleeper.code() == AsyncErrorCode::stopped); + + // A sleep task started after its queue was destroyed reports `stopped`. + start(*unstarted_task); + Void::Testing::expect(unstarted_task->done()); + Void::Testing::expect(unstarted.code() == AsyncErrorCode::stopped); + Void::Testing::expect(exec.empty()); + + // Destroying a suspended sleep task cancels its timer: a later poll does + // not resume the destroyed frame. + auto q2 = make_queue(exec, clock); + SleepProbe abandoned; + { + auto abandoned_task = await_sleep(q2->sleep_until(at(1ms)), &abandoned); + start(abandoned_task); + Void::Testing::expect_eq(q2->active_timers(), std::size_t{1}); + } + Void::Testing::expect_eq(q2->active_timers(), std::size_t{0}); + advance_clock(clock, 1s); + Void::Testing::expect_eq(q2->poll_expired(), std::size_t{0}); + Void::Testing::expect(exec.empty()); + Void::Testing::expect_eq(abandoned.resumes, 0); +} + +Void::Testing::Test timer_callback_schedules_new_timer_no_deadlock() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + TimerQueue* qp = q.get(); + + // Re-entrant use from inside a callback: the queue lock is not held. + int outer = 0; + int inner = 0; + bool inner_scheduled = false; + std::size_t seen_active = 99; + std::optional seen_next; + TimerHandle inner_handle; + auto h = q->schedule_at(at(1ms), [&](TimerEvent event) noexcept { + if (event != TimerEvent::expired) { + return; + } + ++outer; + auto again = qp->schedule_at(qp->clock().now(), [&inner](TimerEvent e) noexcept { + if (e == TimerEvent::expired) { + ++inner; + } + }); + inner_scheduled = again.has_value(); + if (again.has_value()) { + inner_handle = std::move(*again); + } + seen_active = qp->active_timers(); + seen_next = qp->next_deadline(); + (void)qp->wait_duration(1s); + }); + Void::Testing::require(h.has_value()); + advance_clock(clock, 1ms); + + // The timer scheduled during dispatch is not part of the running batch. + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(outer, 1); + Void::Testing::expect(inner_scheduled); + Void::Testing::expect_eq(inner, 0); + Void::Testing::expect_eq(seen_active, std::size_t{1}); + Void::Testing::expect(seen_next.has_value() && *seen_next == at(1ms)); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{1}); + Void::Testing::expect_eq(inner, 1); + + // Cancel during dispatch: a timer already claimed by the running batch + // cannot be cancelled and still runs once; a not-yet-due timer can be. + std::vector order; + TimerHandle second; + TimerHandle later; + bool second_cancel = true; + bool later_cancel = false; + auto first = q->schedule_at(at(2ms), [&](TimerEvent) noexcept { + order.push_back(1); + second_cancel = second.cancel(); + later_cancel = later.cancel(); + }); + auto s = q->schedule_at(at(2ms), [&order](TimerEvent) noexcept { order.push_back(2); }); + auto l = q->schedule_at(at(10ms), [&order](TimerEvent) noexcept { order.push_back(3); }); + Void::Testing::require(first.has_value() && s.has_value() && l.has_value()); + second = std::move(*s); + later = std::move(*l); + advance_clock(clock, 1ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{2}); + Void::Testing::expect(order == std::vector{1, 2}); + Void::Testing::expect(!second_cancel); + Void::Testing::expect(later_cancel); + advance_clock(clock, 10ms); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{0}); + Void::Testing::expect(order == std::vector{1, 2}); + + // close() from inside a callback: still-pending timers get `closed` + // (nested), entries already claimed by the poll still see `expired`. + std::vector> events; + auto ca = q->schedule_at(at(20ms), [&events, qp](TimerEvent event) noexcept { + events.emplace_back(1, event); + qp->close(); + }); + auto cb = q->schedule_at(at(20ms), [&events](TimerEvent event) noexcept { + events.emplace_back(2, event); + }); + auto cc = q->schedule_at(at(30ms), [&events](TimerEvent event) noexcept { + events.emplace_back(3, event); + }); + Void::Testing::require(ca.has_value() && cb.has_value() && cc.has_value()); + Void::Testing::require(clock.set(at(20ms)).has_value()); + Void::Testing::expect_eq(q->poll_expired(), std::size_t{2}); + Void::Testing::expect(events == std::vector>{ + {1, TimerEvent::expired}, + {3, TimerEvent::closed}, + {2, TimerEvent::expired}}); + Void::Testing::expect_eq(q->active_timers(), std::size_t{0}); + auto after_close = q->schedule_at(at(40ms), [](TimerEvent) noexcept {}); + Void::Testing::expect(!after_close.has_value()); + Void::Testing::expect(exec.empty()); +} diff --git a/tests/standalone/Time/ClockSaturation.cpp b/tests/standalone/Time/ClockSaturation.cpp new file mode 100644 index 0000000..6587064 --- /dev/null +++ b/tests/standalone/Time/ClockSaturation.cpp @@ -0,0 +1,112 @@ +#include +#include +#include + +#include +#include +#include +#include + +using namespace std::chrono_literals; + +namespace +{ + +using TimePoint = Void::Time::MonotonicClock::time_point; + +constexpr std::int64_t kMax = std::numeric_limits::max(); +constexpr std::int64_t kMin = std::numeric_limits::min(); + +std::int64_t ns_of(TimePoint tp) +{ + return std::chrono::duration_cast( + tp.time_since_epoch()) + .count(); +} + +TimePoint at_ns(std::int64_t ns) +{ + return TimePoint{std::chrono::duration_cast( + std::chrono::nanoseconds{ns})}; +} + +} // namespace + +Void::Testing::Test clock_saturating_add_and_deadline_after_bounds() +{ + using Void::Time::deadline_after; + using Void::Time::saturating_add; + + static_assert(noexcept(saturating_add(std::declval(), + std::declval()))); + static_assert(noexcept( + deadline_after(std::declval(), + std::declval()))); + + // In-range arithmetic, positive and negative steps. + Void::Testing::expect_eq(ns_of(saturating_add(at_ns(0), 5ns)), std::int64_t{5}); + Void::Testing::expect_eq(ns_of(saturating_add(at_ns(10), -3ns)), std::int64_t{7}); + Void::Testing::expect_eq(ns_of(saturating_add(at_ns(-10), 0ns)), std::int64_t{-10}); + Void::Testing::expect_eq(ns_of(saturating_add(at_ns(-1), std::chrono::nanoseconds::max())), + kMax - 1); + Void::Testing::expect_eq(ns_of(saturating_add(at_ns(0), std::chrono::nanoseconds::max())), + kMax); + Void::Testing::expect_eq(ns_of(saturating_add(at_ns(0), std::chrono::nanoseconds::min())), + kMin); + Void::Testing::expect_eq(ns_of(saturating_add(at_ns(1), std::chrono::nanoseconds::min())), + kMin + 1); + + // Positive overflow clamps to time_point::max(). + Void::Testing::expect(saturating_add(at_ns(kMax - 1), 2ns) == TimePoint::max()); + Void::Testing::expect(saturating_add(TimePoint::max(), 1ns) == TimePoint::max()); + Void::Testing::expect(saturating_add(at_ns(1), std::chrono::nanoseconds::max()) == + TimePoint::max()); + Void::Testing::expect(saturating_add(TimePoint::max(), std::chrono::nanoseconds::max()) == + TimePoint::max()); + Void::Testing::expect(saturating_add(TimePoint::max(), 0ns) == TimePoint::max()); + + // Negative overflow clamps to time_point::min(). + Void::Testing::expect(saturating_add(at_ns(kMin + 1), -2ns) == TimePoint::min()); + Void::Testing::expect(saturating_add(TimePoint::min(), -1ns) == TimePoint::min()); + Void::Testing::expect(saturating_add(at_ns(-1), std::chrono::nanoseconds::min()) == + TimePoint::min()); + Void::Testing::expect(saturating_add(TimePoint::min(), std::chrono::nanoseconds::min()) == + TimePoint::min()); + + // Extremes in the other direction stay exact. + Void::Testing::expect_eq(ns_of(saturating_add(TimePoint::max(), std::chrono::nanoseconds::min())), + std::int64_t{-1}); + Void::Testing::expect_eq(ns_of(saturating_add(TimePoint::min(), std::chrono::nanoseconds::max())), + std::int64_t{-1}); + + // deadline_after uses the injected clock's own domain, never the host clock. + Void::Time::ManualClock epoch_clock; + Void::Testing::expect_eq(ns_of(deadline_after(epoch_clock, 1s)), + std::int64_t{1'000'000'000}); + Void::Testing::expect_eq(ns_of(deadline_after(epoch_clock, -5ns)), std::int64_t{-5}); + Void::Testing::expect(deadline_after(epoch_clock, std::chrono::nanoseconds::max()) == + TimePoint::max()); + Void::Testing::expect(deadline_after(epoch_clock, std::chrono::nanoseconds::min()) == + TimePoint::min()); + + Void::Time::ManualClock offset_clock{at_ns(100)}; + Void::Testing::expect_eq(ns_of(deadline_after(offset_clock, 50ns)), std::int64_t{150}); + Void::Testing::require(offset_clock.advance(25ns).has_value()); + Void::Testing::expect_eq(ns_of(deadline_after(offset_clock, 50ns)), std::int64_t{175}); + + Void::Time::ManualClock far_clock{at_ns(kMax - 10)}; + Void::Testing::expect_eq(ns_of(deadline_after(far_clock, 10ns)), kMax); + Void::Testing::expect(deadline_after(far_clock, 1s) == TimePoint::max()); + Void::Testing::expect(deadline_after(far_clock, std::chrono::nanoseconds::max()) == + TimePoint::max()); + Void::Testing::expect_eq(ns_of(deadline_after(far_clock, -10ns)), kMax - 20); + + // A saturated deadline is consistent with remaining_until (no wrap to 0). + Void::Testing::expect_eq( + Void::Time::remaining_until(epoch_clock, + deadline_after(epoch_clock, std::chrono::nanoseconds::max())), + std::chrono::nanoseconds::max()); + Void::Testing::expect_eq( + Void::Time::remaining_until(far_clock, deadline_after(far_clock, 1h)), + std::chrono::nanoseconds{10}); +}