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>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-11-29 19:34:46 +03:00
1 parent 99203ce1f3
commit 26edf653e3
4 files changed
+2842 -2

No files matched your search

+181 -2
View File
@@ -1,13 +1,23 @@
#pragma once
#include <Void/Functional/RetryState.hpp>
#include <algorithm>
#include <chrono>
#include <concepts>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <limits>
#include <mutex>
#include <optional>
#include <random>
#include <stdexcept>
#include <stop_token>
#include <thread>
#include <type_traits>
#include <utility>
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 <typename Backoff = ExponentialBackoff> 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 <class NowFn = SteadyNow, class SleepFn = ThreadSleep,
class Classify = RetryEveryError, class URBG = std::mt19937_64>
struct BlockingRetryOptions {
NowFn now{};
SleepFn sleep{};
Classify classify{};
URBG urbg = detail::seeded_engine<URBG>();
std::stop_token stop{};
std::optional<SteadyTimePoint> deadline{};
};
namespace detail
{
template <class R> struct expected_traits;
template <class T, class E> struct expected_traits<std::expected<T, E>> {
using value_type = T;
using error_type = E;
};
template <class F>
using blocking_result_t = std::expected<
typename expected_traits<
std::remove_cvref_t<std::invoke_result_t<F&>>>::value_type,
RetryError<typename expected_traits<
std::remove_cvref_t<std::invoke_result_t<F&>>>::error_type>>;
} // namespace detail
// Runs `fn` (callable returning std::expected<T, E>) 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 <class F, class NowFn = SteadyNow, class SleepFn = ThreadSleep,
class Classify = RetryEveryError, class URBG = std::mt19937_64>
requires std::invocable<F&>
[[nodiscard]] auto
retry_blocking(const RetrySpec& spec, F&& fn,
BlockingRetryOptions<NowFn, SleepFn, Classify, URBG>
options = {}) -> detail::blocking_result_t<F>
{
using Result = std::remove_cvref_t<std::invoke_result_t<F&>>;
using T = typename detail::expected_traits<Result>::value_type;
using E = typename detail::expected_traits<Result>::error_type;
using Error = RetryError<E>;
using Out = std::expected<T, Error>;
static_assert(
std::is_invocable_r_v<AttemptOutcome, Classify&, const E&>,
"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<URBG>::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<URBG>& state = *created;
std::optional<E> 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<T>) {
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<Rep>::max() + now_ticks;
wait = overflows
? std::chrono::nanoseconds::max()
: std::chrono::duration_cast<std::chrono::nanoseconds>(
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
+416
View File
@@ -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 <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
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff