From 26edf653e3278f10b1a95342fd89fb1a1e8584bd Mon Sep 17 00:00:00 2001 From: faumaray Date: Sun, 29 Nov 2026 19:34:46 +0300 Subject: [PATCH] feat(functional): add pure RetryState and named retry_blocking adapter (M-FUNCTIONAL-03) - NEW std-only Functional/RetryState.hpp: RetrySpec/BackoffSpec validation, begin/next/resume/succeed decisions, saturating backoff, Full/Equal jitter, explicit no_deadline, random_device-seeded default engine, final stop decisions - Retry.hpp: relocate JitterMode, add SteadyNow/ThreadSleep/BlockingRetryOptions and retry_blocking with injected now/sleep; saturating wait computation - 1.x retry/retry_while/retry_or_throw unchanged (zero-attempt defect pinned) - Tests: RetryState (13), RetryBlocking (10) Review: W11-REVIEW-A1 READY (P3 fixes 1, 2, 5 applied by root) Co-Authored-By: Claude Opus 5.5 --- include/Void/Functional/Retry.hpp | 183 ++- include/Void/Functional/RetryState.hpp | 416 ++++++ tests/standalone/Functional/RetryBlocking.cpp | 1044 ++++++++++++++ tests/standalone/Functional/RetryState.cpp | 1201 +++++++++++++++++ 4 files changed, 2842 insertions(+), 2 deletions(-) create mode 100644 include/Void/Functional/RetryState.hpp create mode 100644 tests/standalone/Functional/RetryBlocking.cpp create mode 100644 tests/standalone/Functional/RetryState.cpp diff --git a/include/Void/Functional/Retry.hpp b/include/Void/Functional/Retry.hpp index 3ed0ebe..74557a0 100644 --- a/include/Void/Functional/Retry.hpp +++ b/include/Void/Functional/Retry.hpp @@ -1,13 +1,23 @@ #pragma once +#include + #include #include #include +#include #include +#include #include +#include +#include +#include #include #include +#include #include +#include +#include namespace Void::Retry { @@ -72,8 +82,7 @@ namespace Void::Retry // any backoff to randomize its delay and avoid thundering-herd retries. // Full: uniform in [0, base] // Equal: base/2 + uniform in [0, base/2] (keeps a guaranteed floor) - - enum class JitterMode { Full, Equal }; + // JitterMode is defined in RetryState.hpp (same name, same namespace). template struct Jittered { Backoff inner{}; @@ -210,4 +219,174 @@ namespace Void::Retry return last; } + // ── retry_blocking — named blocking adapter over RetryState + // ────────────────── Drives a RetryState with an injected clock and sleeper, + // so the retry schedule is testable without real time. Unlike the 1.x + // `retry`, an invalid spec (including max_attempts == 0) is reported as an + // error and never as a success, and the result says why retrying stopped. + + // Clock for production use. + struct SteadyNow { + [[nodiscard]] SteadyTimePoint operator()() const noexcept + { + return std::chrono::steady_clock::now(); + } + }; + + // Blocks the calling thread for `wait` or until `stop` is requested. + // Returns false when the wait was cut short by a stop request. A zero or + // negative `wait` returns immediately without blocking. + struct ThreadSleep { + bool operator()(std::chrono::nanoseconds wait, + std::stop_token stop) const + { + if (stop.stop_requested()) { + return false; + } + if (wait <= std::chrono::nanoseconds::zero()) { + return true; + } + std::mutex mutex; + std::condition_variable_any cv; + std::unique_lock lock{mutex}; + const SteadyTimePoint until = + saturating_add(std::chrono::steady_clock::now(), wait); + // The predicate is "stop requested": the call returns when it + // becomes true or when `until` passes. + (void)cv.wait_until(lock, stop, until, [&stop] { + return stop.stop_requested(); + }); + return !stop.stop_requested(); + } + }; + + // NowFn: SteadyTimePoint() + // SleepFn: bool(std::chrono::nanoseconds wait, std::stop_token) + // false means the wait was interrupted by a stop request + // Classify: AttemptOutcome(const E&) for the error type E of the callable + // URBG: random engine used for jitter (seeded from random_device by + // default) + // deadline: optional absolute admission deadline; the effective deadline + // is the earlier of it and the spec's budget. + template + struct BlockingRetryOptions { + NowFn now{}; + SleepFn sleep{}; + Classify classify{}; + URBG urbg = detail::seeded_engine(); + std::stop_token stop{}; + std::optional deadline{}; + }; + + namespace detail + { + template struct expected_traits; + + template struct expected_traits> { + using value_type = T; + using error_type = E; + }; + + template + using blocking_result_t = std::expected< + typename expected_traits< + std::remove_cvref_t>>::value_type, + RetryError>>::error_type>>; + } // namespace detail + + // Runs `fn` (callable returning std::expected) until it succeeds or + // RetryState says to stop. + // success -> the value of the successful attempt + // invalid spec -> RetryError{config = error, attempts = 0}, + // `fn` is never called + // anything else that stops -> RetryError{reason, attempts, last_error} + // Waits are `decision.at - now()` (never negative) handed to `sleep` + // together with `options.stop`; when `sleep` returns false the call ends + // with stop_requested and no further attempt. `T` may be move-only. + template + requires std::invocable + [[nodiscard]] auto + retry_blocking(const RetrySpec& spec, F&& fn, + BlockingRetryOptions + options = {}) -> detail::blocking_result_t + { + using Result = std::remove_cvref_t>; + using T = typename detail::expected_traits::value_type; + using E = typename detail::expected_traits::error_type; + using Error = RetryError; + using Out = std::expected; + static_assert( + std::is_invocable_r_v, + "Classify must be callable as AttemptOutcome(const E&)"); + + if (const auto valid = validate(spec); !valid) { + return Out(std::unexpect, + Error{RetryStopReason::none, 0, std::nullopt, + valid.error()}); + } + + const SteadyTimePoint start = options.now(); + auto created = RetryState::create( + spec, start, std::move(options.urbg), options.deadline); + if (!created.has_value()) { // unreachable after validate() + return Out(std::unexpect, + Error{RetryStopReason::none, 0, std::nullopt, + created.error()}); + } + RetryState& state = *created; + + std::optional last_error; + RetryDecision decision = + state.begin(start, options.stop.stop_requested()); + for (;;) { + if (decision.action == RetryAction::attempt) { + auto result = fn(); + if (result.has_value()) { + (void)state.succeed(); + if constexpr (std::is_void_v) { + return Out{}; + } else { + return Out(std::in_place, std::move(*result)); + } + } + last_error.emplace(std::move(result).error()); + const AttemptOutcome outcome = + options.classify(std::as_const(*last_error)); + decision = state.next(options.now(), outcome, + options.stop.stop_requested()); + } else if (decision.action == RetryAction::wait_until) { + const SteadyTimePoint now = options.now(); + std::chrono::nanoseconds wait = std::chrono::nanoseconds::zero(); + if (decision.at > now) { + // Saturating `at - now`: an injected clock may step backwards + // to a negative epoch while `at` is near max(). + using Rep = SteadyTimePoint::duration::rep; + const Rep at_ticks = decision.at.time_since_epoch().count(); + const Rep now_ticks = now.time_since_epoch().count(); + const bool overflows = now_ticks < 0 && + at_ticks > std::numeric_limits::max() + now_ticks; + wait = overflows + ? std::chrono::nanoseconds::max() + : std::chrono::duration_cast( + SteadyTimePoint::duration{at_ticks - now_ticks}); + } + if (!options.sleep(wait, options.stop)) { + return Out(std::unexpect, + Error{RetryStopReason::stop_requested, + state.attempts_started(), + std::move(last_error), std::nullopt}); + } + decision = state.resume(options.now(), + options.stop.stop_requested()); + } else { + return Out(std::unexpect, + Error{decision.reason, decision.attempts_started, + std::move(last_error), std::nullopt}); + } + } + } + } // namespace Void::Retry diff --git a/include/Void/Functional/RetryState.hpp b/include/Void/Functional/RetryState.hpp new file mode 100644 index 0000000..c5cbe86 --- /dev/null +++ b/include/Void/Functional/RetryState.hpp @@ -0,0 +1,416 @@ +#pragma once + +// Pure retry decision engine. +// +// Standard-library only: it pulls in no threading header and no other Void +// header. Nothing in this header reads a clock, sleeps or calls user code: +// callers pass the current time in and carry out the returned decision +// themselves. The blocking adapter +// lives in Retry.hpp (`retry_blocking`); asynchronous adapters live in the +// modules that own a timer. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Retry +{ + + using SteadyTimePoint = std::chrono::steady_clock::time_point; + + // ── Jitter + // ──────────────────────────────────────────────────────────────────── + // Full: uniform in [0, d] + // Equal: d/2 + uniform in [0, d - d/2] (keeps a guaranteed floor) + // (Relocated from Retry.hpp; name and namespace are unchanged.) + + enum class JitterMode { Full, Equal }; + + // ── Specification + // ───────────────────────────────────────────────────────────── + + // Explicit "no total time budget" marker for RetrySpec::budget. + struct NoDeadline { + constexpr bool operator==(const NoDeadline&) const noexcept + = default; + }; + + inline constexpr NoDeadline no_deadline{}; + + struct BackoffSpec { + // Delay before the first retry. + std::chrono::nanoseconds initial{std::chrono::milliseconds{100}}; + // Upper bound on any single (unjittered) delay. + std::chrono::nanoseconds cap{std::chrono::seconds{30}}; + // Growth factor between consecutive retries; finite and >= 1. + double multiplier{2.0}; + // Randomisation applied to every non-zero delay. + std::optional jitter{}; + }; + + struct RetrySpec { + // Total attempts including the first one; must be >= 1. + std::uint32_t max_attempts{3}; + // Total time budget measured from the start of the operation, or + // `no_deadline`. A zero or negative duration is invalid. + std::variant budget{ + std::chrono::seconds{30}}; + BackoffSpec backoff{}; + }; + + enum class RetryConfigError : std::uint8_t { + zero_attempts, + negative_duration, + zero_budget, + nonfinite_multiplier, + multiplier_below_one, + cap_below_initial, + }; + + // ── Decisions + // ───────────────────────────────────────────────────────────────── + + enum class RetryAction : std::uint8_t { attempt, wait_until, stop }; + + enum class RetryStopReason : std::uint8_t { + none, + succeeded, + attempts_exhausted, + deadline_exceeded, + not_retryable, + stop_requested, + }; + + enum class AttemptOutcome : std::uint8_t { + retryable_failure, + permanent_failure, + }; + + struct RetryDecision { + RetryAction action{RetryAction::stop}; + // Absolute time to wait until; meaningful for `wait_until` only. + SteadyTimePoint at{}; + RetryStopReason reason{RetryStopReason::none}; + // Attempts that have been started so far. + std::uint32_t attempts_started{0}; + }; + + // Validation order (first failing check wins): zero_attempts, + // negative_duration (initial, cap or budget < 0), zero_budget, + // nonfinite_multiplier, multiplier_below_one, cap_below_initial. + [[nodiscard]] inline std::expected + validate(const RetrySpec& spec) noexcept + { + using std::chrono::nanoseconds; + if (spec.max_attempts == 0) { + return std::unexpected{RetryConfigError::zero_attempts}; + } + const nanoseconds* const budget = + std::get_if(&spec.budget); + if (spec.backoff.initial < nanoseconds::zero() || + spec.backoff.cap < nanoseconds::zero() || + (budget != nullptr && *budget < nanoseconds::zero())) { + return std::unexpected{RetryConfigError::negative_duration}; + } + if (budget != nullptr && *budget == nanoseconds::zero()) { + return std::unexpected{RetryConfigError::zero_budget}; + } + if (!std::isfinite(spec.backoff.multiplier)) { + return std::unexpected{RetryConfigError::nonfinite_multiplier}; + } + if (spec.backoff.multiplier < 1.0) { + return std::unexpected{RetryConfigError::multiplier_below_one}; + } + if (spec.backoff.cap < spec.backoff.initial) { + return std::unexpected{RetryConfigError::cap_below_initial}; + } + return {}; + } + + // `initial * multiplier^retry_index`, saturated at `cap`, without jitter. + // The product is computed and compared in floating point and only converted + // to an integer once it is known to lie strictly below `cap`, so it never + // overflows. The function is total: for a spec that fails validate() the + // result is unspecified but always lies in [0, max(cap, 0)]. + [[nodiscard]] inline std::chrono::nanoseconds + backoff_delay(const BackoffSpec& spec, + std::uint32_t retry_index) noexcept + { + using std::chrono::nanoseconds; + if (spec.initial <= nanoseconds::zero() || + spec.cap <= nanoseconds::zero()) { + return nanoseconds::zero(); + } + const nanoseconds first = std::min(spec.initial, spec.cap); + if (retry_index == 0 || spec.multiplier == 1.0) { + return first; + } + const double cap = static_cast(spec.cap.count()); + const double raw = + static_cast(spec.initial.count()) * + std::pow(spec.multiplier, static_cast(retry_index)); + // `!(raw < cap)` also catches NaN and +infinity. + if (!(raw < cap)) { + return spec.cap; + } + if (raw <= 0.0) { + return nanoseconds::zero(); + } + // 0 < raw < cap <= 2^63, so the conversion is in range; the final + // min() only guards against rounding of `cap` to double. + return std::min(nanoseconds{static_cast(raw)}, + spec.cap); + } + + // `tp + delta`, clamped to [time_point::min(), time_point::max()]. + [[nodiscard]] constexpr SteadyTimePoint + saturating_add(SteadyTimePoint tp, + std::chrono::nanoseconds delta) noexcept + { + using Rep = SteadyTimePoint::rep; + static_assert(std::is_integral_v && std::is_signed_v, + "steady_clock must have a signed integral rep"); + const Rep base = tp.time_since_epoch().count(); + const Rep step = + std::chrono::duration_cast(delta) + .count(); + if (step >= 0) { + if (base > std::numeric_limits::max() - step) { + return SteadyTimePoint::max(); + } + } else if (base < std::numeric_limits::min() - step) { + return SteadyTimePoint::min(); + } + return SteadyTimePoint{SteadyTimePoint::duration{base + step}}; + } + + namespace detail + { + // Default random engine: seeded from std::random_device when the + // engine can be seeded from one integer, default-constructed + // otherwise. + template G seeded_engine() + { + if constexpr (std::is_constructible_v< + G, std::random_device::result_type>) { + // Parentheses, not braces: braces would make a seed type + // narrower than random_device::result_type a narrowing error. + return G(std::random_device{}()); + } else { + return G{}; + } + } + } // namespace detail + + // ── RetryState + // ──────────────────────────────────────────────────────────────── + // Drives one retried operation. Protocol: + // + // begin(now) -> attempt | stop + // ... run the attempt ... + // succeed() -> stop(succeeded) + // next(now, outcome) -> wait_until(at) | stop + // ... wait until `at` ... + // resume(now) -> attempt | stop + // + // `next` never returns `attempt`: a retry always goes through a wait + // decision (possibly of zero length) and a resume() that re-checks the + // stop request and the deadline at the time the wait actually ended. + // No decision method allocates, reads a clock or blocks. + + template + class RetryState + { + public: + + // Validates `spec`. The effective deadline is + // min(start + budget, admission_deadline); with `no_deadline` it + // is `admission_deadline` alone (possibly none). + [[nodiscard]] static std::expected + create(const RetrySpec& spec, SteadyTimePoint start, + URBG urbg = detail::seeded_engine(), + std::optional admission_deadline = + std::nullopt) + { + if (const auto valid = validate(spec); !valid) { + return std::unexpected{valid.error()}; + } + std::optional deadline = admission_deadline; + if (const auto* budget = + std::get_if(&spec.budget)) { + const SteadyTimePoint by_budget = + saturating_add(start, *budget); + deadline = admission_deadline.has_value() + ? std::min(by_budget, *admission_deadline) + : by_budget; + } + return RetryState{spec.max_attempts, spec.backoff, deadline, + std::move(urbg)}; + } + + // Decide whether the first attempt may start. Calling it again + // behaves like resume(). + [[nodiscard]] RetryDecision + begin(SteadyTimePoint now, bool stop_requested = false) noexcept + { + if (final_reason_.has_value()) { + return stop_decision(*final_reason_); + } + return start_attempt(now, stop_requested); + } + + // Record the outcome of the attempt that just finished and decide + // what follows: stop, or wait until an absolute time. + // Checked in order: permanent failure, attempts exhausted, stop + // request, jittered delay overshooting the deadline. + [[nodiscard]] RetryDecision + next(SteadyTimePoint now, AttemptOutcome outcome, + bool stop_requested = false) noexcept + { + if (final_reason_.has_value()) { + return stop_decision(*final_reason_); + } + if (outcome == AttemptOutcome::permanent_failure) { + return stop_decision(RetryStopReason::not_retryable); + } + if (attempts_started_ >= max_attempts_) { + return stop_decision(RetryStopReason::attempts_exhausted); + } + if (stop_requested) { + return stop_decision(RetryStopReason::stop_requested); + } + const std::uint32_t retry_index = + attempts_started_ == 0 ? 0 : attempts_started_ - 1; + const SteadyTimePoint at = saturating_add( + now, jittered(backoff_delay(backoff_, retry_index))); + // A wake-up exactly at the deadline is already too late. + if (deadline_.has_value() && at >= *deadline_) { + return stop_decision(RetryStopReason::deadline_exceeded); + } + return RetryDecision{RetryAction::wait_until, at, + RetryStopReason::none, attempts_started_}; + } + + // Call after a `wait_until` decision has elapsed (or was cut + // short): re-checks the stop request and the deadline, then + // starts the next attempt. + [[nodiscard]] RetryDecision + resume(SteadyTimePoint now, bool stop_requested = false) noexcept + { + if (final_reason_.has_value()) { + return stop_decision(*final_reason_); + } + return start_attempt(now, stop_requested); + } + + [[nodiscard]] RetryDecision succeed() noexcept + { + return stop_decision(RetryStopReason::succeeded); + } + + [[nodiscard]] std::uint32_t attempts_started() const noexcept + { + return attempts_started_; + } + + [[nodiscard]] std::optional + deadline() const noexcept + { + return deadline_; + } + + private: + + RetryState(std::uint32_t max_attempts, const BackoffSpec& backoff, + std::optional deadline, URBG urbg) + : max_attempts_{max_attempts}, backoff_{backoff}, + deadline_{deadline}, urbg_{std::move(urbg)} + { + } + + // Every stop decision is final: later begin/next/resume calls + // repeat it instead of starting another attempt. + [[nodiscard]] RetryDecision + stop_decision(RetryStopReason reason) noexcept + { + final_reason_ = reason; + return RetryDecision{RetryAction::stop, SteadyTimePoint{}, + reason, attempts_started_}; + } + + [[nodiscard]] RetryDecision + start_attempt(SteadyTimePoint now, bool stop_requested) noexcept + { + if (stop_requested) { + return stop_decision(RetryStopReason::stop_requested); + } + if (deadline_.has_value() && now >= *deadline_) { + return stop_decision(RetryStopReason::deadline_exceeded); + } + // Only reachable when the protocol above is violated; keeps + // the counter bounded by max_attempts_ (<= UINT32_MAX). + if (attempts_started_ >= max_attempts_) { + return stop_decision(RetryStopReason::attempts_exhausted); + } + ++attempts_started_; + return RetryDecision{RetryAction::attempt, SteadyTimePoint{}, + RetryStopReason::none, attempts_started_}; + } + + [[nodiscard]] std::chrono::nanoseconds + jittered(std::chrono::nanoseconds delay) noexcept + { + if (!backoff_.jitter.has_value() || + delay <= std::chrono::nanoseconds::zero()) { + return delay; + } + using Rep = std::chrono::nanoseconds::rep; + const Rep full = delay.count(); + const Rep floor = + *backoff_.jitter == JitterMode::Equal ? full / 2 : 0; + std::uniform_int_distribution dist{0, full - floor}; + return std::chrono::nanoseconds{floor + dist(urbg_)}; + } + + std::uint32_t max_attempts_; + BackoffSpec backoff_; + std::optional deadline_; + URBG urbg_; + std::uint32_t attempts_started_{0}; + std::optional final_reason_{}; + }; + + // ── Results and classification + // ──────────────────────────────────────────────── + + // Error half of a retried operation's result. + // attempts attempts that were started (0 when none ran) + // last_error the most recent attempt error; empty iff no attempt ran + // config set (with attempts == 0) when the spec was rejected + template struct RetryError { + RetryStopReason reason{}; + std::uint32_t attempts{0}; + std::optional last_error{}; + std::optional config{}; + }; + + // Default classifier: every error is worth retrying. + struct RetryEveryError { + template + [[nodiscard]] constexpr AttemptOutcome + operator()(const E&) const noexcept + { + return AttemptOutcome::retryable_failure; + } + }; + +} // namespace Void::Retry diff --git a/tests/standalone/Functional/RetryBlocking.cpp b/tests/standalone/Functional/RetryBlocking.cpp new file mode 100644 index 0000000..7828bc2 --- /dev/null +++ b/tests/standalone/Functional/RetryBlocking.cpp @@ -0,0 +1,1044 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// retry_blocking is exercised against a fake clock and a fake sleeper that +// both live in this file: no Time module and no real sleeping anywhere in +// this file. The last two tests cover the default (real) options only on +// paths that return immediately: an already-requested stop, a zero-length +// wait and a cross-thread stop request that is race-free whichever side +// wins. The timed ThreadSleep path is deliberately not exercised here. + +namespace +{ + using namespace std::chrono_literals; + namespace R = Void::Retry; + using Void::Testing::expect; + using Void::Testing::expect_eq; + + using R::SteadyTimePoint; + using Engine = std::mt19937_64; + using Ns = std::chrono::nanoseconds; + + constexpr SteadyTimePoint t0{std::chrono::seconds{1000}}; + + // Manually advanced clock plus a record of everything the adapter asked + // the sleeper to do. + struct FakeWorld { + SteadyTimePoint now{t0}; + std::vector waits; + bool sleeper_saw_stoppable_token{false}; + }; + + struct FakeNow { + FakeWorld* world{nullptr}; + [[nodiscard]] SteadyTimePoint operator()() const noexcept + { + return world->now; + } + }; + + // Records the wait and moves the fake clock forward by exactly that much. + struct FakeSleep { + FakeWorld* world{nullptr}; + bool operator()(Ns wait, std::stop_token stop) const + { + world->waits.push_back(wait); + world->sleeper_saw_stoppable_token = stop.stop_possible(); + world->now += wait; + return true; + } + }; + + // Models a sleeper that is cut short by a stop request: it asks the stop + // source to stop and, when `interrupted`, reports the wait as cut short + // (what ThreadSleep does). + struct StoppingSleep { + FakeWorld* world{nullptr}; + std::stop_source* source{nullptr}; + bool interrupted{true}; + bool operator()(Ns wait, std::stop_token) const + { + world->waits.push_back(wait); + if (source != nullptr) { + source->request_stop(); + } + if (interrupted) { + return false; + } + world->now += wait; + return true; + } + }; + + struct FatalClassifier { + [[nodiscard]] R::AttemptOutcome + operator()(const std::string& e) const noexcept + { + return e == "fatal" ? R::AttemptOutcome::permanent_failure + : R::AttemptOutcome::retryable_failure; + } + }; + + template + [[nodiscard]] auto make_options(FakeWorld& world, Sleep sleep, + Classify classify = {}) + { + return R::BlockingRetryOptions{ + .now = FakeNow{&world}, + .sleep = std::move(sleep), + .classify = std::move(classify), + .urbg = Engine{42}, + .stop = {}, + .deadline = std::nullopt}; + } + + [[nodiscard]] auto make_options(FakeWorld& world) + { + return make_options(world, FakeSleep{&world}); + } + + void expect_waits(const std::vector& actual, + const std::vector& expected, + std::source_location loc = std::source_location::current()) + { + expect_eq(actual.size(), expected.size(), loc); + if (actual.size() != expected.size()) { + return; + } + for (std::size_t i = 0; i < actual.size(); ++i) { + expect_eq(actual[i].count(), expected[i].count(), loc); + } + } + + // Bulk checks are folded into one assertion: the test runner keeps only + // the first 1000 assertions of a test (kMaxRetainedAssertionsPerTest) and + // decides pass/fail from those, so a failure past that point would be lost. + void expect_all_within(const std::vector& values, Ns lo, Ns hi, + std::source_location loc = std::source_location::current()) + { + std::size_t outside = 0; + for (const Ns v : values) { + if (v < lo || v > hi) { + ++outside; + } + } + expect_eq(outside, std::size_t{0}, loc); + } + + [[nodiscard]] R::RetrySpec constant_delay_spec( + Ns delay, std::optional jitter, std::uint32_t attempts) + { + R::RetrySpec spec; + spec.max_attempts = attempts; + spec.budget = R::no_deadline; + spec.backoff.initial = delay; + spec.backoff.cap = delay; + spec.backoff.multiplier = 1.0; + spec.backoff.jitter = jitter; + return spec; + } +} // namespace + +// ── schedule, attempt counts and deadlines on a fake clock ──────────────────── + +Void::Testing::Test retry_blocking_fake_clock_exact_waits_and_attempts() +{ + // Succeeds on the fourth attempt: three waits of 100ms, 200ms, 400ms. + { + R::RetrySpec spec; + spec.max_attempts = 4; + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + if (++calls < 4) { + return std::unexpected{std::string{"e"}}; + } + return 7; + }, + make_options(world)); + expect(r.has_value()); + if (r.has_value()) { + expect_eq(*r, 7); + } + expect_eq(calls, 4); + expect_waits(world.waits, {100ms, 200ms, 400ms}); + expect(world.now == t0 + 700ms); + expect(world.sleeper_saw_stoppable_token == false); + } + + // Default spec (3 attempts), every attempt fails: two waits, then + // "attempts exhausted" with the third error kept. + { + const R::RetrySpec spec{}; + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + return std::unexpected{++calls}; + }, + make_options(world)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::attempts_exhausted)); + expect_eq(r.error().attempts, std::uint32_t{3}); + expect(r.error().last_error.has_value()); + expect(!r.error().config.has_value()); + if (r.error().last_error.has_value()) { + expect_eq(*r.error().last_error, 3); + } + } + expect_eq(calls, 3); + expect_waits(world.waits, {100ms, 200ms}); + expect(world.now == t0 + 300ms); + } + + // A budget of 250ms: attempt 2 starts at 100ms, and the 200ms wait that + // would follow ends at 300ms, past the deadline. + { + R::RetrySpec spec; + spec.max_attempts = 5; + spec.budget = 250ms; + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + return std::unexpected{++calls}; + }, + make_options(world)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::deadline_exceeded)); + expect_eq(r.error().attempts, std::uint32_t{2}); + } + expect_eq(calls, 2); + expect_waits(world.waits, {100ms}); + expect(world.now == t0 + 100ms); + } + + // A wake-up landing exactly on the deadline is too late. + { + R::RetrySpec spec; + spec.max_attempts = 5; + spec.budget = 300ms; + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + return std::unexpected{++calls}; + }, + make_options(world)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::deadline_exceeded)); + } + expect_eq(calls, 2); + } + + // Attempts that take time count against the budget (1s): attempt 1 ends + // at 600ms, the 100ms wait fits, attempt 2 ends at 1300ms and nothing + // more fits. + { + R::RetrySpec spec; + spec.max_attempts = 5; + spec.budget = 1s; + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + world.now += 600ms; + return std::unexpected{++calls}; + }, + make_options(world)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::deadline_exceeded)); + expect_eq(r.error().attempts, std::uint32_t{2}); + } + expect_eq(calls, 2); + expect_waits(world.waits, {100ms}); + } + + // Jitter on a fake clock: each of the 49 waits lies in [0, 100ms], and a + // second run with the same seed produces the same schedule. + { + const auto spec = + constant_delay_spec(100ms, R::JitterMode::Full, 50); + std::vector first; + for (int run = 0; run < 2; ++run) { + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + return std::unexpected{++calls}; + }, + make_options(world)); + expect(!r.has_value()); + expect_eq(calls, 50); + expect_eq(world.waits.size(), std::size_t{49}); + expect_all_within(world.waits, 0ns, 100ms); + if (run == 0) { + first = world.waits; + } else { + expect(first == world.waits); + } + } + } +} + +// ── validation and admission ────────────────────────────────────────────────── + +Void::Testing::Test retry_blocking_zero_attempts_config_error_no_call() +{ + // The 1.x retry() treats zero attempts as a default-constructed success; + // retry_blocking reports a configuration error and never calls `fn`. + { + R::RetrySpec spec; + spec.max_attempts = 0; + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + ++calls; + return 1; + }, + make_options(world)); + expect(!r.has_value()); + if (!r.has_value()) { + expect(r.error().config.has_value()); + if (r.error().config.has_value()) { + expect_eq(static_cast(*r.error().config), + static_cast(R::RetryConfigError::zero_attempts)); + } + expect_eq(r.error().attempts, std::uint32_t{0}); + expect(!r.error().last_error.has_value()); + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::none)); + } + expect_eq(calls, 0); + expect(world.waits.empty()); + } + + // Every other configuration error is reported the same way. + { + struct Bad { + R::RetrySpec spec; + R::RetryConfigError error; + }; + std::vector bad; + { + R::RetrySpec s; + s.backoff.initial = -1ns; + bad.push_back({s, R::RetryConfigError::negative_duration}); + } + { + R::RetrySpec s; + s.budget = 0ns; + bad.push_back({s, R::RetryConfigError::zero_budget}); + } + { + R::RetrySpec s; + s.backoff.multiplier = std::numeric_limits::quiet_NaN(); + bad.push_back({s, R::RetryConfigError::nonfinite_multiplier}); + } + { + R::RetrySpec s; + s.backoff.multiplier = 0.5; + bad.push_back({s, R::RetryConfigError::multiplier_below_one}); + } + { + R::RetrySpec s; + s.backoff.initial = 2s; + s.backoff.cap = 1s; + bad.push_back({s, R::RetryConfigError::cap_below_initial}); + } + for (const Bad& b : bad) { + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + b.spec, + [&]() -> std::expected { + ++calls; + return 1; + }, + make_options(world)); + expect(!r.has_value()); + if (!r.has_value()) { + expect(r.error().config.has_value()); + if (r.error().config.has_value()) { + expect_eq(static_cast(*r.error().config), + static_cast(b.error)); + } + expect_eq(r.error().attempts, std::uint32_t{0}); + } + expect_eq(calls, 0); + expect(world.waits.empty()); + } + } +} + +Void::Testing::Test retry_blocking_expired_deadline_no_call_no_success() +{ + const R::RetrySpec spec{}; + + // An admission deadline that is already due: `fn` would succeed, but it + // is never called and no success is returned. + for (const auto deadline : {t0, t0 - 1h, t0 - 1ns}) { + FakeWorld world; + int calls = 0; + auto options = make_options(world); + options.deadline = deadline; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + ++calls; + return 1; + }, + std::move(options)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::deadline_exceeded)); + expect_eq(r.error().attempts, std::uint32_t{0}); + expect(!r.error().last_error.has_value()); + expect(!r.error().config.has_value()); + } + expect_eq(calls, 0); + expect(world.waits.empty()); + } + + // One nanosecond of room is enough to run the attempt. + { + FakeWorld world; + int calls = 0; + auto options = make_options(world); + options.deadline = t0 + 1ns; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + ++calls; + return 1; + }, + std::move(options)); + expect(r.has_value()); + expect_eq(calls, 1); + } + + // The admission deadline tightens the spec's budget (30s default). + { + FakeWorld world; + int calls = 0; + auto options = make_options(world); + options.deadline = t0 + 250ms; + R::RetrySpec many; + many.max_attempts = 10; + const auto r = R::retry_blocking( + many, + [&]() -> std::expected { + return std::unexpected{++calls}; + }, + std::move(options)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::deadline_exceeded)); + expect_eq(r.error().attempts, std::uint32_t{2}); + } + expect_waits(world.waits, {100ms}); + } +} + +Void::Testing::Test retry_blocking_last_error_and_attempt_count() +{ + // The most recent error is kept, not the first. + { + const R::RetrySpec spec{}; + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + return std::unexpected{"e" + std::to_string(++calls)}; + }, + make_options(world)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(r.error().attempts, std::uint32_t{3}); + expect(r.error().last_error.has_value()); + if (r.error().last_error.has_value()) { + expect_eq(*r.error().last_error, std::string{"e3"}); + } + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::attempts_exhausted)); + } + expect_eq(calls, 3); + } + + // A single allowed attempt: one call, one error, no waits. + { + R::RetrySpec spec; + spec.max_attempts = 1; + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + ++calls; + return std::unexpected{std::string{"only"}}; + }, + make_options(world)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(r.error().attempts, std::uint32_t{1}); + expect(r.error().last_error.has_value()); + if (r.error().last_error.has_value()) { + expect_eq(*r.error().last_error, std::string{"only"}); + } + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::attempts_exhausted)); + } + expect_eq(calls, 1); + expect(world.waits.empty()); + } + + // First attempt succeeds: the value comes back and nothing else happens. + { + const R::RetrySpec spec{}; + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + ++calls; + return std::string{"ok"}; + }, + make_options(world)); + expect(r.has_value()); + if (r.has_value()) { + expect_eq(*r, std::string{"ok"}); + } + expect_eq(calls, 1); + expect(world.waits.empty()); + } + + // No attempt ran: last_error is empty (stop requested before the start). + { + const R::RetrySpec spec{}; + FakeWorld world; + std::stop_source source; + source.request_stop(); + auto options = make_options(world); + options.stop = source.get_token(); + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + ++calls; + return 1; + }, + std::move(options)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::stop_requested)); + expect_eq(r.error().attempts, std::uint32_t{0}); + expect(!r.error().last_error.has_value()); + expect(!r.error().config.has_value()); + } + expect_eq(calls, 0); + } + + // expected is supported. + { + const R::RetrySpec spec{}; + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + if (++calls < 2) { + return std::unexpected{calls}; + } + return {}; + }, + make_options(world)); + expect(r.has_value()); + expect_eq(calls, 2); + expect_waits(world.waits, {100ms}); + } +} + +// ── stop requests ───────────────────────────────────────────────────────────── + +Void::Testing::Test retry_blocking_stop_during_sleep_no_extra_attempt() +{ + const R::RetrySpec spec{}; + + // The sleeper is interrupted (returns false): the call ends with + // stop_requested and the second attempt never starts. + { + FakeWorld world; + std::stop_source source; + auto options = + make_options(world, StoppingSleep{&world, &source, true}); + options.stop = source.get_token(); + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + return std::unexpected{"e" + std::to_string(++calls)}; + }, + std::move(options)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::stop_requested)); + expect_eq(r.error().attempts, std::uint32_t{1}); + expect(r.error().last_error.has_value()); + if (r.error().last_error.has_value()) { + expect_eq(*r.error().last_error, std::string{"e1"}); + } + } + expect_eq(calls, 1); + expect_waits(world.waits, {100ms}); + } + + // The sleeper reports a normal wake-up but a stop was requested meanwhile: + // resume() sees it and no further attempt starts. + { + FakeWorld world; + std::stop_source source; + auto options = + make_options(world, StoppingSleep{&world, &source, false}); + options.stop = source.get_token(); + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + ++calls; + return std::unexpected{std::string{"e"}}; + }, + std::move(options)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::stop_requested)); + expect_eq(r.error().attempts, std::uint32_t{1}); + } + expect_eq(calls, 1); + expect_waits(world.waits, {100ms}); + } + + // A stop requested from inside the attempt ends the sequence without + // any wait. + { + FakeWorld world; + std::stop_source source; + auto options = make_options(world); + options.stop = source.get_token(); + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + ++calls; + source.request_stop(); + return std::unexpected{std::string{"e"}}; + }, + std::move(options)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::stop_requested)); + expect_eq(r.error().attempts, std::uint32_t{1}); + expect(r.error().last_error.has_value()); + } + expect_eq(calls, 1); + expect(world.waits.empty()); + } + + // A success is a success even if a stop was requested during the attempt. + { + FakeWorld world; + std::stop_source source; + auto options = make_options(world); + options.stop = source.get_token(); + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + source.request_stop(); + return 5; + }, + std::move(options)); + expect(r.has_value()); + if (r.has_value()) { + expect_eq(*r, 5); + } + } + + // The sleeper receives the caller's stop token. + { + FakeWorld world; + std::stop_source source; + auto options = make_options(world); + options.stop = source.get_token(); + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + if (++calls < 2) { + return std::unexpected{calls}; + } + return 1; + }, + std::move(options)); + expect(r.has_value()); + expect(world.sleeper_saw_stoppable_token); + } +} + +// ── classification ──────────────────────────────────────────────────────────── + +Void::Testing::Test retry_blocking_permanent_failure_single_attempt() +{ + R::RetrySpec spec; + spec.max_attempts = 5; + + // A permanent error on the first attempt: one call, no wait. + { + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + ++calls; + return std::unexpected{std::string{"fatal"}}; + }, + make_options(world, FakeSleep{&world}, FatalClassifier{})); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::not_retryable)); + expect_eq(r.error().attempts, std::uint32_t{1}); + expect(r.error().last_error.has_value()); + if (r.error().last_error.has_value()) { + expect_eq(*r.error().last_error, std::string{"fatal"}); + } + } + expect_eq(calls, 1); + expect(world.waits.empty()); + } + + // Transient errors are retried until a permanent one shows up. + { + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected { + return std::unexpected{++calls < 3 ? std::string{"transient"} + : std::string{"fatal"}}; + }, + make_options(world, FakeSleep{&world}, FatalClassifier{})); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::not_retryable)); + expect_eq(r.error().attempts, std::uint32_t{3}); + } + expect_eq(calls, 3); + expect_waits(world.waits, {100ms, 200ms}); + } + + // On the last allowed attempt, a permanent error is "not retryable", the + // same error under the default classifier is "attempts exhausted". + { + R::RetrySpec two; + two.max_attempts = 2; + auto fn = [](int& calls) { + return [&calls]() -> std::expected { + return std::unexpected{++calls < 2 ? std::string{"transient"} + : std::string{"fatal"}}; + }; + }; + { + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + two, fn(calls), + make_options(world, FakeSleep{&world}, FatalClassifier{})); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq( + static_cast(r.error().reason), + static_cast(R::RetryStopReason::not_retryable)); + } + } + { + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking(two, fn(calls), + make_options(world)); + expect(!r.has_value()); + if (!r.has_value()) { + expect_eq(static_cast(r.error().reason), + static_cast( + R::RetryStopReason::attempts_exhausted)); + } + } + } +} + +// ── ownership ───────────────────────────────────────────────────────────────── + +Void::Testing::Test retry_blocking_move_only_value() +{ + const R::RetrySpec spec{}; + + // Move-only success value. + { + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected, int> { + if (++calls < 2) { + return std::unexpected{calls}; + } + return std::make_unique(42); + }, + make_options(world)); + expect(r.has_value()); + if (r.has_value()) { + expect(*r != nullptr); + if (*r != nullptr) { + expect_eq(**r, 42); + } + } + expect_eq(calls, 2); + expect_waits(world.waits, {100ms}); + } + + // The value can be moved out of the result. + { + FakeWorld world; + auto r = R::retry_blocking( + spec, + []() -> std::expected, int> { + return std::make_unique("owned"); + }, + make_options(world)); + expect(r.has_value()); + if (r.has_value()) { + std::unique_ptr taken = std::move(*r); + expect(taken != nullptr); + if (taken != nullptr) { + expect_eq(*taken, std::string{"owned"}); + } + } + } + + // Move-only error type: kept as last_error without copying. + { + FakeWorld world; + int calls = 0; + const auto r = R::retry_blocking( + spec, + [&]() -> std::expected> { + return std::unexpected{ + std::make_unique("e" + + std::to_string(++calls))}; + }, + make_options(world)); + expect(!r.has_value()); + if (!r.has_value()) { + expect(r.error().last_error.has_value()); + if (r.error().last_error.has_value() && + *r.error().last_error != nullptr) { + expect_eq(**r.error().last_error, std::string{"e3"}); + } + expect_eq(r.error().attempts, std::uint32_t{3}); + } + } + + // The callable itself may be move-only and is invoked as an lvalue. + { + FakeWorld world; + auto counter = std::make_unique(0); + const auto r = R::retry_blocking( + spec, + [counter = std::move(counter)]() mutable + -> std::expected { + if (++*counter < 3) { + return std::unexpected{*counter}; + } + return *counter; + }, + make_options(world)); + expect(r.has_value()); + if (r.has_value()) { + expect_eq(*r, 3); + } + } +} + +// ── legacy behaviour, recorded for later work ───────────────────────────────── + +Void::Testing::Test legacy_retry_zero_attempts_behavior_pinned() +{ + // 1.x defect, pinned on purpose and recorded for Wave C: with + // max_attempts == 0 the legacy retry(), retry_while() and + // retry_or_throw() never call the callable and return a + // default-constructed result, which for retry() is a *successful* + // std::expected. Do not "fix" this here; retry_blocking() is the API that + // rejects zero attempts (see retry_blocking_zero_attempts_*). + const R::Policy policy{.max_attempts = 0}; + + int calls = 0; + const auto r = R::retry(policy, [&]() -> std::expected { + ++calls; + return std::unexpected{std::string{"never called"}}; + }); + expect_eq(calls, 0); + expect(r.has_value()); + if (r.has_value()) { + expect_eq(*r, 0); + } + + int while_calls = 0; + int predicate_calls = 0; + const int w = R::retry_while( + policy, + [&]() -> int { + ++while_calls; + return 503; + }, + [&](int) { + ++predicate_calls; + return true; + }); + expect_eq(while_calls, 0); + expect_eq(predicate_calls, 0); + expect_eq(w, 0); + + int throw_calls = 0; + const int v = + R::retry_or_throw(policy, [&]() -> std::expected { + ++throw_calls; + return std::unexpected{std::string{"never called"}}; + }); + expect_eq(throw_calls, 0); + expect_eq(v, 0); +} + +// ── default (real) options, immediate paths only ───────────────────────────── + +Void::Testing::Test retry_blocking_thread_sleep_honors_stop_and_zero_wait() +{ + R::ThreadSleep thread_sleep; + + // A stop that is already requested wins without blocking, however long + // the wait. + { + std::stop_source source; + source.request_stop(); + expect(!thread_sleep(1h, source.get_token())); + expect(!thread_sleep(Ns::max(), source.get_token())); + } + + // A zero or negative wait returns at once, stoppable token or not. + { + std::stop_source source; + expect(thread_sleep(0ns, source.get_token())); + expect(thread_sleep(-5ns, source.get_token())); + expect(thread_sleep(0ns, std::stop_token{})); + expect(thread_sleep(Ns::min(), std::stop_token{})); + } + + // A stop request from another thread ends an hour-long wait. The request + // may land before or after the wait begins; either way the call returns + // false promptly, so the outcome does not depend on timing. + { + std::stop_source source; + std::jthread requester{[&source] { source.request_stop(); }}; + expect(!thread_sleep(1h, source.get_token())); + } +} + +Void::Testing::Test retry_blocking_defaults_compile_and_run() +{ + // No options argument: steady clock, thread sleep, retry-everything + // classifier and a random_device-seeded engine are all defaults. The + // delay is zero, so ThreadSleep returns immediately and nothing blocks. + const auto spec = constant_delay_spec(0ns, std::nullopt, 3); + + int calls = 0; + const auto failed = R::retry_blocking( + spec, [&]() -> std::expected { + return std::unexpected{++calls}; + }); + expect(!failed.has_value()); + if (!failed.has_value()) { + expect_eq(static_cast(failed.error().reason), + static_cast(R::RetryStopReason::attempts_exhausted)); + expect_eq(failed.error().attempts, std::uint32_t{3}); + } + expect_eq(calls, 3); + + int second_calls = 0; + const auto ok = R::retry_blocking( + spec, [&]() -> std::expected { + if (++second_calls < 2) { + return std::unexpected{second_calls}; + } + return 9; + }); + expect(ok.has_value()); + if (ok.has_value()) { + expect_eq(*ok, 9); + } + expect_eq(second_calls, 2); + + // Options with only the stop token set (all other members defaulted) + // work through the fully-spelled type as well. + std::stop_source source; + source.request_stop(); + R::BlockingRetryOptions<> options; + options.stop = source.get_token(); + int stopped_calls = 0; + const auto stopped = R::retry_blocking( + spec, + [&]() -> std::expected { + ++stopped_calls; + return 1; + }, + std::move(options)); + expect(!stopped.has_value()); + expect_eq(stopped_calls, 0); +} diff --git a/tests/standalone/Functional/RetryState.cpp b/tests/standalone/Functional/RetryState.cpp new file mode 100644 index 0000000..8e82060 --- /dev/null +++ b/tests/standalone/Functional/RetryState.cpp @@ -0,0 +1,1201 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Pure decision-engine tests: no clock is read and nothing sleeps. Every +// time value is passed in explicitly. + +namespace +{ + using namespace std::chrono_literals; + namespace R = Void::Retry; + using Void::Testing::expect; + using Void::Testing::expect_eq; + + using R::SteadyTimePoint; + using Engine = std::mt19937_64; + using Loc = std::source_location; + + constexpr SteadyTimePoint t0{std::chrono::seconds{1000}}; + + // A deterministic engine that cannot be seeded from one integer, so + // detail::seeded_engine<> has to fall back to default construction. + struct StepEngine { + using result_type = std::uint64_t; + StepEngine() = default; + static constexpr result_type min() noexcept { return 0; } + static constexpr result_type max() noexcept + { + return std::numeric_limits::max(); + } + result_type operator()() noexcept + { + state += 0x9E3779B97F4A7C15ULL; + return state; + } + result_type state{0}; + }; + // An engine seeded from a type narrower than random_device::result_type: + // seeded_engine<> must construct it with parentheses, because list + // initialisation would reject the narrowing conversion. + struct NarrowSeedEngine { + using result_type = std::uint64_t; + explicit NarrowSeedEngine(std::uint16_t seed) : state{seed} {} + static constexpr result_type min() noexcept { return 0; } + static constexpr result_type max() noexcept + { + return std::numeric_limits::max(); + } + result_type operator()() noexcept + { + state += 0x9E3779B97F4A7C15ULL; + return state; + } + result_type state; + }; + static_assert(std::uniform_random_bit_generator); + static_assert(std::is_constructible_v); + static_assert(std::uniform_random_bit_generator); + static_assert( + !std::is_constructible_v); + + void expect_ns(std::chrono::nanoseconds actual, + std::chrono::nanoseconds expected, Loc loc = Loc::current()) + { + expect_eq(actual.count(), expected.count(), loc); + } + + void expect_tp(SteadyTimePoint actual, SteadyTimePoint expected, + Loc loc = Loc::current()) + { + expect_eq(actual.time_since_epoch().count(), + expected.time_since_epoch().count(), loc); + } + + void expect_attempt(const R::RetryDecision& d, std::uint32_t attempts, + Loc loc = Loc::current()) + { + expect_eq(static_cast(d.action), + static_cast(R::RetryAction::attempt), loc); + expect_eq(static_cast(d.reason), + static_cast(R::RetryStopReason::none), loc); + expect_eq(d.attempts_started, attempts, loc); + } + + void expect_wait(const R::RetryDecision& d, SteadyTimePoint at, + std::uint32_t attempts, Loc loc = Loc::current()) + { + expect_eq(static_cast(d.action), + static_cast(R::RetryAction::wait_until), loc); + expect_eq(static_cast(d.reason), + static_cast(R::RetryStopReason::none), loc); + expect_tp(d.at, at, loc); + expect_eq(d.attempts_started, attempts, loc); + } + + void expect_stop(const R::RetryDecision& d, R::RetryStopReason reason, + std::uint32_t attempts, Loc loc = Loc::current()) + { + expect_eq(static_cast(d.action), + static_cast(R::RetryAction::stop), loc); + expect_eq(static_cast(d.reason), static_cast(reason), loc); + expect_eq(d.attempts_started, attempts, loc); + } + + void expect_invalid(const R::RetrySpec& spec, R::RetryConfigError error, + Loc loc = Loc::current()) + { + const auto v = R::validate(spec); + expect(!v.has_value(), loc); + if (!v.has_value()) { + expect_eq(static_cast(v.error()), static_cast(error), + loc); + } + const auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(!created.has_value(), loc); + if (!created.has_value()) { + expect_eq(static_cast(created.error()), + static_cast(error), loc); + } + } + + void expect_valid(const R::RetrySpec& spec, Loc loc = Loc::current()) + { + expect(R::validate(spec).has_value(), loc); + expect(R::RetryState::create(spec, t0, Engine{42}).has_value(), + loc); + } + + // Bulk checks are folded into one assertion each: the test runner keeps + // only the first 1000 assertions of a test (kMaxRetainedAssertionsPerTest) + // and decides pass/fail from those, so a failure past that point would be + // lost. Counting violations keeps every check visible. + void expect_all_within(const std::vector& values, + std::chrono::nanoseconds lo, + std::chrono::nanoseconds hi, + Loc loc = Loc::current()) + { + std::size_t outside = 0; + for (const auto v : values) { + if (v < lo || v > hi) { + ++outside; + } + } + expect_eq(outside, std::size_t{0}, loc); + } + + // Drives begin / next / resume with every attempt failing retryably and + // the clock jumping straight to each wake-up time. Returns the wait + // lengths (`at - now`) in order; stops after `retries` waits or at the + // first non-wait decision. + template + [[nodiscard]] std::vector + collect_waits(R::RetryState& state, SteadyTimePoint now, + std::size_t retries) + { + std::vector waits; + R::RetryDecision d = state.begin(now); + for (std::size_t i = 0; + i < retries && d.action == R::RetryAction::attempt; ++i) { + const R::RetryDecision n = + state.next(now, R::AttemptOutcome::retryable_failure); + if (n.action != R::RetryAction::wait_until) { + break; + } + waits.push_back(n.at - now); + now = n.at; + d = state.resume(now); + } + return waits; + } + + [[nodiscard]] R::RetrySpec constant_delay_spec( + std::chrono::nanoseconds delay, + std::optional jitter, std::uint32_t attempts = 1000) + { + R::RetrySpec spec; + spec.max_attempts = attempts; + spec.budget = R::no_deadline; + spec.backoff.initial = delay; + spec.backoff.cap = delay; + spec.backoff.multiplier = 1.0; + spec.backoff.jitter = jitter; + return spec; + } +} // namespace + +// ── validation ──────────────────────────────────────────────────────────────── + +Void::Testing::Test retry_state_rejects_invalid_specs() +{ + using E = R::RetryConfigError; + + // zero_attempts + { + R::RetrySpec spec; + spec.max_attempts = 0; + expect_invalid(spec, E::zero_attempts); + } + + // negative_duration: initial, cap and budget are each checked + { + R::RetrySpec spec; + spec.backoff.initial = -1ns; + expect_invalid(spec, E::negative_duration); + } + { + R::RetrySpec spec; + spec.backoff.cap = -1ns; + expect_invalid(spec, E::negative_duration); + } + { + R::RetrySpec spec; + spec.budget = -1ns; + expect_invalid(spec, E::negative_duration); + } + { + R::RetrySpec spec; + spec.budget = std::chrono::nanoseconds::min(); + expect_invalid(spec, E::negative_duration); + } + + // zero_budget: 0 is rejected rather than meaning "unlimited" + { + R::RetrySpec spec; + spec.budget = 0ns; + expect_invalid(spec, E::zero_budget); + } + + // nonfinite_multiplier + for (const double m : {std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity(), + -std::numeric_limits::infinity()}) { + R::RetrySpec spec; + spec.backoff.multiplier = m; + expect_invalid(spec, E::nonfinite_multiplier); + } + + // multiplier_below_one + for (const double m : {0.5, 0.0, -2.0, std::nextafter(1.0, 0.0)}) { + R::RetrySpec spec; + spec.backoff.multiplier = m; + expect_invalid(spec, E::multiplier_below_one); + } + + // cap_below_initial + { + R::RetrySpec spec; + spec.backoff.initial = 2s; + spec.backoff.cap = 1s; + expect_invalid(spec, E::cap_below_initial); + } + + // Precedence: the first failing check in the documented order wins. + { + R::RetrySpec spec; + spec.max_attempts = 0; + spec.budget = -1ns; + spec.backoff.multiplier = std::numeric_limits::quiet_NaN(); + expect_invalid(spec, E::zero_attempts); + } + { + R::RetrySpec spec; + spec.backoff.cap = -1ns; // also below initial + spec.backoff.multiplier = std::numeric_limits::quiet_NaN(); + expect_invalid(spec, E::negative_duration); + } + { + R::RetrySpec spec; + spec.budget = 0ns; + spec.backoff.multiplier = 0.5; + expect_invalid(spec, E::zero_budget); + } + { + R::RetrySpec spec; + spec.backoff.multiplier = std::numeric_limits::quiet_NaN(); + spec.backoff.initial = 2s; + spec.backoff.cap = 1s; + expect_invalid(spec, E::nonfinite_multiplier); + } + { + R::RetrySpec spec; + spec.backoff.multiplier = 0.5; + spec.backoff.initial = 2s; + spec.backoff.cap = 1s; + expect_invalid(spec, E::multiplier_below_one); + } + + // Boundary values that are valid. + expect_valid(R::RetrySpec{}); + { + R::RetrySpec spec; + spec.max_attempts = 1; + expect_valid(spec); + spec.max_attempts = std::numeric_limits::max(); + expect_valid(spec); + } + { + R::RetrySpec spec; + spec.backoff.multiplier = 1.0; + spec.backoff.cap = spec.backoff.initial; + expect_valid(spec); + } + { + R::RetrySpec spec; + spec.budget = R::no_deadline; + expect_valid(spec); + spec.budget = 1ns; + expect_valid(spec); + } + { + R::RetrySpec spec; // zero delays are allowed + spec.backoff.initial = 0ns; + spec.backoff.cap = 0ns; + expect_valid(spec); + } +} + +// ── exact attempt counts ────────────────────────────────────────────────────── + +Void::Testing::Test retry_state_exact_three_attempts_default() +{ + const R::RetrySpec spec{}; // 3 attempts, 30s budget, 100ms x2 up to 30s + expect_eq(spec.max_attempts, std::uint32_t{3}); + + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_eq(state.attempts_started(), std::uint32_t{0}); + + std::uint32_t attempts = 0; + SteadyTimePoint now = t0; + + R::RetryDecision d = state.begin(now); + expect_attempt(d, 1); + attempts += (d.action == R::RetryAction::attempt) ? 1U : 0U; + expect_eq(state.attempts_started(), std::uint32_t{1}); + + // retry index 0 -> 100ms + d = state.next(now, R::AttemptOutcome::retryable_failure); + expect_wait(d, now + 100ms, 1); + now = d.at; + d = state.resume(now); + expect_attempt(d, 2); + attempts += (d.action == R::RetryAction::attempt) ? 1U : 0U; + + // retry index 1 -> 200ms + d = state.next(now, R::AttemptOutcome::retryable_failure); + expect_wait(d, now + 200ms, 2); + now = d.at; + d = state.resume(now); + expect_attempt(d, 3); + attempts += (d.action == R::RetryAction::attempt) ? 1U : 0U; + + // the third failure leaves no attempt to retry + d = state.next(now, R::AttemptOutcome::retryable_failure); + expect_stop(d, R::RetryStopReason::attempts_exhausted, 3); + + expect_eq(attempts, std::uint32_t{3}); + expect_eq(state.attempts_started(), std::uint32_t{3}); + expect_tp(now, t0 + 300ms); + + // Asking again keeps answering "exhausted" and never starts an attempt. + d = state.next(now, R::AttemptOutcome::retryable_failure); + expect_stop(d, R::RetryStopReason::attempts_exhausted, 3); + expect_eq(state.attempts_started(), std::uint32_t{3}); +} + +Void::Testing::Test retry_state_attempt_counter_stays_bounded() +{ + // A single allowed attempt: next() stops, and a misused resume() cannot + // push the counter past max_attempts. + R::RetrySpec spec; + spec.max_attempts = 1; + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.next(t0, R::AttemptOutcome::retryable_failure), + R::RetryStopReason::attempts_exhausted, 1); + expect_stop(state.resume(t0), R::RetryStopReason::attempts_exhausted, 1); + expect_eq(state.attempts_started(), std::uint32_t{1}); + + // UINT32_MAX attempts: counters and the delay index do not overflow. + R::RetrySpec big; + big.max_attempts = std::numeric_limits::max(); + big.budget = R::no_deadline; + auto big_created = R::RetryState::create(big, t0, Engine{42}); + expect(big_created.has_value()); + auto& big_state = *big_created; + SteadyTimePoint now = t0; + expect_attempt(big_state.begin(now), 1); + for (std::uint32_t i = 1; i <= 40; ++i) { + const auto n = + big_state.next(now, R::AttemptOutcome::retryable_failure); + expect_eq(static_cast(n.action), + static_cast(R::RetryAction::wait_until)); + expect_eq(n.attempts_started, i); + // no jitter: wait is the unjittered, saturated delay + expect_ns(n.at - now, R::backoff_delay(big.backoff, i - 1)); + now = n.at; + expect_attempt(big_state.resume(now), i + 1); + } + expect_eq(big_state.attempts_started(), std::uint32_t{41}); +} + +// ── deadlines ───────────────────────────────────────────────────────────────── + +Void::Testing::Test retry_state_deadline_at_admission_prevents_first_attempt() +{ + const R::RetrySpec spec{}; // 30s budget + + // Admission deadline equal to the start time: not even one attempt. + { + auto created = R::RetryState::create(spec, t0, Engine{42}, t0); + expect(created.has_value()); + auto& state = *created; + expect(state.deadline().has_value()); + if (state.deadline().has_value()) { + expect_tp(*state.deadline(), t0); + } + const auto d = state.begin(t0); + expect_stop(d, R::RetryStopReason::deadline_exceeded, 0); + expect_eq(state.attempts_started(), std::uint32_t{0}); + } + + // Admission deadline already in the past. + { + auto created = + R::RetryState::create(spec, t0, Engine{42}, t0 - 1s); + expect(created.has_value()); + auto& state = *created; + expect(state.deadline().has_value()); + if (state.deadline().has_value()) { + expect_tp(*state.deadline(), t0 - 1s); + } + expect_stop(state.begin(t0), R::RetryStopReason::deadline_exceeded, 0); + expect_eq(state.attempts_started(), std::uint32_t{0}); + } + + // now == deadline is exceeded; one nanosecond earlier is still allowed. + { + auto created = + R::RetryState::create(spec, t0, Engine{42}, t0 + 1ms); + expect(created.has_value()); + expect_attempt(created->begin(t0 + 1ms - 1ns), 1); + } + { + auto created = + R::RetryState::create(spec, t0, Engine{42}, t0 + 1ms); + expect(created.has_value()); + expect_stop(created->begin(t0 + 1ms), + R::RetryStopReason::deadline_exceeded, 0); + } + + // The effective deadline is the earlier of start + budget and admission. + { + auto later = R::RetryState::create(spec, t0, Engine{42}, t0 + 1h); + expect(later.has_value()); + expect(later->deadline().has_value()); + if (later->deadline().has_value()) { + expect_tp(*later->deadline(), t0 + 30s); + } + auto none = R::RetryState::create(spec, t0, Engine{42}); + expect(none.has_value()); + expect(none->deadline().has_value()); + if (none->deadline().has_value()) { + expect_tp(*none->deadline(), t0 + 30s); + } + } + + // start + budget saturates instead of overflowing. + { + R::RetrySpec huge; + huge.budget = std::chrono::nanoseconds::max(); + auto created = R::RetryState::create(huge, t0 + 1h, Engine{42}); + expect(created.has_value()); + expect(created->deadline().has_value()); + if (created->deadline().has_value()) { + expect_tp(*created->deadline(), SteadyTimePoint::max()); + } + } + + // The budget deadline itself also rejects a late begin(). + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + expect_stop(created->begin(t0 + 30s), + R::RetryStopReason::deadline_exceeded, 0); + } +} + +Void::Testing::Test retry_state_backoff_overshooting_deadline_stops() +{ + R::RetrySpec spec; // 100ms, 200ms, 400ms, ... + spec.max_attempts = 10; + + auto run = [&](std::chrono::nanoseconds budget) { + spec.budget = budget; + return R::RetryState::create(spec, t0, Engine{42}); + }; + + // Budget 250ms: the 200ms wait after attempt 2 would end at 300ms. + { + auto created = run(250ms); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + auto d = state.next(t0, R::AttemptOutcome::retryable_failure); + expect_wait(d, t0 + 100ms, 1); + expect_attempt(state.resume(t0 + 100ms), 2); + d = state.next(t0 + 100ms, R::AttemptOutcome::retryable_failure); + expect_stop(d, R::RetryStopReason::deadline_exceeded, 2); + } + + // Budget 300ms: the wake-up lands exactly on the deadline, which counts + // as exceeded. + { + auto created = run(300ms); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_wait(state.next(t0, R::AttemptOutcome::retryable_failure), + t0 + 100ms, 1); + expect_attempt(state.resume(t0 + 100ms), 2); + expect_stop(state.next(t0 + 100ms, + R::AttemptOutcome::retryable_failure), + R::RetryStopReason::deadline_exceeded, 2); + } + + // Budget 300ms + 1ns: the same wake-up is now one nanosecond early. + { + auto created = run(300ms + 1ns); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_wait(state.next(t0, R::AttemptOutcome::retryable_failure), + t0 + 100ms, 1); + expect_attempt(state.resume(t0 + 100ms), 2); + expect_wait(state.next(t0 + 100ms, + R::AttemptOutcome::retryable_failure), + t0 + 300ms, 2); + } + + // A long attempt that already consumed the budget: the next wait cannot + // fit, even though attempts remain. + { + auto created = run(1s); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.next(t0 + 2s, R::AttemptOutcome::retryable_failure), + R::RetryStopReason::deadline_exceeded, 1); + } + + // resume() re-checks the deadline at the time the wait actually ended. + { + auto created = run(1s); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_wait(state.next(t0, R::AttemptOutcome::retryable_failure), + t0 + 100ms, 1); + expect_stop(state.resume(t0 + 1s), + R::RetryStopReason::deadline_exceeded, 1); + expect_eq(state.attempts_started(), std::uint32_t{1}); + } +} + +Void::Testing::Test retry_state_no_deadline_explicit_marker() +{ + expect(R::no_deadline == R::NoDeadline{}); + + R::RetrySpec spec; + spec.max_attempts = 5; + spec.budget = R::no_deadline; + expect_valid(spec); + + // With no admission deadline there is no deadline at all, however far in + // the future the clock is. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect(!state.deadline().has_value()); + + SteadyTimePoint now = SteadyTimePoint::max() - 1h; + expect_attempt(state.begin(now), 1); + const std::chrono::nanoseconds expected[] = {100ms, 200ms, 400ms, + 800ms}; + std::uint32_t attempts = 1; + for (const auto delay : expected) { + const auto d = + state.next(now, R::AttemptOutcome::retryable_failure); + expect_wait(d, now + delay, attempts); + now = d.at; + expect_attempt(state.resume(now), ++attempts); + } + expect_eq(attempts, std::uint32_t{5}); + expect_stop(state.next(now, R::AttemptOutcome::retryable_failure), + R::RetryStopReason::attempts_exhausted, 5); + } + + // An admission deadline still applies on its own. + { + auto created = + R::RetryState::create(spec, t0, Engine{42}, t0 + 150ms); + expect(created.has_value()); + auto& state = *created; + expect(state.deadline().has_value()); + if (state.deadline().has_value()) { + expect_tp(*state.deadline(), t0 + 150ms); + } + expect_attempt(state.begin(t0), 1); + expect_wait(state.next(t0, R::AttemptOutcome::retryable_failure), + t0 + 100ms, 1); + expect_attempt(state.resume(t0 + 100ms), 2); + expect_stop(state.next(t0 + 100ms, + R::AttemptOutcome::retryable_failure), + R::RetryStopReason::deadline_exceeded, 2); + } +} + +// ── backoff saturation ──────────────────────────────────────────────────────── + +Void::Testing::Test retry_state_backoff_saturates_without_overflow() +{ + const R::BackoffSpec def{}; // 100ms, cap 30s, x2 + expect_ns(R::backoff_delay(def, 0), 100ms); + expect_ns(R::backoff_delay(def, 1), 200ms); + expect_ns(R::backoff_delay(def, 2), 400ms); + expect_ns(R::backoff_delay(def, 8), 25'600ms); + expect_ns(R::backoff_delay(def, 9), 30s); // 51.2s clamped + expect_ns(R::backoff_delay(def, 63), 30s); + expect_ns(R::backoff_delay(def, 1'000'000), 30s); + expect_ns(R::backoff_delay(def, std::numeric_limits::max()), + 30s); + + constexpr auto ns_max = std::chrono::nanoseconds::max(); + + // Absurd multiplier: the product leaves double range and still saturates. + { + R::BackoffSpec b; + b.multiplier = 1e300; + expect_ns(R::backoff_delay(b, 0), 100ms); + expect_ns(R::backoff_delay(b, 1), 30s); + expect_ns(R::backoff_delay(b, 1000), 30s); + expect_ns(R::backoff_delay( + b, std::numeric_limits::max()), + 30s); + } + + // initial and cap near the top of the integer range. + { + R::BackoffSpec b; + b.initial = ns_max / 2; + b.cap = ns_max; + b.multiplier = 1e300; + expect_ns(R::backoff_delay(b, 0), ns_max / 2); + expect_ns(R::backoff_delay(b, 1), ns_max); + expect_ns(R::backoff_delay(b, 2), ns_max); + } + { + // Constant backoff is exact even where double cannot represent it. + R::BackoffSpec b; + b.initial = ns_max - 1ns; + b.cap = ns_max; + b.multiplier = 1.0; + expect_ns(R::backoff_delay(b, 0), ns_max - 1ns); + expect_ns(R::backoff_delay(b, 77), ns_max - 1ns); + } + { + // A product just below the cap converts exactly; the next one clamps. + R::BackoffSpec b; + b.initial = std::chrono::nanoseconds{1'000'000'000'000'000'000}; + b.cap = ns_max; + b.multiplier = 2.0; + expect_ns(R::backoff_delay(b, 3), + std::chrono::nanoseconds{8'000'000'000'000'000'000}); + expect_ns(R::backoff_delay(b, 4), ns_max); + } + + // backoff_delay() is total even for specs that validate() rejects: it + // never overflows and stays within [0, cap]. + { + R::BackoffSpec b; + b.multiplier = std::numeric_limits::quiet_NaN(); + const auto nan_delay = R::backoff_delay(b, 3); + expect(nan_delay >= 0ns); + expect(nan_delay <= b.cap); + b.multiplier = std::numeric_limits::infinity(); + expect_ns(R::backoff_delay(b, 1), b.cap); + b.multiplier = -1e300; + const auto negative = R::backoff_delay(b, 1); + expect(negative >= 0ns); + expect(negative <= b.cap); + b.multiplier = 0.5; + const auto shrinking = R::backoff_delay(b, 4); + expect(shrinking >= 0ns); + expect(shrinking <= b.cap); + R::BackoffSpec zero; + zero.initial = 0ns; + zero.multiplier = std::numeric_limits::infinity(); + expect_ns(R::backoff_delay(zero, 5), 0ns); + R::BackoffSpec negative_initial; + negative_initial.initial = -5ns; + expect_ns(R::backoff_delay(negative_initial, 2), 0ns); + } + + // Through the state machine: a saturated delay added to the clock + // saturates too, and an unlimited budget still allows the wait. + { + R::RetrySpec spec; + spec.max_attempts = 5; + spec.budget = R::no_deadline; + spec.backoff.initial = ns_max / 2; + spec.backoff.cap = ns_max; + spec.backoff.multiplier = 1e300; + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + const auto first = + state.next(t0, R::AttemptOutcome::retryable_failure); + expect_wait(first, t0 + ns_max / 2, 1); + expect_attempt(state.resume(first.at), 2); + const auto second = + state.next(first.at, R::AttemptOutcome::retryable_failure); + expect_wait(second, SteadyTimePoint::max(), 2); + } + + // ... and a finite budget turns the same overshoot into a clean stop. + { + R::RetrySpec spec; + spec.max_attempts = 5; + spec.budget = 1h; + spec.backoff.initial = ns_max / 2; + spec.backoff.cap = ns_max; + spec.backoff.multiplier = 1e300; + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.next(t0, R::AttemptOutcome::retryable_failure), + R::RetryStopReason::deadline_exceeded, 1); + } +} + +// ── jitter ──────────────────────────────────────────────────────────────────── + +// clang-format off +Void::Testing::Test retry_state_full_equal_jitter_bounds_and_seed_reproducibility() +// clang-format on +{ + constexpr auto delay = 100ms; + + for (const R::JitterMode mode : + {R::JitterMode::Full, R::JitterMode::Equal}) { + const auto spec = constant_delay_spec(delay, mode); + const auto lo = (mode == R::JitterMode::Equal) ? delay / 2 : 0ms; + + auto a = R::RetryState::create(spec, t0, Engine{42}); + auto b = R::RetryState::create(spec, t0, Engine{42}); + auto c = R::RetryState::create(spec, t0, Engine{43}); + expect(a.has_value() && b.has_value() && c.has_value()); + if (!(a.has_value() && b.has_value() && c.has_value())) { + return; + } + const auto wa = collect_waits(*a, t0, 500); + const auto wb = collect_waits(*b, t0, 500); + const auto wc = collect_waits(*c, t0, 500); + expect_eq(wa.size(), std::size_t{500}); + + expect_all_within(wa, lo, delay); + // Same seed: same schedule. Different seed: a different schedule. + expect(wa == wb); + expect(wa != wc); + // The delay really is randomised. + const std::set distinct = [&] { + std::set s; + for (const auto w : wa) { + s.insert(w.count()); + } + return s; + }(); + expect(distinct.size() > 1); + } + + // Tiny delays pin the exact formula: Full is uniform in [0, d], Equal is + // d/2 + uniform in [0, d - d/2]. Every value in range shows up and none + // outside it does. + struct Case { + std::chrono::nanoseconds d; + R::JitterMode mode; + std::set expected; + }; + const Case cases[] = { + {3ns, R::JitterMode::Full, {0, 1, 2, 3}}, + {3ns, R::JitterMode::Equal, {1, 2, 3}}, + {2ns, R::JitterMode::Equal, {1, 2}}, + {1ns, R::JitterMode::Equal, {0, 1}}, + {1ns, R::JitterMode::Full, {0, 1}}, + }; + for (const auto& c : cases) { + const auto spec = constant_delay_spec(c.d, c.mode, 5000); + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + if (!created.has_value()) { + return; + } + std::set seen; + for (const auto w : collect_waits(*created, t0, 2000)) { + seen.insert(w.count()); + } + expect(seen == c.expected); + } + + // Growing backoff: each wait is bounded by that retry's own delay. + for (const R::JitterMode mode : + {R::JitterMode::Full, R::JitterMode::Equal}) { + R::RetrySpec spec; + spec.max_attempts = 40; + spec.budget = R::no_deadline; + spec.backoff.jitter = mode; + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + if (!created.has_value()) { + return; + } + const auto waits = collect_waits(*created, t0, 39); + expect_eq(waits.size(), std::size_t{39}); + std::size_t outside = 0; + for (std::size_t k = 0; k < waits.size(); ++k) { + const auto d = + R::backoff_delay(spec.backoff, static_cast(k)); + const auto lo = (mode == R::JitterMode::Equal) ? d / 2 : 0ns; + if (waits[k] < lo || waits[k] > d) { + ++outside; + } + } + expect_eq(outside, std::size_t{0}); + } + + // A zero delay has nothing to randomise. + for (const R::JitterMode mode : + {R::JitterMode::Full, R::JitterMode::Equal}) { + const auto spec = constant_delay_spec(0ns, mode, 50); + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + if (!created.has_value()) { + return; + } + const auto waits = collect_waits(*created, t0, 20); + expect_eq(waits.size(), std::size_t{20}); + expect_all_within(waits, 0ns, 0ns); + } + + // The largest possible delay does not overflow the integer draw. + { + const auto spec = constant_delay_spec( + std::chrono::nanoseconds::max(), R::JitterMode::Equal, 10); + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + if (!created.has_value()) { + return; + } + expect_attempt(created->begin(t0), 1); + const auto d = + created->next(t0, R::AttemptOutcome::retryable_failure); + expect_eq(static_cast(d.action), + static_cast(R::RetryAction::wait_until)); + expect(d.at >= R::saturating_add( + t0, std::chrono::nanoseconds::max() / 2)); + } +} + +Void::Testing::Test retry_state_default_engine_jitter_in_bounds() +{ + constexpr auto delay = 100ms; + for (const R::JitterMode mode : + {R::JitterMode::Full, R::JitterMode::Equal}) { + const auto spec = constant_delay_spec(delay, mode); + const auto lo = (mode == R::JitterMode::Equal) ? delay / 2 : 0ms; + + // No engine argument: the default seeds std::mt19937_64 from + // std::random_device. Only bounds are checked, never values. + auto created = R::RetryState<>::create(spec, t0); + expect(created.has_value()); + if (!created.has_value()) { + return; + } + const auto waits = collect_waits(*created, t0, 300); + expect_eq(waits.size(), std::size_t{300}); + expect_all_within(waits, lo, delay); + } + + // The factory itself yields a usable engine, and falls back to default + // construction for engines that cannot be seeded from one integer. + { + auto engine = R::detail::seeded_engine(); + (void)engine(); + } + { + auto fallback = R::detail::seeded_engine(); + StepEngine reference{}; + for (int i = 0; i < 3; ++i) { + expect(fallback() == reference()); + } + } + { + // Narrow seed type: compiles because the seed is passed with + // parentheses; the resulting engine drives a state normally. + auto narrow = R::detail::seeded_engine(); + (void)narrow(); + const auto spec = constant_delay_spec(delay, R::JitterMode::Equal); + auto created = R::RetryState::create(spec, t0); + expect(created.has_value()); + if (!created.has_value()) { + return; + } + const auto waits = collect_waits(*created, t0, 100); + expect_eq(waits.size(), std::size_t{100}); + expect_all_within(waits, delay / 2, delay); + } + { + const auto spec = constant_delay_spec(delay, R::JitterMode::Full); + auto created = R::RetryState::create(spec, t0); + expect(created.has_value()); + if (!created.has_value()) { + return; + } + const auto waits = collect_waits(*created, t0, 100); + expect_eq(waits.size(), std::size_t{100}); + expect_all_within(waits, 0ns, delay); + } +} + +// ── stop requests and classification ────────────────────────────────────────── + +Void::Testing::Test retry_state_stop_prevents_next_attempt() +{ + const R::RetrySpec spec{}; + + // A stop request before the first attempt prevents it and wins over an + // expired deadline. + { + auto created = R::RetryState::create(spec, t0, Engine{42}, t0); + expect(created.has_value()); + auto& state = *created; + expect_stop(state.begin(t0, true), R::RetryStopReason::stop_requested, + 0); + expect_eq(state.attempts_started(), std::uint32_t{0}); + } + + // A stop request after a failed attempt ends the sequence without a wait. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.next(t0, R::AttemptOutcome::retryable_failure, true), + R::RetryStopReason::stop_requested, 1); + expect_eq(state.attempts_started(), std::uint32_t{1}); + } + + // A stop request that arrives while waiting is honoured by resume() and + // the attempt counter does not move. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + const auto d = state.next(t0, R::AttemptOutcome::retryable_failure); + expect_wait(d, t0 + 100ms, 1); + expect_stop(state.resume(d.at, true), + R::RetryStopReason::stop_requested, 1); + expect_eq(state.attempts_started(), std::uint32_t{1}); + } + + // stop wins over an expired deadline in resume() too. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.resume(t0 + 1h, true), + R::RetryStopReason::stop_requested, 1); + } + + // Precedence inside next(): permanent failure and exhaustion are + // reported ahead of a stop request. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.next(t0, R::AttemptOutcome::permanent_failure, true), + R::RetryStopReason::not_retryable, 1); + } + { + R::RetrySpec one; + one.max_attempts = 1; + auto created = R::RetryState::create(one, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.next(t0, R::AttemptOutcome::retryable_failure, true), + R::RetryStopReason::attempts_exhausted, 1); + } + + // Without a stop request the same sequence goes on. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0, false), 1); + expect_wait(state.next(t0, R::AttemptOutcome::retryable_failure, false), + t0 + 100ms, 1); + } +} + +Void::Testing::Test retry_state_permanent_failure_stops() +{ + const R::RetrySpec spec{}; + + // A permanent failure stops immediately even with attempts and budget + // left, and never produces a wait. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.next(t0, R::AttemptOutcome::permanent_failure), + R::RetryStopReason::not_retryable, 1); + } + + // Permanent after a retry: attempts_started reflects both attempts. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + const auto d = state.next(t0, R::AttemptOutcome::retryable_failure); + expect_wait(d, t0 + 100ms, 1); + expect_attempt(state.resume(d.at), 2); + expect_stop(state.next(d.at, R::AttemptOutcome::permanent_failure), + R::RetryStopReason::not_retryable, 2); + } + + // On the last attempt, not_retryable wins over attempts_exhausted. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + SteadyTimePoint now = t0; + expect_attempt(state.begin(now), 1); + for (std::uint32_t i = 2; i <= 3; ++i) { + const auto d = + state.next(now, R::AttemptOutcome::retryable_failure); + expect_eq(static_cast(d.action), + static_cast(R::RetryAction::wait_until)); + now = d.at; + expect_attempt(state.resume(now), i); + } + expect_stop(state.next(now, R::AttemptOutcome::permanent_failure), + R::RetryStopReason::not_retryable, 3); + } + + // Permanent also wins over an exceeded deadline. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.next(t0 + 1h, R::AttemptOutcome::permanent_failure), + R::RetryStopReason::not_retryable, 1); + } + + // succeed() ends the sequence with `succeeded` and the attempt count. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.succeed(), R::RetryStopReason::succeeded, 1); + } + + // The default classifier retries everything and ignores the error value. + expect(R::RetryEveryError{}(42) == R::AttemptOutcome::retryable_failure); + expect(R::RetryEveryError{}(std::string_view{"x"}) == + R::AttemptOutcome::retryable_failure); + static_assert(R::RetryEveryError{}(0) == + R::AttemptOutcome::retryable_failure); +} + +// ── saturating time arithmetic ──────────────────────────────────────────────── + +Void::Testing::Test retry_state_saturating_add_near_max() +{ + constexpr auto tp_max = SteadyTimePoint::max(); + constexpr auto tp_min = SteadyTimePoint::min(); + constexpr auto ns_max = std::chrono::nanoseconds::max(); + constexpr auto ns_min = std::chrono::nanoseconds::min(); + + // Compile-time evaluation is part of the contract. + static_assert(R::saturating_add(tp_max, 1ns) == tp_max); + static_assert(R::saturating_add(tp_min, -1ns) == tp_min); + static_assert(R::saturating_add(t0, 1s) == t0 + 1s); + + // Upward saturation. + expect_tp(R::saturating_add(tp_max, 1ns), tp_max); + expect_tp(R::saturating_add(tp_max, ns_max), tp_max); + expect_tp(R::saturating_add(tp_max - 1ns, 1ns), tp_max); + expect_tp(R::saturating_add(tp_max - 1ns, 2ns), tp_max); + expect_tp(R::saturating_add(tp_max - 10s, 10s), tp_max); + expect_tp(R::saturating_add(tp_max - 10s, 10s + 1ns), tp_max); + expect_tp(R::saturating_add(t0, ns_max), tp_max); + expect_tp(R::saturating_add(t0 + 1h, ns_max), tp_max); + + // Exact results right up to the boundary. + expect_tp(R::saturating_add(tp_max - 10s, 10s - 1ns), tp_max - 1ns); + expect_tp(R::saturating_add(tp_max - 10s, 5s), tp_max - 5s); + + // Downward saturation. + expect_tp(R::saturating_add(tp_min, -1ns), tp_min); + expect_tp(R::saturating_add(tp_min, ns_min), tp_min); + expect_tp(R::saturating_add(tp_min + 1ns, -1ns), tp_min); + expect_tp(R::saturating_add(tp_min + 1ns, -2ns), tp_min); + expect_tp(R::saturating_add(SteadyTimePoint{}, ns_min), tp_min); + expect_tp(R::saturating_add(tp_min + 5s, -5s), tp_min); + expect_tp(R::saturating_add(tp_min + 5s, -5s - 1ns), tp_min); + + // Ordinary arithmetic is unchanged. + expect_tp(R::saturating_add(t0, 0ns), t0); + expect_tp(R::saturating_add(t0, 1s), t0 + 1s); + expect_tp(R::saturating_add(t0, -1s), t0 - 1s); + expect_tp(R::saturating_add(t0, ns_min), t0 + ns_min); + expect_tp(R::saturating_add(tp_max, -1ns), tp_max - 1ns); + expect_tp(R::saturating_add(tp_min, 1ns), tp_min + 1ns); + expect_tp(R::saturating_add(tp_max, ns_min), tp_max + ns_min); +} + +// ── final stop decisions ───────────────────────────────────────────────────── + +Void::Testing::Test retry_state_stop_decisions_are_final() +{ + const R::RetrySpec spec{}; + + // After a stop request, a later resume() without the stop flag must not + // start another attempt: the stop decision is repeated. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.next(t0, R::AttemptOutcome::retryable_failure, true), + R::RetryStopReason::stop_requested, 1); + expect_stop(state.resume(t0), R::RetryStopReason::stop_requested, 1); + expect_stop(state.begin(t0), R::RetryStopReason::stop_requested, 1); + expect_eq(state.attempts_started(), std::uint32_t{1}); + } + + // After succeed(), begin()/resume()/next() keep reporting success. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.succeed(), R::RetryStopReason::succeeded, 1); + expect_stop(state.resume(t0), R::RetryStopReason::succeeded, 1); + expect_stop(state.next(t0, R::AttemptOutcome::retryable_failure), + R::RetryStopReason::succeeded, 1); + expect_eq(state.attempts_started(), std::uint32_t{1}); + } + + // A permanent failure stays final even if the caller ignores it. + { + auto created = R::RetryState::create(spec, t0, Engine{42}); + expect(created.has_value()); + auto& state = *created; + expect_attempt(state.begin(t0), 1); + expect_stop(state.next(t0, R::AttemptOutcome::permanent_failure), + R::RetryStopReason::not_retryable, 1); + expect_stop(state.resume(t0), R::RetryStopReason::not_retryable, 1); + expect_eq(state.attempts_started(), std::uint32_t{1}); + } +}