diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 385807c..d159a0b 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -152,7 +152,7 @@ Decisions: D-033..D-036. | --- | --- | --- | --- | --- | | W11-PLAN | Architecture/task plan + REV1 addendum | [W11-PLAN](tasks/W11-PLAN.md), [output](tasks/W11-PLAN-OUTPUT.md), [REV1](tasks/W11-PLAN-REV1-OUTPUT.md) | DONE | PREFLIGHT 1 CHANGES_REQUIRED ([findings](tasks/W11-PREFLIGHT-OUTPUT.md)); resolved in REV1/D-038; PREFLIGHT 2 running | | M-FUNCTIONAL-03 | Pure retry decisions + named blocking adapter (A1) | [spec](tasks/M-FUNCTIONAL-03.md) | VERIFIED (`26edf65`) | Review W11-REVIEW-A1 READY (P3 1/2/5 fixed by root); ResilienceAsync subset 475 (472 ✔, 3 ⊘), filtered 43/43, ctest 2/2, TSan 40/40 0 races, ASan+UBSan 40/40, `-Werror` syntax checks clean | -| M-TIME-03 | Injected-deadline domains: TimerQueue + clock saturation (B1); `retry_async` (B1b) | [spec](tasks/M-TIME-03.md), [B1b](tasks/M-TIME-03-B1b.md) | B1 VERIFIED; B1b IN REVIEW (root-verified 697: 694 ✔ 3 ⊘, TSan 33/33) | B1: review W11-REVIEW-B1 F1–F3 fixed by root; Runtime;SystemAsync;ResilienceAsync 681 (678 ✔, 3 ⊘), TSan 28/28 ×3, ASan 468 ✔, post-fix 18/18 + TSan 15/15 | +| M-TIME-03 | Injected-deadline domains: TimerQueue + clock saturation (B1); `retry_async` (B1b) | [spec](tasks/M-TIME-03.md), [B1b](tasks/M-TIME-03-B1b.md) | VERIFIED | B1b: review W11-REVIEW-B1b READY (deviation accepted, spec amended, doc P3-3 fixed); root 697 (694 ✔, 3 ⊘), TSan 33/33, reviewer ASan 33/33 + TSan 5×15/15 | B1: review W11-REVIEW-B1 F1–F3 fixed by root; Runtime;SystemAsync;ResilienceAsync 681 (678 ✔, 3 ⊘), TSan 28/28 ×3, ASan 468 ✔, post-fix 18/18 + TSan 15/15 | | M-ASYNC-04 | ThreadExecutor, FuturePool, AsyncChannel, bounded ParallelFor (A2) + root fixes: pre-existing `spawn()` eager-frame race in `Executor.hpp`, ParallelFor runner last-reference ownership | [spec](tasks/M-ASYNC-04.md) | IN REVIEW | Implementer: 109/109, TSan 46/46, ASan 46/46; root: TSan 6/6 runs 47/47 after fixes, spawn regression test added | | M-ASYNC-05 | EventBus/Observable snapshot dispatch, joined subscriptions (A3) | [spec](tasks/M-ASYNC-05.md) | READY (after M-ASYNC-04 commit) | — | | S-IO-03 | Bounded positional file workers, sync, active-cancel, shutdown core, D1 fixes (B2) | [spec](tasks/S-IO-03.md) | IN REVIEW | Implementer: IO 37/37, TSan 37/37 + 30 loops, ASan clean, downstream 883 ✔; root: full 55-module `-Werror` 1,574 (1,570 ✔, 4 ⊘), ctest 2/2, IO-users TSan 627 (624 ✔, 3 ⊘), 0 TSan warnings | @@ -201,3 +201,4 @@ specs' observed baselines (D-035); not separately scheduled. | VL-CRYPTO-02 | P1 | `pbkdf2_hmac_sha256(password, salt, iterations, out_len)` (RFC 8018 §5.2) on the builtin HMAC path; RFC 7914 §11 vectors; bounded iterations/output | PLANNED | | VL-NET-02 | P1 (blocks Forge production email) | Public TLS client stream (TCP+TLS, CA + hostname verification, STARTTLS upgrade) + minimal SMTP submission client (EHLO, STARTTLS-required or implicit TLS, AUTH PLAIN over TLS only, MAIL/RCPT/DATA with dot-stuffing, bounded size, deadlines) | PLANNED | | VL-TEXT-01 | P2 | RFC 4648 base32 + Crockford base32 encode/decode | PLANNED | +| X-QA-04 | AsyncRetry follow-ups from W11-REVIEW-B1b: race test only exercises the late-stop interleaving (add handshake/alternation); add direct checks of `detail::retry_backoff_stop_reason`; add a throwing-classifier test | W11-REVIEW-B1b P3-1/2/4 | PLANNED | diff --git a/docs/agent-workflow/tasks/M-TIME-03-B1b.md b/docs/agent-workflow/tasks/M-TIME-03-B1b.md index f2b7444..93619fe 100644 --- a/docs/agent-workflow/tasks/M-TIME-03-B1b.md +++ b/docs/agent-workflow/tasks/M-TIME-03-B1b.md @@ -50,8 +50,10 @@ MANDATORY semantics: `Coro::Task>` (co_await it). Success → return `T` (also when stop was requested during the attempt). Failure → `next(now, classify(error), stop_requested)`. - On `wait_until(at)`: `co_await timers.sleep_until(at, OperationOptions{options.stop, options.deadline})`. - Then ALWAYS call `resume(now, options.stop.stop_requested())` — it re-checks stop itself, which covers - the TimerQueue choice where a late stop yields `{}`. Sleep result mapping: `{}` → resume; + After a `{}` sleep, ALWAYS call `resume(now, options.stop.stop_requested())` — it re-checks stop itself, + which covers the TimerQueue choice where a late stop yields `{}`. Any sleep error ends the retry without + calling `resume()` (amended after W11-REVIEW-B1b: resuming after `stopped`/`overloaded` would start + attempts with no wait). Sleep result mapping: `{}` → resume; `cancelled` → stop with `stop_requested`; `timeout` → stop with `deadline_exceeded`; `stopped` (queue closed) → stop with `stop_requested` (documented: queue closure aborts the retry; no further attempt); `overloaded` → stop with `stop_requested` and document (no silent busy retry). diff --git a/include/Void/Async/Retry.hpp b/include/Void/Async/Retry.hpp new file mode 100644 index 0000000..eebcb9b --- /dev/null +++ b/include/Void/Async/Retry.hpp @@ -0,0 +1,220 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +// ── retry_async ─────────────────────────────────────────────────────────────── +// Asynchronous adapter over `Void::Retry::RetryState` (C-03/C-04). Attempts run +// on the coroutine; every backoff between attempts is a `TimerQueue` sleep in +// the queue's injected clock domain. +// +// * "Now" is always `timers.clock().now()`, re-read after every suspension. The +// host clock is never consulted and no thread ever sleeps. A backoff ends +// only when the queue's owner advances the injected clock (or real time +// passes, for a system clock), calls `poll_expired()` and then drains the +// queue's completion executor. Even a zero-length backoff needs that poll, so +// the adapter never spins. +// * The effective deadline is min(start + spec.budget, options.deadline), where +// `start` is the clock reading taken when the (lazy) task first runs and +// `options.deadline` is an absolute admission deadline in the same domain. +// * `options.stop` is checked before every attempt (RetryState::begin/resume), +// after every failed attempt (RetryState::next), and wakes a pending backoff. +// No attempt starts after a stop decision. An attempt that succeeds is +// returned even if the stop was requested while it ran. +// +// Results (exactly one): +// success the value of the successful attempt +// invalid spec RetryError{reason = none, attempts = 0, last_error = {}, +// config = error}; `fn` is never called +// RetryState stop RetryError{reason, attempts, last_error} with reason +// attempts_exhausted, deadline_exceeded, not_retryable or +// stop_requested +// failed backoff a backoff sleep that does not complete normally ends the +// retry at once, with no further attempt: +// cancelled (stop won the race with the timer) -> stop_requested +// timeout (options.deadline had already passed when the +// backoff was admitted) -> deadline_exceeded +// stopped (the queue was closed before or during the +// backoff: queue closure aborts the retry) +// -> stop_requested +// overloaded (the queue already holds max_timers timers; +// reported rather than retried without a wait) +// -> stop_requested +// any other sleep error -> stop_requested +// A backoff that completes normally always goes through RetryState::resume +// with a fresh clock reading and stop state, so a stop that lands after the +// timer fired (the sleep then reports success) or a deadline that passed +// before the poll still prevents the next attempt. `attempts` counts started +// attempts; `last_error` holds the most recent attempt error and is empty iff +// no attempt ran. A closed queue does not prevent the first attempt (it needs +// no timer); it ends the retry at the first backoff. +// +// Callable: `fn` is invoked as an lvalue and returns `std::expected` or +// `Coro::Task>` (awaited). `T` may be void or move-only, +// `E` and `F` may be move-only. `classify` is called as AttemptOutcome(const E&). +// An exception thrown by `fn`, by its task or by `classify` propagates out of +// the retry task (rethrown where the retry task is awaited); no further +// attempt is made, and no backoff timer is in flight while an attempt runs. +// `Task::run()` / `sync_wait()` are valid only when the retry finishes without +// suspending in a backoff; otherwise co_await the task and drive the timer +// queue (poll_expired) and its executor until it completes. +// +// Threading: the first attempt runs on the thread that starts the task; every +// later attempt runs where the backoff sleep resumes, i.e. on the completion +// lane of `timers.executor()`. The RetryState is touched only by the coroutine. +// +// Lifetime: the task owns `spec`, `fn`, `options`, `classify` and `urbg` by +// value. `timers`, its completion executor and its clock must outlive the task. +// The TimerQueue sleep rules apply to a retry task suspended in a backoff: it +// may be destroyed only while that backoff's timer is still pending and the +// destruction is serialized with poll, close and stop (the timer is then +// cancelled); once the timer has been settled (fired, cancelled by stop, or +// closed) the task must stay alive until its posted resume has run. Shutdown +// order: `timers.close()`, drain the completion executor, then destroy the +// task. While an attempt's own task is suspended, that task's rules apply. + +namespace Void::Async +{ + +namespace detail +{ + +template +struct retry_attempt_traits; + +template +struct retry_attempt_traits> { + using value_type = T; + using error_type = E; + static constexpr bool is_task = false; +}; + +template +struct retry_attempt_traits>> { + using value_type = T; + using error_type = E; + static constexpr bool is_task = true; +}; + +template +using retry_attempt_traits_t = + retry_attempt_traits>>; + +template +using retry_async_result_t = std::expected< + typename retry_attempt_traits_t::value_type, + Void::Retry::RetryError::error_type>>; + +// Reason a retry stops with when its backoff sleep did not complete normally. +[[nodiscard]] inline Void::Retry::RetryStopReason + retry_backoff_stop_reason(const Void::Result::Error& error) noexcept +{ + const Void::Result::ErrorCode code = error.code(); + if (code.domain == Void::Result::kAsyncErrorDomain && + code.value == static_cast(AsyncErrorCode::timeout)) { + return Void::Retry::RetryStopReason::deadline_exceeded; + } + // cancelled, stopped (queue closed), overloaded, or anything unexpected: + // terminal, never a retry without a wait. + return Void::Retry::RetryStopReason::stop_requested; +} + +} // namespace detail + +template + requires std::invocable +[[nodiscard]] auto retry_async(Void::Retry::RetrySpec spec, + F fn, + TimerQueue& timers, + OperationOptions options = {}, + Classify classify = {}, + URBG urbg = Void::Retry::detail::seeded_engine()) + -> Coro::Task> +{ + using Traits = detail::retry_attempt_traits_t; + using T = typename Traits::value_type; + using E = typename Traits::error_type; + using Error = Void::Retry::RetryError; + using Out = std::expected; + using Void::Retry::RetryAction; + using Void::Retry::RetryDecision; + using Void::Retry::RetryStopReason; + static_assert(std::uniform_random_bit_generator, + "URBG must satisfy std::uniform_random_bit_generator"); + static_assert( + std::is_invocable_r_v, + "Classify must be callable as AttemptOutcome(const E&)"); + + if (const auto valid = Void::Retry::validate(spec); !valid) { + co_return Out(std::unexpect, + Error{RetryStopReason::none, 0, std::nullopt, valid.error()}); + } + + const Void::Time::MonotonicClock& clock = timers.clock(); + const Void::Retry::SteadyTimePoint start = clock.now(); + auto created = Void::Retry::RetryState::create( + spec, start, std::move(urbg), options.deadline); + if (!created.has_value()) { // unreachable after validate() + co_return Out(std::unexpect, + Error{RetryStopReason::none, 0, std::nullopt, created.error()}); + } + Void::Retry::RetryState& state = *created; + + std::optional last_error; + RetryDecision decision = state.begin(start, options.stop.stop_requested()); + for (;;) { + if (decision.action == RetryAction::attempt) { + std::optional> result; + if constexpr (Traits::is_task) { + result.emplace(co_await std::invoke(fn)); + } else { + result.emplace(std::invoke(fn)); + } + if (result->has_value()) { + (void)state.succeed(); + if constexpr (std::is_void_v) { + co_return Out{}; + } else { + co_return Out(std::in_place, std::move(**result)); + } + } + last_error.emplace(std::move(*result).error()); + result.reset(); + const Void::Retry::AttemptOutcome outcome = + std::invoke(classify, std::as_const(*last_error)); + decision = state.next(clock.now(), outcome, options.stop.stop_requested()); + } else if (decision.action == RetryAction::wait_until) { + OperationOptions sleep_options{options.stop, options.deadline}; + auto slept = co_await timers.sleep_until(decision.at, std::move(sleep_options)); + if (!slept.has_value()) { + co_return Out(std::unexpect, + Error{detail::retry_backoff_stop_reason(slept.error()), + state.attempts_started(), + std::move(last_error), + std::nullopt}); + } + decision = state.resume(clock.now(), options.stop.stop_requested()); + } else { + co_return Out(std::unexpect, + Error{decision.reason, + decision.attempts_started, + std::move(last_error), + std::nullopt}); + } + } +} + +} // namespace Void::Async diff --git a/tests/standalone/Async/AsyncRetry.cpp b/tests/standalone/Async/AsyncRetry.cpp new file mode 100644 index 0000000..0bf4b19 --- /dev/null +++ b/tests/standalone/Async/AsyncRetry.cpp @@ -0,0 +1,1183 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// retry_async is driven only by an injected ManualClock, explicit +// TimerQueue::poll_expired() calls and an explicitly drained ManualExecutor: +// nothing here sleeps on a thread or reads the host clock for retry timing. + +namespace +{ + +using namespace Void::Async; +using namespace std::chrono_literals; +namespace R = Void::Retry; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; +using TimePoint = Void::Time::MonotonicClock::time_point; +using Void::Time::ManualClock; +using Engine = std::mt19937_64; +using Ns = std::chrono::nanoseconds; + +using IntOut = std::expected>; + +TimePoint at(Ns since_epoch) +{ + return TimePoint{std::chrono::duration_cast(since_epoch)}; +} + +void advance_clock(ManualClock& clock, Ns delta) +{ + require(clock.advance(delta).has_value()); +} + +std::unique_ptr make_queue(Executor& exec, + const Void::Time::MonotonicClock& clock, + std::size_t max_timers = 1024) +{ + auto created = TimerQueue::create(exec, clock, TimerQueueOptions{.max_timers = max_timers}); + require(created.has_value()); + return std::move(*created); +} + +// Assertion-free variant for loops: the runner retains only the first 1,000 +// assertions per test (X-QA-02), so loops count failures instead. +std::unique_ptr try_make_queue(Executor& exec, const Void::Time::MonotonicClock& clock) +{ + auto created = TimerQueue::create(exec, clock, TimerQueueOptions{}); + return created.has_value() ? std::move(*created) : nullptr; +} + +// Constant backoff of `delay`, no jitter, no time budget. +R::RetrySpec constant_spec(Ns delay, 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 = std::nullopt; + return spec; +} + +template +struct RetryProbe { + int resumes{0}; + bool threw{false}; + std::string what{}; + std::optional result{}; +}; + +// Awaits an already-created retry task and records its single outcome +// (value, error or exception). +template +Void::Coro::Task collect(Void::Coro::Task retry, RetryProbe* probe) +{ + try { + auto res = co_await retry; + probe->result.emplace(std::move(res)); + } catch (const std::exception& e) { + probe->threw = true; + probe->what = e.what(); + } + ++probe->resumes; +} + +void start(Void::Coro::Task& task) +{ + task.handle().resume(); +} + +// Checks a single failed outcome: reason, started attempts, no config error. +template +void expect_stop(const RetryProbe>>& probe, + R::RetryStopReason reason, + std::uint32_t attempts, + std::source_location loc = std::source_location::current()) +{ + expect_eq(probe.resumes, 1, loc); + expect(!probe.threw, loc); + require(probe.result.has_value(), loc); + require(!probe.result->has_value(), loc); + const auto& error = probe.result->error(); + expect_eq(static_cast(error.reason), static_cast(reason), loc); + expect_eq(error.attempts, attempts, loc); + expect(!error.config.has_value(), loc); +} + +void expect_last_error(const RetryProbe& probe, + const std::string& expected, + std::source_location loc = std::source_location::current()) +{ + require(probe.result.has_value() && !probe.result->has_value(), loc); + const auto& last = probe.result->error().last_error; + require(last.has_value(), loc); + expect_eq(*last, expected, loc); +} + +// Fails with "e" on attempt n until attempt `succeed_on`, which returns +// `value`; records the injected time of every attempt. +struct AttemptLog { + const Void::Time::MonotonicClock* clock{nullptr}; + std::vector times{}; + + [[nodiscard]] std::size_t calls() const noexcept { return times.size(); } +}; + +auto failing_until(AttemptLog* log, std::size_t succeed_on, int value = 42) +{ + return [log, succeed_on, value]() -> std::expected { + log->times.push_back(log->clock->now()); + if (succeed_on == 0 || log->calls() < succeed_on) { + return std::unexpected{"e" + std::to_string(log->calls())}; + } + return value; + }; +} + +// Returns `base` for the first `reads_before_jump` reads, then `jumped`. +class JumpingClock final : public Void::Time::MonotonicClock +{ +public: + JumpingClock(time_point base, time_point jumped, int reads_before_jump) noexcept + : base_(base) + , jumped_(jumped) + , remaining_(reads_before_jump) + { + } + + [[nodiscard]] time_point now() const noexcept override + { + return remaining_.fetch_sub(1, std::memory_order_acq_rel) > 0 ? base_ : jumped_; + } + +private: + time_point base_; + time_point jumped_; + mutable std::atomic remaining_; +}; + +// Async attempt: suspends on the queue for 5ms, then fails until attempt 2. +Void::Coro::Task> sleeping_attempt(TimerQueue* q, AttemptLog* log) +{ + log->times.push_back(q->clock().now()); + auto slept = co_await q->sleep_for(5ms); + if (!slept.has_value()) { + co_return std::unexpected{std::string{"attempt sleep failed"}}; + } + if (log->calls() < 2) { + co_return std::unexpected{"e" + std::to_string(log->calls())}; + } + co_return 7; +} + +// Async attempt that fails once and throws on its second run. +Void::Coro::Task> throwing_attempt(int* calls) +{ + ++*calls; + if (*calls >= 2) { + throw std::runtime_error{"attempt threw"}; + } + co_return std::unexpected{std::string{"e1"}}; +} + +// "fatal" is permanent; every other error is worth retrying. +struct FatalClassifier { + [[nodiscard]] R::AttemptOutcome operator()(const std::string& e) const noexcept + { + return e == "fatal" ? R::AttemptOutcome::permanent_failure + : R::AttemptOutcome::retryable_failure; + } +}; + +struct ManualNow { + const ManualClock* clock{nullptr}; + + [[nodiscard]] R::SteadyTimePoint operator()() const noexcept { return clock->now(); } +}; + +struct ManualAdvanceSleep { + ManualClock* clock{nullptr}; + + bool operator()(Ns wait, std::stop_token) const { return clock->advance(wait).has_value(); } +}; + +} // namespace + +// ── scheduling in the injected domain ───────────────────────────────────────── + +Void::Testing::Test async_retry_manual_clock_attempts_only_after_advance_and_poll() +{ + // The host steady clock is far past every manual-domain time used here. + require(std::chrono::steady_clock::now().time_since_epoch() > 100ms); + + ManualExecutor exec; + ManualClock clock; // epoch 0 + auto q = make_queue(exec, clock); + + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), failing_until(&log, 3), *q), &probe); + expect_eq(log.calls(), std::size_t{0}); // lazy: nothing runs before start + + // The first attempt runs when the task starts; the retry then waits on + // exactly one timer at now + backoff. + start(task); + expect_eq(log.calls(), std::size_t{1}); + expect(!task.done()); + expect_eq(q->active_timers(), std::size_t{1}); + require(q->next_deadline().has_value()); + expect(*q->next_deadline() == at(10ms)); + expect(exec.empty()); + + // Neither an early poll nor advancing without a poll starts an attempt. + expect_eq(q->poll_expired(), std::size_t{0}); + advance_clock(clock, 9ms); + expect_eq(q->poll_expired(), std::size_t{0}); + advance_clock(clock, 1ms); + expect_eq(exec.drain(), std::size_t{0}); + expect_eq(log.calls(), std::size_t{1}); + + // Advance + poll fires the backoff; the attempt runs only when the + // completion executor resumes the retry, never inline from poll. + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(log.calls(), std::size_t{1}); + expect(!exec.empty()); + expect_eq(exec.drain(), std::size_t{1}); + expect_eq(log.calls(), std::size_t{2}); + expect(!task.done()); + require(q->next_deadline().has_value()); + expect(*q->next_deadline() == at(20ms)); + + // Time passing well beyond the backoff still needs a poll. + advance_clock(clock, 15ms); // 25ms + expect_eq(exec.drain(), std::size_t{0}); + expect_eq(log.calls(), std::size_t{2}); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + expect_eq(probe.resumes, 1); + require(probe.result.has_value()); + require(probe.result->has_value()); + expect_eq(**probe.result, 42); + + // Each attempt ran at the injected time at which a poll observed expiry. + require(log.calls() == 3); + expect(log.times[0] == at(0ns)); + expect(log.times[1] == at(10ms)); + expect(log.times[2] == at(25ms)); + + // Nothing stays scheduled and nothing runs again. + expect_eq(q->active_timers(), std::size_t{0}); + advance_clock(clock, 1h); + expect_eq(q->poll_expired(), std::size_t{0}); + expect_eq(exec.drain(), std::size_t{0}); + expect_eq(probe.resumes, 1); + expect_eq(log.calls(), std::size_t{3}); +} + +Void::Testing::Test async_retry_total_deadline_expires_once() +{ + require(std::chrono::steady_clock::now().time_since_epoch() > 100ms); + + // Budget 25ms, backoff 10ms: attempts at 0, 10, 20; the wake-up at 30 + // would overshoot, so the retry stops at once without arming a timer. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + auto spec = constant_spec(10ms, 10); + spec.budget = Ns{25ms}; + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(spec, failing_until(&log, 0), *q), &probe); + start(task); + for (int i = 0; i < 2; ++i) { + advance_clock(clock, 10ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + } + expect(task.done()); + expect_eq(q->active_timers(), std::size_t{0}); + expect_stop(probe, R::RetryStopReason::deadline_exceeded, 3); + expect_last_error(probe, "e3"); + require(log.calls() == 3); + expect(log.times[2] == at(20ms)); + + advance_clock(clock, 1h); + expect_eq(q->poll_expired(), std::size_t{0}); + expect_eq(exec.drain(), std::size_t{0}); + expect_eq(probe.resumes, 1); + expect_eq(log.calls(), std::size_t{3}); + } + + // The deadline passes during the backoff: advancing past it plus one + // explicit poll ends the retry exactly once (resume() sees the deadline). + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + auto spec = constant_spec(10ms, 10); + spec.budget = Ns{25ms}; + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(spec, failing_until(&log, 0), *q), &probe); + start(task); + advance_clock(clock, 30ms); + expect_eq(exec.drain(), std::size_t{0}); + expect(!task.done()); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + expect_stop(probe, R::RetryStopReason::deadline_exceeded, 1); + expect_last_error(probe, "e1"); + expect_eq(log.calls(), std::size_t{1}); + expect_eq(q->poll_expired(), std::size_t{0}); + expect_eq(exec.drain(), std::size_t{0}); + expect_eq(probe.resumes, 1); + } + + // An admission deadline in OperationOptions is interpreted in the + // queue's manual domain: the host clock would call it long expired. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 10), + failing_until(&log, 0), + *q, + OperationOptions{.deadline = at(15ms)}), + &probe); + start(task); + expect_eq(log.calls(), std::size_t{1}); + expect(!task.done()); + advance_clock(clock, 10ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + expect_stop(probe, R::RetryStopReason::deadline_exceeded, 2); + expect_last_error(probe, "e2"); + expect_eq(q->active_timers(), std::size_t{0}); + } + + // A backoff whose admission finds options.deadline already passed is + // reported by the TimerQueue as timeout and mapped to deadline_exceeded. + // The clock returns 0 for the adapter's start and post-attempt reads and + // 50ms from the sleep's admission read onwards. + { + ManualExecutor exec; + JumpingClock clock{at(0ns), at(50ms), 2}; + auto q = make_queue(exec, clock); + int calls = 0; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 10), + [&calls]() -> std::expected { + ++calls; + return std::unexpected{std::string{"e1"}}; + }, + *q, + OperationOptions{.deadline = at(40ms)}), + &probe); + start(task); + expect(task.done()); + expect(exec.empty()); + expect_eq(q->active_timers(), std::size_t{0}); + expect_eq(calls, 1); + expect_stop(probe, R::RetryStopReason::deadline_exceeded, 1); + expect_last_error(probe, "e1"); + } +} + +// ── stop ────────────────────────────────────────────────────────────────────── + +Void::Testing::Test async_retry_stop_during_backoff_no_further_attempt() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + + std::stop_source source; + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + failing_until(&log, 0), + *q, + OperationOptions{.stop = source.get_token()}), + &probe); + start(task); + expect_eq(log.calls(), std::size_t{1}); + expect_eq(q->active_timers(), std::size_t{1}); + + // The stop cancels the backoff timer at once but resumes the retry only + // through the completion executor. + expect(source.request_stop()); + expect_eq(q->active_timers(), std::size_t{0}); + expect(!task.done()); + expect_eq(probe.resumes, 0); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + expect_stop(probe, R::RetryStopReason::stop_requested, 1); + expect_last_error(probe, "e1"); + expect_eq(log.calls(), std::size_t{1}); + + // The cancelled backoff never fires and no attempt ever follows. + advance_clock(clock, 1h); + expect_eq(q->poll_expired(), std::size_t{0}); + expect_eq(exec.drain(), std::size_t{0}); + expect_eq(probe.resumes, 1); + expect_eq(log.calls(), std::size_t{1}); +} + +Void::Testing::Test async_retry_success_after_stop_preserved() +{ + // Stop requested during the first attempt, which succeeds. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + std::stop_source source; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + [&source]() -> std::expected { + source.request_stop(); + return 5; + }, + *q, + OperationOptions{.stop = source.get_token()}), + &probe); + start(task); + expect(task.done()); + require(probe.result.has_value()); + require(probe.result->has_value()); + expect_eq(**probe.result, 5); + } + + // Stop requested during a later attempt, which succeeds. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + std::stop_source source; + int calls = 0; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + [&source, &calls]() -> std::expected { + if (++calls < 2) { + return std::unexpected{std::string{"e1"}}; + } + source.request_stop(); + return 9; + }, + *q, + OperationOptions{.stop = source.get_token()}), + &probe); + start(task); + advance_clock(clock, 10ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + expect_eq(calls, 2); + require(probe.result.has_value()); + require(probe.result->has_value()); + expect_eq(**probe.result, 9); + expect_eq(q->active_timers(), std::size_t{0}); + } + + // A void success is preserved the same way. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + std::stop_source source; + RetryProbe>> probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + [&source]() -> std::expected { + source.request_stop(); + return {}; + }, + *q, + OperationOptions{.stop = source.get_token()}), + &probe); + start(task); + expect(task.done()); + require(probe.result.has_value()); + expect(probe.result->has_value()); + } + + // Contrast: a failure under a stop request ends the retry without a + // backoff and without a further attempt. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + std::stop_source source; + int calls = 0; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + [&source, &calls]() -> std::expected { + ++calls; + source.request_stop(); + return std::unexpected{std::string{"e1"}}; + }, + *q, + OperationOptions{.stop = source.get_token()}), + &probe); + start(task); + expect(task.done()); + expect_eq(q->active_timers(), std::size_t{0}); + expect(exec.empty()); + expect_eq(calls, 1); + expect_stop(probe, R::RetryStopReason::stop_requested, 1); + expect_last_error(probe, "e1"); + } +} + +Void::Testing::Test async_retry_late_stop_after_timer_fired_no_further_attempt() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + + std::stop_source source; + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + failing_until(&log, 0), + *q, + OperationOptions{.stop = source.get_token()}), + &probe); + start(task); + advance_clock(clock, 10ms); + // The timer fires first; its resume is posted but has not run yet. + expect_eq(q->poll_expired(), std::size_t{1}); + expect(!exec.empty()); + // The stop loses the race with the timer, so the sleep itself reports + // success; resume() still sees the stop and starts no attempt. + expect(source.request_stop()); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + expect_stop(probe, R::RetryStopReason::stop_requested, 1); + expect_last_error(probe, "e1"); + expect_eq(log.calls(), std::size_t{1}); + expect_eq(q->active_timers(), std::size_t{0}); + advance_clock(clock, 1h); + expect_eq(q->poll_expired(), std::size_t{0}); + expect_eq(exec.drain(), std::size_t{0}); + expect_eq(log.calls(), std::size_t{1}); +} + +Void::Testing::Test async_retry_stop_vs_poll_race_single_result_tsan() +{ + constexpr int kIterations = 200; + int failures = 0; + for (int i = 0; i < kIterations; ++i) { + ManualExecutor exec; + ManualClock clock; + auto q = try_make_queue(exec, clock); + if (q == nullptr) { + ++failures; + continue; + } + std::stop_source source; + int calls = 0; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + [&calls]() -> std::expected { + ++calls; + return std::unexpected{std::string{"e"}}; + }, + *q, + OperationOptions{.stop = source.get_token()}), + &probe); + task.handle().resume(); + if (!clock.advance(10ms).has_value()) { + ++failures; + } + + std::atomic go{false}; + std::thread stopper([&source, &go] { + while (!go.load(std::memory_order_acquire)) { + std::this_thread::yield(); + } + source.request_stop(); + }); + go.store(true, std::memory_order_release); + (void)q->poll_expired(); + stopper.join(); + + // Whichever side won, exactly one resume is posted and the stop is + // visible to resume(): one result, no second attempt. + const std::size_t resumed = exec.drain(); + const bool ok = resumed == 1 && task.done() && calls == 1 && probe.resumes == 1 && + probe.result.has_value() && !probe.result->has_value() && + probe.result->error().reason == R::RetryStopReason::stop_requested && + probe.result->error().attempts == 1 && q->active_timers() == 0; + if (!ok) { + ++failures; + } + } + expect_eq(failures, 0); +} + +// ── attempts that never start ───────────────────────────────────────────────── + +Void::Testing::Test async_retry_zero_attempts_no_call() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + + // An invalid spec is a config error, never a success, and fn never runs. + { + int calls = 0; + auto spec = constant_spec(10ms, 0); + RetryProbe probe; + auto task = collect(retry_async(spec, + [&calls]() -> std::expected { + ++calls; + return 1; + }, + *q), + &probe); + start(task); + expect(task.done()); + expect_eq(calls, 0); + expect_eq(probe.resumes, 1); + require(probe.result.has_value()); + require(!probe.result->has_value()); + const auto& error = probe.result->error(); + expect_eq(static_cast(error.reason), static_cast(R::RetryStopReason::none)); + expect_eq(error.attempts, std::uint32_t{0}); + expect(!error.last_error.has_value()); + require(error.config.has_value()); + expect(*error.config == R::RetryConfigError::zero_attempts); + } + { + int calls = 0; + auto spec = constant_spec(10ms, 3); + spec.backoff.multiplier = 0.5; + RetryProbe probe; + auto task = collect(retry_async(spec, + [&calls]() -> std::expected { + ++calls; + return 1; + }, + *q), + &probe); + start(task); + expect_eq(calls, 0); + require(probe.result.has_value() && !probe.result->has_value()); + expect(probe.result->error().config == std::optional{R::RetryConfigError::multiplier_below_one}); + expect_eq(probe.result->error().attempts, std::uint32_t{0}); + } + + // Stop requested before the first attempt. + { + std::stop_source source; + source.request_stop(); + int calls = 0; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 3), + [&calls]() -> std::expected { + ++calls; + return 1; + }, + *q, + OperationOptions{.stop = source.get_token()}), + &probe); + start(task); + expect(task.done()); + expect_eq(calls, 0); + expect_stop(probe, R::RetryStopReason::stop_requested, 0); + expect(!probe.result->error().last_error.has_value()); + } + + // Admission deadline already passed in the manual domain. + { + advance_clock(clock, 10ms); + int calls = 0; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 3), + [&calls]() -> std::expected { + ++calls; + return 1; + }, + *q, + OperationOptions{.deadline = at(5ms)}), + &probe); + start(task); + expect(task.done()); + expect_eq(calls, 0); + expect_stop(probe, R::RetryStopReason::deadline_exceeded, 0); + expect(!probe.result->error().last_error.has_value()); + } + + expect_eq(q->active_timers(), std::size_t{0}); + expect(exec.empty()); +} + +// ── callable shapes ─────────────────────────────────────────────────────────── + +Void::Testing::Test async_retry_task_returning_callable() +{ + // Each attempt is itself a task that suspends on the queue. The backoff + // starts from the time the attempt finished, not when it started. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + AttemptLog log{&clock}; + TimerQueue* qp = q.get(); + RetryProbe probe; + auto task = collect( + retry_async(constant_spec(10ms, 5), [qp, &log] { return sleeping_attempt(qp, &log); }, *q), + &probe); + start(task); + expect_eq(log.calls(), std::size_t{1}); + expect(!task.done()); + require(q->next_deadline().has_value()); + expect(*q->next_deadline() == at(5ms)); // the attempt's own sleep + + advance_clock(clock, 5ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); // attempt 1 fails at 5ms + expect_eq(log.calls(), std::size_t{1}); + require(q->next_deadline().has_value()); + expect(*q->next_deadline() == at(15ms)); // backoff from 5ms + + advance_clock(clock, 10ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); // attempt 2 starts, sleeps + expect_eq(log.calls(), std::size_t{2}); + expect(!task.done()); + + advance_clock(clock, 5ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + require(probe.result.has_value()); + require(probe.result->has_value()); + expect_eq(**probe.result, 7); + require(log.calls() == 2); + expect(log.times[0] == at(0ns)); + expect(log.times[1] == at(15ms)); + expect_eq(q->active_timers(), std::size_t{0}); + } + + // An exception from an attempt task propagates out of the retry task; + // nothing is retried and no timer is left behind. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + int calls = 0; + RetryProbe probe; + auto task = collect( + retry_async(constant_spec(10ms, 5), [&calls] { return throwing_attempt(&calls); }, *q), + &probe); + start(task); + expect_eq(calls, 1); + advance_clock(clock, 10ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + expect_eq(calls, 2); + expect_eq(probe.resumes, 1); + expect(probe.threw); + expect_eq(probe.what, std::string{"attempt threw"}); + expect(!probe.result.has_value()); + expect_eq(q->active_timers(), std::size_t{0}); + advance_clock(clock, 1h); + expect_eq(q->poll_expired(), std::size_t{0}); + expect_eq(exec.drain(), std::size_t{0}); + expect_eq(calls, 2); + } + + // The same holds for a plain callable that throws. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + int calls = 0; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + [&calls]() -> std::expected { + ++calls; + throw std::runtime_error{"plain threw"}; + }, + *q), + &probe); + start(task); + expect(task.done()); + expect_eq(calls, 1); + expect(probe.threw); + expect_eq(probe.what, std::string{"plain threw"}); + expect_eq(q->active_timers(), std::size_t{0}); + } +} + +Void::Testing::Test async_retry_move_only_value() +{ + // Move-only value and move-only callable (invoked as an lvalue). + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + auto counter = std::make_unique(0); + using Out = std::expected, R::RetryError>; + RetryProbe probe; + auto task = collect( + retry_async(constant_spec(10ms, 5), + [counter = std::move(counter)]() mutable + -> std::expected, int> { + if (++*counter < 2) { + return std::unexpected{*counter}; + } + return std::make_unique(42); + }, + *q), + &probe); + start(task); + advance_clock(clock, 10ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + require(probe.result.has_value()); + require(probe.result->has_value()); + std::unique_ptr taken = std::move(**probe.result); + require(taken != nullptr); + expect_eq(*taken, 42); + } + + // Move-only error type: the most recent one is kept as last_error. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + int calls = 0; + using Out = std::expected>>; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 3), + [&calls]() -> std::expected> { + return std::unexpected{std::make_unique( + "e" + std::to_string(++calls))}; + }, + *q), + &probe); + start(task); + for (int i = 0; i < 2; ++i) { + advance_clock(clock, 10ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + } + expect(task.done()); + expect_eq(calls, 3); + expect_stop(probe, R::RetryStopReason::attempts_exhausted, 3); + const auto& last = probe.result->error().last_error; + require(last.has_value() && *last != nullptr); + expect_eq(**last, std::string{"e3"}); + } +} + +Void::Testing::Test async_retry_classifier_permanent_failure_stops() +{ + // Permanent on the first attempt: no backoff is armed. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + int calls = 0; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + [&calls]() -> std::expected { + ++calls; + return std::unexpected{std::string{"fatal"}}; + }, + *q, + {}, + FatalClassifier{}), + &probe); + start(task); + expect(task.done()); + expect(exec.empty()); + expect_eq(q->active_timers(), std::size_t{0}); + expect_eq(calls, 1); + expect_stop(probe, R::RetryStopReason::not_retryable, 1); + expect_last_error(probe, "fatal"); + } + + // Retryable first, permanent on the retry. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + int calls = 0; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + [&calls]() -> std::expected { + return std::unexpected{std::string{++calls < 2 ? "e1" : "fatal"}}; + }, + *q, + {}, + FatalClassifier{}), + &probe); + start(task); + expect_eq(q->active_timers(), std::size_t{1}); + advance_clock(clock, 10ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + expect_eq(calls, 2); + expect_stop(probe, R::RetryStopReason::not_retryable, 2); + expect_last_error(probe, "fatal"); + expect_eq(q->active_timers(), std::size_t{0}); + } +} + +// ── queue availability ──────────────────────────────────────────────────────── + +Void::Testing::Test async_retry_queue_closed_during_backoff_stops() +{ + // Closing the queue settles the pending backoff `stopped`; the retry ends + // with stop_requested and makes no further attempt. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), failing_until(&log, 0), *q), &probe); + start(task); + expect_eq(q->active_timers(), std::size_t{1}); + q->close(); + expect(!task.done()); + expect_eq(probe.resumes, 0); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + expect_stop(probe, R::RetryStopReason::stop_requested, 1); + expect_last_error(probe, "e1"); + advance_clock(clock, 1h); + expect_eq(q->poll_expired(), std::size_t{0}); + expect_eq(exec.drain(), std::size_t{0}); + expect_eq(log.calls(), std::size_t{1}); + } + + // A queue closed before the retry starts: the first attempt needs no + // timer and runs; the first backoff is rejected without suspending. + { + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + q->close(); + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), failing_until(&log, 0), *q), &probe); + start(task); + expect(task.done()); + expect(exec.empty()); + expect_eq(log.calls(), std::size_t{1}); + expect_stop(probe, R::RetryStopReason::stop_requested, 1); + expect_last_error(probe, "e1"); + } +} + +Void::Testing::Test async_retry_timer_overloaded_stops_without_busy_retry() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock, 1); + auto occupier = q->schedule_at(at(1h), [](TimerEvent) noexcept {}); + require(occupier.has_value()); + + // The backoff cannot be admitted: the retry ends with stop_requested + // instead of retrying without a wait. + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(0ns, 50), failing_until(&log, 0), *q), &probe); + start(task); + expect(task.done()); + expect(exec.empty()); + expect_eq(log.calls(), std::size_t{1}); + expect_stop(probe, R::RetryStopReason::stop_requested, 1); + expect_last_error(probe, "e1"); + expect_eq(q->active_timers(), std::size_t{1}); + expect(occupier->cancel()); +} + +Void::Testing::Test async_retry_destroy_during_pending_backoff_cancels_timer() +{ + ManualExecutor exec; + ManualClock clock; + auto q = make_queue(exec, clock); + std::stop_source source; + int calls = 0; + { + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), + [&calls]() -> std::expected { + ++calls; + return std::unexpected{std::string{"e"}}; + }, + *q, + OperationOptions{.stop = source.get_token()}), + &probe); + start(task); + expect_eq(q->active_timers(), std::size_t{1}); + expect_eq(probe.resumes, 0); + // Destroyed while its backoff timer is still pending (same thread as + // poll, close and stop): the timer is cancelled with the frame. + } + expect_eq(q->active_timers(), std::size_t{0}); + expect(!q->next_deadline().has_value()); + + // Nothing can resume the destroyed frame afterwards. + expect(source.request_stop()); + advance_clock(clock, 1h); + expect_eq(q->poll_expired(), std::size_t{0}); + q->close(); + expect(exec.empty()); + expect_eq(exec.drain(), std::size_t{0}); + expect_eq(calls, 1); +} + +// ── clock range and cross-adapter conformance ───────────────────────────────── + +Void::Testing::Test async_retry_far_future_manual_clock_saturates() +{ + const TimePoint far = TimePoint::max() - std::chrono::duration_cast(15ms); + + // Budget 1h saturates the deadline to max(); the second backoff would + // reach max() as well, which is not before the deadline. + { + ManualExecutor exec; + ManualClock clock{far}; + auto q = make_queue(exec, clock); + auto spec = constant_spec(10ms, 5); + spec.budget = Ns{1h}; + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(spec, failing_until(&log, 0), *q), &probe); + start(task); + require(q->next_deadline().has_value()); + expect(*q->next_deadline() == far + std::chrono::duration_cast(10ms)); + advance_clock(clock, 10ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + expect_stop(probe, R::RetryStopReason::deadline_exceeded, 2); + expect_eq(log.calls(), std::size_t{2}); + expect_eq(q->active_timers(), std::size_t{0}); + } + + // Without a budget the wake-up saturates to max() instead of wrapping + // into the past, and fires once the clock reaches max(). + { + ManualExecutor exec; + ManualClock clock{far}; + auto q = make_queue(exec, clock); + AttemptLog log{&clock}; + RetryProbe probe; + auto task = collect(retry_async(constant_spec(10ms, 5), failing_until(&log, 3), *q), &probe); + start(task); + advance_clock(clock, 10ms); + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect_eq(log.calls(), std::size_t{2}); + require(q->next_deadline().has_value()); + expect(*q->next_deadline() == TimePoint::max()); + expect_eq(q->poll_expired(), std::size_t{0}); + advance_clock(clock, 5ms); // exactly max() + expect_eq(q->poll_expired(), std::size_t{1}); + expect_eq(exec.drain(), std::size_t{1}); + expect(task.done()); + require(probe.result.has_value()); + require(probe.result->has_value()); + expect_eq(**probe.result, 42); + require(log.calls() == 3); + expect(log.times[2] == TimePoint::max()); + } +} + +Void::Testing::Test async_retry_matches_blocking_schedule_same_seed() +{ + R::RetrySpec spec; + spec.max_attempts = 6; + spec.budget = R::no_deadline; + spec.backoff.initial = 10ms; + spec.backoff.cap = 80ms; + spec.backoff.multiplier = 2.0; + spec.backoff.jitter = R::JitterMode::Full; + + // Blocking adapter: injected now plus a sleep that advances the clock. + ManualClock blocking_clock; + AttemptLog blocking_log{&blocking_clock}; + const auto blocking = R::retry_blocking( + spec, + failing_until(&blocking_log, 0), + R::BlockingRetryOptions{ + .now = ManualNow{&blocking_clock}, + .sleep = ManualAdvanceSleep{&blocking_clock}, + .classify = {}, + .urbg = Engine{42}, + .stop = {}, + .deadline = std::nullopt}); + require(!blocking.has_value()); + expect_eq(static_cast(blocking.error().reason), + static_cast(R::RetryStopReason::attempts_exhausted)); + + // Async adapter: jump the clock to each backoff deadline, poll, drain. + ManualExecutor exec; + ManualClock async_clock; + auto q = make_queue(exec, async_clock); + AttemptLog async_log{&async_clock}; + RetryProbe probe; + auto task = collect( + retry_async(spec, failing_until(&async_log, 0), *q, {}, R::RetryEveryError{}, Engine{42}), + &probe); + start(task); + int steps = 0; + int stalls = 0; + while (!task.done() && steps < 16) { + ++steps; + const auto next = q->next_deadline(); + if (!next.has_value() || !async_clock.set(*next).has_value() || q->poll_expired() != 1 || + exec.drain() != 1) { + ++stalls; + break; + } + } + expect_eq(stalls, 0); + expect(task.done()); + expect_stop(probe, R::RetryStopReason::attempts_exhausted, 6); + + // Same spec and seed: both adapters attempt at identical injected times. + expect_eq(async_log.calls(), std::size_t{6}); + expect(async_log.times == blocking_log.times); +} diff --git a/tests/standalone/Async/DeadlineDomains.cpp b/tests/standalone/Async/DeadlineDomains.cpp index cbedc86..fb06486 100644 --- a/tests/standalone/Async/DeadlineDomains.cpp +++ b/tests/standalone/Async/DeadlineDomains.cpp @@ -2,15 +2,21 @@ #include #include #include +#include #include #include #include #include #include +#include +#include #include #include +#include +#include #include +#include namespace { @@ -77,6 +83,51 @@ void start(Void::Coro::Task& task) task.handle().resume(); } +// retry_blocking's only notion of time: `now` reads the ManualClock and the +// sleeper advances it by the requested wait (plus an optional overshoot). +struct ManualNow { + const ManualClock* clock{nullptr}; + + [[nodiscard]] Void::Retry::SteadyTimePoint operator()() const noexcept { return clock->now(); } +}; + +struct ManualAdvanceSleep { + ManualClock* clock{nullptr}; + std::vector* waits{nullptr}; + std::chrono::nanoseconds overshoot{0}; + + bool operator()(std::chrono::nanoseconds wait, std::stop_token) const + { + waits->push_back(wait); + return clock->advance(wait + overshoot).has_value(); + } +}; + +using ManualBlockingOptions = Void::Retry:: + BlockingRetryOptions; + +// Constant backoff of `delay`, no jitter, no time budget. +Void::Retry::RetrySpec constant_retry_spec(std::chrono::nanoseconds delay, std::uint32_t attempts) +{ + Void::Retry::RetrySpec spec; + spec.max_attempts = attempts; + spec.budget = Void::Retry::no_deadline; + spec.backoff.initial = delay; + spec.backoff.cap = delay; + spec.backoff.multiplier = 1.0; + spec.backoff.jitter = std::nullopt; + return spec; +} + +// Fails every attempt with its 1-based index and records when it ran. +auto failing_attempt(const ManualClock* clock, std::vector* times) +{ + return [clock, times]() -> std::expected { + times->push_back(clock->now()); + return std::unexpected{static_cast(times->size())}; + }; +} + } // namespace Void::Testing::Test deadline_domain_schedule_on_and_scope_admission_injected_clock() @@ -242,3 +293,98 @@ Void::Testing::Test deadline_domain_timer_and_operation_deadline_same_manual_clo Void::Testing::require(later.result.has_value()); Void::Testing::expect(later.result->has_value()); } + +Void::Testing::Test deadline_domain_blocking_retry_manual_clock() +{ + namespace R = Void::Retry; + using Ns = std::chrono::nanoseconds; + // The host steady clock is far past the manual-domain deadline below, so + // any host-clock comparison would stop the retry before its first attempt. + Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms); + + // Admission deadline in the ManualClock domain (epoch 0): attempts at 0, + // 10 and 20ms; the wake-up at 30ms would overshoot 25ms, so it stops. + { + ManualClock clock; + const OperationOptions opts{.deadline = at(25ms)}; + Void::Testing::expect(is_deadline_expired(opts)); + Void::Testing::expect(!is_deadline_expired(opts, clock)); + + std::vector attempts; + std::vector waits; + const auto r = R::retry_blocking(constant_retry_spec(10ms, 10), + failing_attempt(&clock, &attempts), + ManualBlockingOptions{.now = ManualNow{&clock}, + .sleep = ManualAdvanceSleep{&clock, &waits}, + .classify = {}, + .urbg = std::mt19937_64{1}, + .stop = {}, + .deadline = opts.deadline}); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::deadline_exceeded)); + Void::Testing::expect_eq(r.error().attempts, std::uint32_t{3}); + Void::Testing::require(r.error().last_error.has_value()); + Void::Testing::expect_eq(*r.error().last_error, 3); + Void::Testing::require(attempts.size() == 3); + Void::Testing::expect(attempts[0] == at(0ns)); + Void::Testing::expect(attempts[1] == at(10ms)); + Void::Testing::expect(attempts[2] == at(20ms)); + Void::Testing::require(waits.size() == 2); + Void::Testing::expect_eq(waits[0], Ns{10ms}); + Void::Testing::expect_eq(waits[1], Ns{10ms}); + // Only the injected sleeper moved time. + Void::Testing::expect(clock.now() == at(20ms)); + } + + // The budget is measured from the start the manual clock reports, here + // a century past epoch, far from any host uptime. + { + const TimePoint start = at(std::chrono::hours{24 * 365 * 100}); + ManualClock clock{start}; + auto spec = constant_retry_spec(10ms, 10); + spec.budget = Ns{25ms}; + std::vector attempts; + std::vector waits; + const auto r = R::retry_blocking(spec, + failing_attempt(&clock, &attempts), + ManualBlockingOptions{.now = ManualNow{&clock}, + .sleep = ManualAdvanceSleep{&clock, &waits}, + .classify = {}, + .urbg = std::mt19937_64{1}, + .stop = {}, + .deadline = std::nullopt}); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::deadline_exceeded)); + Void::Testing::expect_eq(r.error().attempts, std::uint32_t{3}); + Void::Testing::require(attempts.size() == 3); + Void::Testing::expect(attempts[0] == start); + Void::Testing::expect(attempts[2] == start + std::chrono::duration_cast(20ms)); + Void::Testing::expect_eq(waits.size(), std::size_t{2}); + } + + // Advancing manual time past the deadline during one sleep expires the + // operation exactly once: resume() observes it and no attempt follows. + { + ManualClock clock; + std::vector attempts; + std::vector waits; + const auto r = R::retry_blocking(constant_retry_spec(10ms, 10), + failing_attempt(&clock, &attempts), + ManualBlockingOptions{.now = ManualNow{&clock}, + .sleep = ManualAdvanceSleep{&clock, &waits, 30ms}, + .classify = {}, + .urbg = std::mt19937_64{1}, + .stop = {}, + .deadline = at(25ms)}); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq(static_cast(r.error().reason), + static_cast(R::RetryStopReason::deadline_exceeded)); + Void::Testing::expect_eq(r.error().attempts, std::uint32_t{1}); + Void::Testing::expect_eq(attempts.size(), std::size_t{1}); + Void::Testing::require(waits.size() == 1); + Void::Testing::expect_eq(waits[0], Ns{10ms}); + Void::Testing::expect(clock.now() == at(40ms)); + } +}