# M-FUNCTIONAL-03 — Pure retry decisions and named blocking adapter Task ID: M-FUNCTIONAL-03 Role: sonnet-implementer Status: READY ## 1. Context and baseline - Wave 11 package step A1. - Repo: `/home/faumaray/Projects/VoidLibrary`, branch `feat/roadmap-p2-wave11`, HEAD `7f95f89` (root prep on `main` `38436b1`). You work in an isolated git worktree of `7f95f89`; your cwd is that worktree root. Do not touch the user's untracked files (`.env`, `WG.conf`, `keys`, `jev_token`). - Baseline: full suite at `38436b1` = 1,484 tests, 1,480 passed, 4 skipped, 0 failed. - Observed source (M-FUNCTIONAL-01 characterization folded in, D-035): - `include/Void/Functional/Retry.hpp` (tabs for indentation): backoff structs in milliseconds (`NoDelay`, `ConstantDelay`, `LinearBackoff`, `ExponentialBackoff`), `JitterMode` + `Jittered` (thread_local `mt19937_64` seeded from `std::random_device`, ~:76-95), `Policy{max_attempts=3, max_elapsed=0 → unlimited}` (~:100-110), `Detail::backoff_sleep` hard-wired to `steady_clock::now()`/`sleep_for` (~:117-142), `retry`/`retry_or_throw`/`retry_while`; with `max_attempts == 0` legacy `retry` returns a default-constructed (successful) `expected` without calling `fn` (~:150-211). - `src/Functional/module.cmake` declares no `INTERNAL_DEPS` (D-015: standard-library-only). - Consumers: `include/Void/Resilience/AsyncPolicy.hpp` uses `Void::Retry::ExponentialBackoff`, `JitterMode` (lines ~6, 486, 533) — must stay source-compatible. - Tests: `tests/standalone/Functional/Retry.cpp` (14), `RetryJitter.cpp` (4). - Requirements: roadmap row M-FUNCTIONAL-03 (`docs/roadmap/modules/Functional.md` "Pure retry and callable ownership", updated in `7f95f89`); decisions D-029, D-038; contracts C-02, C-04. ## 2. Objective and deliverables Roadmap acceptance: "Extract pure retry decisions and retain named blocking adapter; fake-time tests prove exact attempt counts, deadlines, jitter bounds and no zero-attempt success." Deliver: 1. NEW `include/Void/Functional/RetryState.hpp` — pure, standard-library-only decision engine. 2. EDIT `include/Void/Functional/Retry.hpp` — include `RetryState.hpp`, relocate `JitterMode` definition into it (same name/namespace), add `SteadyNow`, `ThreadSleep`, `BlockingRetryOptions`, `retry_blocking`. All 1.x symbols keep identical behavior. 3. NEW tests `tests/standalone/Functional/RetryState.cpp`, `tests/standalone/Functional/RetryBlocking.cpp`. ## 3. Scope and non-goals In: the above. Out: Time/Async adapters (`Async::retry_async` is M-TIME-03), changing any 1.x retry behavior (including the zero-attempt defect — pin it with a characterization test), Resilience changes, any build-file edit. ## 4. Files to inspect `include/Void/Functional/Retry.hpp` (all), `include/Void/Resilience/AsyncPolicy.hpp` (Retry uses), `tests/standalone/Functional/{Retry,RetryJitter}.cpp` (test style: `VOID_TEST`/assert macros, file stem = suite name), `src/Testing/Runner.cpp:209-225` (`--filter` is a regex over `suite.name`), `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §M-FUNCTIONAL-03 and `W11-PLAN-REV1-OUTPUT.md` F8/P3 (design source). ## 5. Write ownership and coordination Write scope: `include/Void/Functional/RetryState.hpp` (NEW), `include/Void/Functional/Retry.hpp`, `tests/standalone/Functional/RetryState.cpp` (NEW), `tests/standalone/Functional/RetryBlocking.cpp` (NEW). Forbidden: every other path (build files, other modules, docs). Another worker (M-TIME-03) runs concurrently in a different worktree and will later include `RetryState.hpp`; keep the interface exactly as specified. No git commit/branch/stash/reset; root integrates your diff. ## 6. Implementation or investigation approach 1. Create `RetryState.hpp` (namespace `Void::Retry`, includes only ` ` as needed; NO ``, NO `Void/...` include). Move `enum class JitterMode { Full, Equal };` here verbatim; remove it from `Retry.hpp` and `#include "Void/Functional/RetryState.hpp"` (match existing include style). 2. Implement the interface in §7 with the fixed semantics below. 3. Add the blocking adapter to `Retry.hpp` after the 1.x API, without touching 1.x bodies. 4. Write the tests (§10). Build/run per §11 (configure/build in your worktree; build dir under `/tmp/void-w11-fn3*`). Fixed semantics (mandatory): - `create` validates via `validate`; deadline = `min(saturating_add(start, budget), admission_deadline)` when budget is a duration; with `no_deadline` deadline is `admission_deadline` (may be none). - `begin(now, stop)`: stop → `{stop, reason=stop_requested}`; `now >= deadline` → `deadline_exceeded`; else `{attempt}` and `attempts_started` becomes 1. - `next(now, outcome, stop)` checks in order: permanent → `not_retryable`; `attempts_started == max_attempts` → `attempts_exhausted`; stop → `stop_requested`; else `at = saturating_add(now, jitter(backoff_delay(spec.backoff, attempts_started - 1)))`; `at >= deadline` → `deadline_exceeded`; else `{wait_until, at}`. `next` never returns `attempt`. - `resume(now, stop)`: re-checks stop and deadline, then `{attempt}` and increments `attempts_started`. - `succeed()` → `{stop, succeeded}`. - `backoff_delay(b, k)` = `initial * multiplier^k` saturated at `cap` before any integer conversion (compute in `long double`/`double`, clamp, then convert); never overflows; unjittered. - Full jitter: uniform integer ns in `[0, d]`; Equal: `d/2 + uniform[0, d - d/2]`. - Validation errors: `zero_attempts` (max_attempts == 0), `negative_duration` (initial/cap/budget < 0), `zero_budget` (budget duration == 0), `nonfinite_multiplier`, `multiplier_below_one`, `cap_below_initial`. - Default engine is seeded from `std::random_device` (F8): use `detail::seeded_engine()`. - `retry_blocking`: invalid spec → `RetryError{config=err, attempts=0}` without calling `fn`; waits are `decision.at - options.now()` passed to `options.sleep(wait, options.stop)`; a `false` return (stopped) ends with `stop_requested` and no further attempt; the adapter never calls `sleep_until`. `last_error` holds the most recent `E` (empty iff no attempt ran). Value type may be move-only. ## 7. Interfaces and data contracts ```cpp namespace Void::Retry { // RetryState.hpp (NEW) using SteadyTimePoint = std::chrono::steady_clock::time_point; enum class JitterMode { Full, Equal }; // EXISTING, relocated verbatim struct NoDeadline { constexpr bool operator==(const NoDeadline&) const noexcept = default; }; inline constexpr NoDeadline no_deadline{}; struct BackoffSpec { std::chrono::nanoseconds initial{std::chrono::milliseconds{100}}; std::chrono::nanoseconds cap{std::chrono::seconds{30}}; double multiplier{2.0}; std::optional jitter{}; }; struct RetrySpec { std::uint32_t max_attempts{3}; // total, including the first 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 }; 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}; SteadyTimePoint at{}; RetryStopReason reason{RetryStopReason::none}; std::uint32_t attempts_started{0}; }; [[nodiscard]] std::expected validate(const RetrySpec&) noexcept; [[nodiscard]] std::chrono::nanoseconds backoff_delay(const BackoffSpec&, std::uint32_t retry_index) noexcept; [[nodiscard]] constexpr SteadyTimePoint saturating_add(SteadyTimePoint, std::chrono::nanoseconds) noexcept; namespace detail { template G seeded_engine(); } // random_device seed if constructible template class RetryState { public: [[nodiscard]] static std::expected create(const RetrySpec&, SteadyTimePoint start, URBG urbg = detail::seeded_engine(), std::optional admission_deadline = std::nullopt); [[nodiscard]] RetryDecision begin(SteadyTimePoint now, bool stop_requested = false) noexcept; [[nodiscard]] RetryDecision next(SteadyTimePoint now, AttemptOutcome, bool stop_requested = false) noexcept; [[nodiscard]] RetryDecision resume(SteadyTimePoint now, bool stop_requested = false) noexcept; [[nodiscard]] RetryDecision succeed() noexcept; [[nodiscard]] std::uint32_t attempts_started() const noexcept; [[nodiscard]] std::optional deadline() const noexcept; }; template struct RetryError { RetryStopReason reason{}; std::uint32_t attempts{0}; std::optional last_error{}; std::optional config{}; }; struct RetryEveryError { template constexpr AttemptOutcome operator()(const E&) const noexcept { return AttemptOutcome::retryable_failure; } }; } namespace Void::Retry { // Retry.hpp additions (NEW) struct SteadyNow { SteadyTimePoint operator()() const noexcept { return std::chrono::steady_clock::now(); } }; struct ThreadSleep { bool operator()(std::chrono::nanoseconds wait, std::stop_token) const; }; // condition_variable_any + stop; false if stopped template struct BlockingRetryOptions { NowFn now{}; SleepFn sleep{}; Classify classify{}; URBG urbg = detail::seeded_engine(); std::stop_token stop{}; std::optional deadline{}; }; template // F() -> std::expected [[nodiscard]] auto retry_blocking(const RetrySpec&, F&& fn, BlockingRetryOptions options = {}) -> std::expected>; // T,E deduced from F's result } ``` `ThreadSleep` may live inline in `Retry.hpp` (which already includes ``). Unchanged 1.x: `NoDelay`, `ConstantDelay`, `LinearBackoff`, `ExponentialBackoff`, `Jittered`, `JitterMode`, `Policy`, `Detail::backoff_sleep`, `retry`, `retry_or_throw`, `retry_while`. ## 8. Dependencies and integration Upstream: M-FUNCTIONAL-02 (done). Downstream: M-TIME-03 `Async::retry_async` consumes `RetryState`, `RetrySpec`, `RetryError`, `RetryEveryError`, `AttemptOutcome` exactly as above (gate G1). Root integrates and commits. ## 9. Edge cases security and performance Saturating arithmetic near `time_point::max()`; multiplier 1e300 and `initial` near max; NaN/inf multiplier; negative durations; `max_attempts = UINT32_MAX` does not overflow counters; jitter on `d = 0`; deadline exactly equal to `at` counts as exceeded; no allocation in `RetryState`. ## 10. Acceptance criteria 1. `RetryState.cpp` tests: `retry_state_rejects_invalid_specs` (one check per `RetryConfigError`), `retry_state_exact_three_attempts_default`, `retry_state_deadline_at_admission_prevents_first_attempt`, `retry_state_backoff_overshooting_deadline_stops`, `retry_state_no_deadline_explicit_marker`, `retry_state_backoff_saturates_without_overflow`, `retry_state_full_equal_jitter_bounds_and_seed_reproducibility` (seeded `mt19937_64{42}`; bounds + same-seed equality, not exact values), `retry_state_default_engine_jitter_in_bounds`, `retry_state_stop_prevents_next_attempt`, `retry_state_permanent_failure_stops`, `retry_state_saturating_add_near_max` — all pass. 2. `RetryBlocking.cpp` tests (fake clock struct local to the test, no Time include, zero real sleeps): `retry_blocking_fake_clock_exact_waits_and_attempts`, `retry_blocking_zero_attempts_config_error_no_call`, `retry_blocking_expired_deadline_no_call_no_success`, `retry_blocking_last_error_and_attempt_count`, `retry_blocking_stop_during_sleep_no_extra_attempt`, `retry_blocking_permanent_failure_single_attempt`, `retry_blocking_move_only_value`, `legacy_retry_zero_attempts_behavior_pinned` (characterizes the 1.x defect; comment says it is recorded for Wave C) — all pass. 3. Existing `Retry`, `RetryJitter`, `AsyncPolicy` tests pass unchanged. 4. `RetryState.hpp` contains no `` and no `Void/` include; `src/Functional/module.cmake` unchanged. 5. `-DVOID_WARNINGS_AS_ERRORS=ON` clean. ## 11. Verification commands and evidence Run from your worktree root (`$PWD`). `dev` must run with the sandbox disabled (the nix fetcher lock fails inside it). Expected: build exit 0, filtered tests all pass, ctest 2/2. ```sh dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3 -G Ninja -DVOID_ENABLED_MODULES="Functional;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3 --parallel 8 && /tmp/void-w11-fn3/tests/VoidTests --filter "^(RetryState|RetryBlocking|Retry|RetryJitter)\." && ctest --test-dir /tmp/void-w11-fn3 --output-on-failure --timeout 60' dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3-res -G Ninja -DVOID_ENABLED_MODULES="ResilienceAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3-res --parallel 8 && /tmp/void-w11-fn3-res/tests/VoidTests --filter "^(AsyncPolicy|Retry|RetryJitter|RetryState|RetryBlocking)\."' dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Functional;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3-asan --parallel 8 && /tmp/void-w11-fn3-asan/tests/VoidTests --filter "^(RetryState|RetryBlocking|Retry|RetryJitter)\."' rg -n "#include |Void/" include/Void/Functional/RetryState.hpp # expect no output ``` If a cmake option name differs (e.g. sanitizer flags), discover it in `CMakeLists.txt`/`cmake/Capabilities.cmake` and report the exact command used. ## 12. Constraints and stop conditions Do not edit outside write scope, weaken assertions, disable warnings, or change 1.x behavior. Stop and report BLOCKED if: the interface cannot compile as specified; a 1.x test needs changing; a build failure originates outside your files; the sanitizer option names cannot be found. ## 13. Authorization and decisions Root decisions D-034, D-038 under user decisions D-027/D-029/D-031. Implementation of the listed files only; no commits, pushes or other side effects. ## 14. Return format Return task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance criterion; commands with cwd/results (test counts); checks not run; residual risks; integration notes (worktree path). Do not spawn children.