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