Files
Library/include/Void/Functional/RetryState.hpp
T
faumarayandClaude Opus 5.5 26edf653e3 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 <noreply@anthropic.com>
2026-11-29 19:34:46 +03:00

417 lines
14 KiB
C++

#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 <algorithm>
#include <chrono>
#include <cmath>
#include <concepts>
#include <cstdint>
#include <expected>
#include <limits>
#include <optional>
#include <random>
#include <type_traits>
#include <utility>
#include <variant>
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<JitterMode> 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<std::chrono::nanoseconds, NoDeadline> 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<void, RetryConfigError>
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<nanoseconds>(&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<double>(spec.cap.count());
const double raw =
static_cast<double>(spec.initial.count()) *
std::pow(spec.multiplier, static_cast<double>(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<nanoseconds::rep>(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<Rep> && std::is_signed_v<Rep>,
"steady_clock must have a signed integral rep");
const Rep base = tp.time_since_epoch().count();
const Rep step =
std::chrono::duration_cast<SteadyTimePoint::duration>(delta)
.count();
if (step >= 0) {
if (base > std::numeric_limits<Rep>::max() - step) {
return SteadyTimePoint::max();
}
} else if (base < std::numeric_limits<Rep>::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 <class G> 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 <std::uniform_random_bit_generator URBG = std::mt19937_64>
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<RetryState, RetryConfigError>
create(const RetrySpec& spec, SteadyTimePoint start,
URBG urbg = detail::seeded_engine<URBG>(),
std::optional<SteadyTimePoint> admission_deadline =
std::nullopt)
{
if (const auto valid = validate(spec); !valid) {
return std::unexpected{valid.error()};
}
std::optional<SteadyTimePoint> deadline = admission_deadline;
if (const auto* budget =
std::get_if<std::chrono::nanoseconds>(&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<SteadyTimePoint>
deadline() const noexcept
{
return deadline_;
}
private:
RetryState(std::uint32_t max_attempts, const BackoffSpec& backoff,
std::optional<SteadyTimePoint> 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<Rep> dist{0, full - floor};
return std::chrono::nanoseconds{floor + dist(urbg_)};
}
std::uint32_t max_attempts_;
BackoffSpec backoff_;
std::optional<SteadyTimePoint> deadline_;
URBG urbg_;
std::uint32_t attempts_started_{0};
std::optional<RetryStopReason> 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 <class E> struct RetryError {
RetryStopReason reason{};
std::uint32_t attempts{0};
std::optional<E> last_error{};
std::optional<RetryConfigError> config{};
};
// Default classifier: every error is worth retrying.
struct RetryEveryError {
template <class E>
[[nodiscard]] constexpr AttemptOutcome
operator()(const E&) const noexcept
{
return AttemptOutcome::retryable_failure;
}
};
} // namespace Void::Retry