Files
Library/tests/standalone/Async/DeadlineDomains.cpp
T
faumarayandClaude Opus 5.5 5c24f8e84f feat(async): add retry_async over TimerQueue and deadline-domain conformance (M-TIME-03 B1b)
- NEW Async/Retry.hpp: retry_async drives RetryState with the TimerQueue's
  injected clock, awaits backoff via sleep_until, resumes only after a clean
  sleep (any sleep error ends the retry), preserves success after stop,
  supports Task-returning and move-only callables
- Tests: AsyncRetry (15), DeadlineDomains blocking-retry manual-clock case

Review: W11-REVIEW-B1b READY (deviation accepted; doc fix applied by root)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 00:35:20 +03:00

391 lines
16 KiB
C++

#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Async/Timer.hpp>
#include <Void/Functional/Retry.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <random>
#include <stop_token>
#include <utility>
#include <vector>
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<TimePoint::duration>(offset)};
}
void advance_clock(ManualClock& clock, std::chrono::nanoseconds delta)
{
Void::Testing::require(clock.advance(delta).has_value());
}
std::optional<AsyncErrorCode> code_of(const Void::Result::Result<void>& res)
{
if (res.has_value()) {
return std::nullopt;
}
return static_cast<AsyncErrorCode>(res.error().code().value);
}
Void::Coro::Task<void> schedule_into(Executor* exec,
OperationOptions options,
const Void::Time::MonotonicClock* clock,
std::optional<Void::Result::Result<void>>* out)
{
*out = co_await schedule_on(*exec, std::move(options), *clock);
}
Void::Coro::Task<void> schedule_host_into(Executor* exec,
OperationOptions options,
std::optional<Void::Result::Result<void>>* out)
{
*out = co_await schedule_on(*exec, std::move(options));
}
Void::Coro::Task<void> increment_task(int* counter)
{
++(*counter);
co_return;
}
struct SleepProbe {
int resumes{0};
std::optional<Void::Result::Result<void>> result{};
};
Void::Coro::Task<void> await_sleep(Void::Coro::Task<Void::Result::Result<void>> sleep,
SleepProbe* probe)
{
auto res = co_await sleep;
probe->result = std::move(res);
++probe->resumes;
}
void start(Void::Coro::Task<void>& task)
{
task.handle().resume();
}
// retry_blocking's only notion of time: `now` reads the ManualClock and the
// sleeper advances it by the requested wait (plus an optional overshoot).
struct ManualNow {
const ManualClock* clock{nullptr};
[[nodiscard]] Void::Retry::SteadyTimePoint operator()() const noexcept { return clock->now(); }
};
struct ManualAdvanceSleep {
ManualClock* clock{nullptr};
std::vector<std::chrono::nanoseconds>* waits{nullptr};
std::chrono::nanoseconds overshoot{0};
bool operator()(std::chrono::nanoseconds wait, std::stop_token) const
{
waits->push_back(wait);
return clock->advance(wait + overshoot).has_value();
}
};
using ManualBlockingOptions = Void::Retry::
BlockingRetryOptions<ManualNow, ManualAdvanceSleep, Void::Retry::RetryEveryError, std::mt19937_64>;
// Constant backoff of `delay`, no jitter, no time budget.
Void::Retry::RetrySpec constant_retry_spec(std::chrono::nanoseconds delay, std::uint32_t attempts)
{
Void::Retry::RetrySpec spec;
spec.max_attempts = attempts;
spec.budget = Void::Retry::no_deadline;
spec.backoff.initial = delay;
spec.backoff.cap = delay;
spec.backoff.multiplier = 1.0;
spec.backoff.jitter = std::nullopt;
return spec;
}
// Fails every attempt with its 1-based index and records when it ran.
auto failing_attempt(const ManualClock* clock, std::vector<TimePoint>* times)
{
return [clock, times]() -> std::expected<int, int> {
times->push_back(clock->now());
return std::unexpected{static_cast<int>(times->size())};
};
}
} // 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<void>::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<Void::Result::Result<void>> 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<Void::Result::Result<void>> 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<Void::Result::Result<void>> 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<Void::Result::Result<void>> 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<Void::Result::Result<void>> 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<Void::Result::Result<void>> 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());
}
Void::Testing::Test deadline_domain_blocking_retry_manual_clock()
{
namespace R = Void::Retry;
using Ns = std::chrono::nanoseconds;
// The host steady clock is far past the manual-domain deadline below, so
// any host-clock comparison would stop the retry before its first attempt.
Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms);
// Admission deadline in the ManualClock domain (epoch 0): attempts at 0,
// 10 and 20ms; the wake-up at 30ms would overshoot 25ms, so it stops.
{
ManualClock clock;
const OperationOptions opts{.deadline = at(25ms)};
Void::Testing::expect(is_deadline_expired(opts));
Void::Testing::expect(!is_deadline_expired(opts, clock));
std::vector<TimePoint> attempts;
std::vector<Ns> waits;
const auto r = R::retry_blocking(constant_retry_spec(10ms, 10),
failing_attempt(&clock, &attempts),
ManualBlockingOptions{.now = ManualNow{&clock},
.sleep = ManualAdvanceSleep{&clock, &waits},
.classify = {},
.urbg = std::mt19937_64{1},
.stop = {},
.deadline = opts.deadline});
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(static_cast<int>(r.error().reason),
static_cast<int>(R::RetryStopReason::deadline_exceeded));
Void::Testing::expect_eq(r.error().attempts, std::uint32_t{3});
Void::Testing::require(r.error().last_error.has_value());
Void::Testing::expect_eq(*r.error().last_error, 3);
Void::Testing::require(attempts.size() == 3);
Void::Testing::expect(attempts[0] == at(0ns));
Void::Testing::expect(attempts[1] == at(10ms));
Void::Testing::expect(attempts[2] == at(20ms));
Void::Testing::require(waits.size() == 2);
Void::Testing::expect_eq(waits[0], Ns{10ms});
Void::Testing::expect_eq(waits[1], Ns{10ms});
// Only the injected sleeper moved time.
Void::Testing::expect(clock.now() == at(20ms));
}
// The budget is measured from the start the manual clock reports, here
// a century past epoch, far from any host uptime.
{
const TimePoint start = at(std::chrono::hours{24 * 365 * 100});
ManualClock clock{start};
auto spec = constant_retry_spec(10ms, 10);
spec.budget = Ns{25ms};
std::vector<TimePoint> attempts;
std::vector<Ns> waits;
const auto r = R::retry_blocking(spec,
failing_attempt(&clock, &attempts),
ManualBlockingOptions{.now = ManualNow{&clock},
.sleep = ManualAdvanceSleep{&clock, &waits},
.classify = {},
.urbg = std::mt19937_64{1},
.stop = {},
.deadline = std::nullopt});
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(static_cast<int>(r.error().reason),
static_cast<int>(R::RetryStopReason::deadline_exceeded));
Void::Testing::expect_eq(r.error().attempts, std::uint32_t{3});
Void::Testing::require(attempts.size() == 3);
Void::Testing::expect(attempts[0] == start);
Void::Testing::expect(attempts[2] == start + std::chrono::duration_cast<TimePoint::duration>(20ms));
Void::Testing::expect_eq(waits.size(), std::size_t{2});
}
// Advancing manual time past the deadline during one sleep expires the
// operation exactly once: resume() observes it and no attempt follows.
{
ManualClock clock;
std::vector<TimePoint> attempts;
std::vector<Ns> waits;
const auto r = R::retry_blocking(constant_retry_spec(10ms, 10),
failing_attempt(&clock, &attempts),
ManualBlockingOptions{.now = ManualNow{&clock},
.sleep = ManualAdvanceSleep{&clock, &waits, 30ms},
.classify = {},
.urbg = std::mt19937_64{1},
.stop = {},
.deadline = at(25ms)});
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(static_cast<int>(r.error().reason),
static_cast<int>(R::RetryStopReason::deadline_exceeded));
Void::Testing::expect_eq(r.error().attempts, std::uint32_t{1});
Void::Testing::expect_eq(attempts.size(), std::size_t{1});
Void::Testing::require(waits.size() == 1);
Void::Testing::expect_eq(waits[0], Ns{10ms});
Void::Testing::expect(clock.now() == at(40ms));
}
}