feat(Resilience): add validated configs, RAII breaker/resource permits, bounded keyed cleanup, ResilienceAsync composition, and reserve P2 error domains (M-RESILIENCE-01..04)

This commit is contained in:
faumaray committed 2026-11-24 10:06:35 +03:00
1 parent fe99051ded
commit 18a623aa62
19 files changed
+2854 -427

No files matched your search

+5
View File
@@ -126,6 +126,11 @@ if(_has_obs)
run_consumer(ObservabilityOnly "${install_prefix}" "ObservabilityOnly" ${_no_external_deps})
endif()
has_modules(_has_resilience Resilience ObservabilityHooks Time Functional Core)
if(_has_resilience)
run_consumer(ResilienceOnly "${install_prefix}" "ResilienceOnly" ${_no_external_deps})
endif()
# Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation)
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(VoidResilienceOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Resilience)
add_executable(void_resilience_only_consumer main.cpp)
target_link_libraries(void_resilience_only_consumer PRIVATE Void::Resilience)
enable_testing()
add_test(NAME VoidResilienceOnlyConsumer COMMAND void_resilience_only_consumer)
+22
View File
@@ -0,0 +1,22 @@
#include <Void/Resilience/Resilience.hpp>
int main()
{
auto b = Void::Resilience::TokenBucket::create(
Void::Resilience::BucketConfig{4.0, 1.0});
auto br = Void::Resilience::Breaker::create(Void::Resilience::BreakerConfig{});
auto mon = Void::Resilience::ResourceMonitor::create(
Void::Resilience::MonitorConfig{16, 0.9, 0.7});
if (!b || !br || !mon) {
return 1;
}
auto bp = br->acquire();
auto rp = mon->try_acquire_checked(4);
auto adm = b->try_acquire_checked(1.0);
if (!bp || !rp || !adm || !adm->allowed) {
return 2;
}
bp->finish(Void::Resilience::Outcome::success);
rp->release();
return 0;
}
@@ -0,0 +1,272 @@
#include <Void/Resilience/Resilience.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <limits>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
namespace
{
using namespace Void::Resilience;
using namespace std::chrono_literals;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
} // namespace
Void::Testing::Test resilience_bucket_config_regression_and_multi_rollback()
{
expect(!BucketConfig{0.0, 1.0}.validate().has_value());
expect(!BucketConfig{-1.0, 1.0}.validate().has_value());
expect(!BucketConfig{std::numeric_limits<double>::quiet_NaN(), 1.0}.validate().has_value());
expect(!BucketConfig{10.0, -0.5}.validate().has_value());
expect(!BucketConfig{10.0, std::numeric_limits<double>::infinity()}.validate().has_value());
// Zero refill is valid (finite non-refilling bucket).
expect(BucketConfig{10.0, 0.0}.validate().has_value());
Void::Time::ManualClock clock;
(void)clock.advance(10s);
auto b1_res = TokenBucket::create(BucketConfig{10.0, 2.0}, clock);
auto b2_res = TokenBucket::create(BucketConfig{4.0, 1.0}, clock);
require(b1_res.has_value() && b2_res.has_value());
auto b1 = std::move(*b1_res);
auto b2 = std::move(*b2_res);
// Invalid costs consume nothing.
expect(!b1.try_acquire_checked(-1.0).has_value());
expect(!b1.try_acquire_checked(0.0).has_value());
expect(!b1.try_acquire_checked(std::numeric_limits<double>::quiet_NaN()).has_value());
expect(!b1.try_acquire_checked(11.0).has_value());
expect_eq(b1.available(), 10.0);
// Spend 2 from b1, then prove backwards timestamp cannot add double credit.
auto ok1 = b1.try_acquire_checked(2.0);
require(ok1.has_value());
expect(ok1->allowed);
const auto t_now = clock.now();
const auto earlier = t_now - 5s;
expect(b1.available_at(earlier) <= 8.0001);
expect(b1.available_at(t_now) <= 8.0001);
// Multi-bucket atomic acquisition rolls back (leaves both untouched) when b2 fails.
const std::pair<TokenBucket*, double> pair_fail[] = {{&b1, 5.0}, {&b2, 5.0}};
expect(!TokenBucket::try_acquire_all(pair_fail, clock).has_value());
expect_eq(b1.available(), 8.0);
expect_eq(b2.available(), 4.0);
const std::pair<TokenBucket*, double> pair_deny[] = {{&b1, 5.0}, {&b2, 4.0}};
auto adm1 = TokenBucket::try_acquire_all(pair_deny, clock);
require(adm1.has_value());
expect(adm1->allowed);
expect_eq(b1.available(), 3.0);
expect_eq(b2.available(), 0.0);
// Now b2 cannot afford 1 -> b1 must NOT be debited!
const std::pair<TokenBucket*, double> pair_second[] = {{&b1, 2.0}, {&b2, 1.0}};
auto adm2 = TokenBucket::try_acquire_all(pair_second, clock);
require(adm2.has_value());
expect(!adm2->allowed);
expect(adm2->retry_after > 0ns);
expect_eq(b1.available(), 3.0);
}
Void::Testing::Test resilience_resource_monitor_overflow_permits_and_observers()
{
expect(!MonitorConfig{0, 0.9, 0.7}.validate().has_value());
expect(!MonitorConfig{100, 0.5, 0.8}.validate().has_value());
expect(!MonitorConfig{100, 1.5, 0.7}.validate().has_value());
// Overflow-safe check near UINT64_MAX.
const auto umax = std::numeric_limits<std::uint64_t>::max();
ResourceMonitor hugemon{umax};
expect(hugemon.try_acquire(umax - 10));
expect(!hugemon.try_acquire(20)); // previously wrapped unsigned arithmetic!
expect_eq(hugemon.usage(), umax - 10);
auto mon_res = ResourceMonitor::create(MonitorConfig{100, 0.9, 0.7});
require(mon_res.has_value());
auto mon = std::move(*mon_res);
// Observer that throws AND re-enters monitor queries must not corrupt state.
int high_calls = 0;
mon.on_high_watermark([&](std::uint64_t) {
++high_calls;
(void)mon.usage();
throw std::runtime_error{"observer failed"};
});
{
auto p = mon.try_acquire_checked(95);
require(p.has_value());
expect(p->active());
expect_eq(mon.usage(), std::uint64_t{95});
expect_eq(high_calls, 1);
expect_eq(mon.observer_errors(), std::uint64_t{1});
}
// Permit auto-released on destruction.
expect_eq(mon.usage(), std::uint64_t{0});
// Strict over-release check rejects instead of silently clamping.
expect(mon.try_acquire(10));
auto over = mon.release_checked(20);
expect(!over.has_value());
expect_eq(over.error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::over_release));
expect_eq(mon.usage(), std::uint64_t{10});
}
Void::Testing::Test resilience_breaker_single_probe_generation_and_abandon()
{
expect(!BreakerConfig{0, 5s, 1, 2}.validate().has_value());
expect(!BreakerConfig{5, 5s, 0, 2}.validate().has_value());
expect(!BreakerConfig{5, 5s, 1, 0}.validate().has_value());
Void::Time::ManualClock clock;
BreakerConfig cfg{};
cfg.failure_threshold = 2;
cfg.cooldown = 5s;
cfg.half_open_max_probes = 1;
cfg.success_threshold = 2;
auto br_res = Breaker::create(cfg, clock);
require(br_res.has_value());
auto br = std::move(*br_res);
// Grab an in-flight permit at gen 1 BEFORE tripping, then trip Open with another.
auto stale_p = br.acquire();
require(stale_p.has_value());
const auto gen1 = stale_p->generation();
for (int i = 0; i < 2; ++i) {
auto p = br.acquire();
require(p.has_value());
p->finish(Outcome::dependency_failure);
}
expect(br.state() == BreakerState::open);
expect(br.generation() > gen1);
// Completing stale generation permit must not close or corrupt Open breaker.
stale_p->finish(Outcome::success);
expect(br.state() == BreakerState::open);
expect(!br.acquire().has_value());
// Advance cooldown: first acquire gets sole HalfOpen probe; concurrent 2nd fails.
(void)clock.advance(5s);
{
auto probe1 = br.acquire();
require(probe1.has_value());
expect(probe1->is_probe());
expect(br.state() == BreakerState::half_open);
expect_eq(br.half_open_in_flight(), std::size_t{1});
auto concurrent = br.acquire();
expect(!concurrent.has_value());
expect_eq(concurrent.error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::circuit_open));
// Destroying probe1 without explicit finish treats it neutrally and
// frees the probe slot so HalfOpen does not deadlock.
}
expect_eq(br.half_open_in_flight(), std::size_t{0});
expect(br.state() == BreakerState::half_open);
// Two sequential successful probes close the breaker.
for (int i = 0; i < 2; ++i) {
auto probe = br.acquire();
require(probe.has_value());
expect(probe->is_probe());
probe->finish(Outcome::success);
}
expect(br.state() == BreakerState::closed);
// Multi-thread contention during HalfOpen never exceeds 1 concurrent probe.
for (int i = 0; i < 2; ++i) {
auto p = br.acquire();
require(p.has_value());
p->finish(Outcome::dependency_failure);
}
(void)clock.advance(5s);
std::atomic<int> admitted_probes{0};
std::atomic<int> rejected{0};
std::vector<std::thread> racers;
std::vector<std::optional<BreakerPermit>> acquired(16);
std::atomic<bool> go{false};
for (std::size_t i = 0; i < 16; ++i) {
racers.emplace_back([&, i] {
while (!go.load(std::memory_order_acquire)) {
}
auto r = br.acquire();
if (r.has_value()) {
admitted_probes.fetch_add(1, std::memory_order_relaxed);
acquired[i].emplace(std::move(*r));
} else {
rejected.fetch_add(1, std::memory_order_relaxed);
}
});
}
go.store(true, std::memory_order_release);
for (auto& t : racers) {
t.join();
}
expect_eq(admitted_probes.load(), 1);
expect_eq(rejected.load(), 15);
acquired.clear();
}
Void::Testing::Test resilience_bounded_keyed_limiter_churn_and_cursor_cleanup()
{
Void::Time::ManualClock clock;
KeyedBucketConfig cfg{};
cfg.capacity = 2.0;
cfg.refill_per_second = 0.0;
cfg.max_keys = 3;
cfg.max_key_bytes = 16;
cfg.idle_retention = 10s;
cfg.cleanup_batch_limit = 2;
auto kl_res = BoundedKeyedRateLimiter<std::string>::create(cfg, clock);
require(kl_res.has_value());
auto kl = std::move(*kl_res);
// Oversize key fails with key_too_large.
auto too_long = kl.admit(std::string(17, 'x'));
expect(!too_long.has_value());
expect_eq(too_long.error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::key_too_large));
expect(kl.admit("k1")->allowed);
expect(kl.admit("k2")->allowed);
expect(kl.admit("k3")->allowed);
expect_eq(kl.tracked(), std::size_t{3});
// Churn keys k4..k10 must be rejected cleanly WITHOUT evicting live k1..k3!
for (int i = 4; i <= 10; ++i) {
auto r = kl.admit("k" + std::to_string(i));
require(r.has_value());
expect(!r->allowed);
}
expect_eq(kl.rejected_new_keys(), std::uint64_t{7});
expect(kl.admit("k1")->allowed); // k1's quota was NOT reset (1/2 remaining)!
expect(!kl.admit("k1")->allowed); // k1 is now genuinely empty!
// Refresh k1 at t=8s; leave k2 and k3 untouched since t=0s.
(void)clock.advance(8s);
(void)kl.admit("k2", 0.5); // consume from k2 to refresh last_seen to 8s
// Advance to t=11s: k1 (last=0s) & k3 (last=0s) are >=10s idle; k2 (last=8s) is live.
(void)clock.advance(3s);
// cleanup_batch_limit=2 removes in bounded incremental steps across turns.
const std::size_t r1 = kl.cleanup_step();
const std::size_t r2 = kl.cleanup_step();
expect_eq(r1 + r2, std::size_t{2});
expect_eq(kl.tracked(), std::size_t{1});
}
@@ -0,0 +1,252 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/ThreadPool.hpp>
#include <Void/Resilience/AsyncPolicy.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <stop_token>
#include <string>
#include <vector>
namespace Async = Void::Async;
using namespace Void::Resilience;
using namespace std::chrono_literals;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
namespace
{
Void::Coro::Task<Void::Result::Result<BulkheadPermit>> acquire_bulkhead_coro(
Bulkhead& bh,
Async::OperationOptions opts,
Async::Executor* exec)
{
co_return co_await bh.acquire_async(std::move(opts), exec);
}
Void::Coro::Task<void> spawn_acquire_to_slot(
Bulkhead* bh,
Async::OperationOptions opts,
Async::Executor* exec,
std::optional<Void::Result::Result<BulkheadPermit>>* out,
std::atomic<int>* done_count)
{
*out = co_await bh->acquire_async(std::move(opts), exec);
done_count->fetch_add(1, std::memory_order_release);
}
Void::Coro::Task<Void::Result::Result<int>> run_pipeline_coro(
ResiliencePipeline pipeline,
std::function<Void::Result::Result<int>()> fn,
std::function<AttemptClassification(const Void::Result::Result<int>&)> classify,
Async::OperationOptions opts,
Async::Executor* exec)
{
co_return co_await execute_resilient(
std::move(pipeline),
std::move(fn),
std::move(classify),
std::move(opts),
exec);
}
} // namespace
Void::Testing::Test resilience_async_bulkhead_fifo_expiry_stop_and_close()
{
Void::Time::ManualClock clock;
BulkheadConfig cfg{};
cfg.max_active = 1;
cfg.max_waiting = 2;
auto bh_res = Bulkhead::create(cfg, clock);
require(bh_res.has_value());
auto bh = std::move(*bh_res);
auto active1 = bh.try_acquire();
require(active1.has_value());
expect_eq(bh.active_count(), std::size_t{1});
Void::Async::ManualExecutor exec;
std::optional<Void::Result::Result<BulkheadPermit>> out_exp;
std::optional<Void::Result::Result<BulkheadPermit>> out_stop;
std::optional<Void::Result::Result<BulkheadPermit>> out_ok;
std::atomic<int> done{0};
std::stop_source stop_src;
Async::OperationOptions exp_opts{};
exp_opts.deadline = clock.now() + 50ms;
Async::OperationOptions stop_opts{};
stop_opts.stop = stop_src.get_token();
// Enqueue 2 waiters (limit=2): waiter1 has deadline, waiter2 has stop token.
Void::Async::spawn(
exec, spawn_acquire_to_slot(&bh, exp_opts, &exec, &out_exp, &done));
Void::Async::spawn(
exec, spawn_acquire_to_slot(&bh, stop_opts, &exec, &out_stop, &done));
(void)exec.drain();
expect_eq(bh.waiting_count(), std::size_t{2});
// Advance past waiter1's deadline AND request waiter2 stop before next admission.
(void)clock.advance(100ms);
stop_src.request_stop();
(void)exec.drain();
// Release active1 -> evicts expired waiter1 and cancelled waiter2, freeing slot!
active1->release();
(void)exec.drain();
expect_eq(done.load(std::memory_order_acquire), 2);
require(out_exp.has_value() && !out_exp->has_value());
require(out_stop.has_value() && !out_stop->has_value());
expect_eq(bh.waiting_count(), std::size_t{0});
expect_eq(bh.active_count(), std::size_t{0});
// Now test FIFO wait grant + close().
auto active2 = bh.try_acquire();
require(active2.has_value());
done.store(0);
std::optional<Void::Result::Result<BulkheadPermit>> out_closed;
Void::Async::spawn(
exec, spawn_acquire_to_slot(&bh, {}, &exec, &out_ok, &done));
Void::Async::spawn(
exec, spawn_acquire_to_slot(&bh, {}, &exec, &out_closed, &done));
(void)exec.drain();
expect_eq(bh.waiting_count(), std::size_t{2});
// 3rd waiter overflows max_waiting=2 immediately.
auto full_t = acquire_bulkhead_coro(bh, {}, &exec);
auto full_r = full_t.run();
expect(!full_r.has_value());
expect_eq(full_r.error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::bulkhead_full));
// Releasing active2 grants first FIFO waiter (out_ok).
active2->release();
(void)exec.drain();
require(out_ok.has_value() && out_ok->has_value());
// close() rejects remaining waiter (out_closed) with closed error.
bh.close();
(void)exec.drain();
require(out_closed.has_value() && !out_closed->has_value());
expect_eq(out_closed->error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::closed));
out_ok->value().release();
}
Void::Testing::Test resilience_async_execute_order_replay_deadline_and_breaker()
{
Void::Time::ManualClock clock;
auto rl = TokenBucket::create(BucketConfig{10.0, 1.0}, clock);
auto bh = Bulkhead::create(BulkheadConfig{2, 4}, clock);
auto br = Breaker::create(BreakerConfig{2, 5s, 1, 1}, clock);
require(rl.has_value() && bh.has_value() && br.has_value());
// 1. Non-replay-safe write never retries even when classifier marks retryable.
int calls = 0;
std::vector<std::chrono::nanoseconds> delays;
ResiliencePipeline write_pipe{};
write_pipe.rate_limiter = &*rl;
write_pipe.bulkhead = &*bh;
write_pipe.breaker = &*br;
write_pipe.clock = &clock;
write_pipe.retry = ResilientRetryConfig{
.max_attempts = 3,
.base_delay = 100ms,
.max_delay = 2000ms,
.replay_safe = false,
.deterministic_seed = 42};
write_pipe.wait_fn = [&](std::chrono::nanoseconds d, const Async::OperationOptions&) {
delays.push_back(d);
(void)clock.advance(d);
return true;
};
auto res1 = run_pipeline_coro(
write_pipe,
[&]() -> Void::Result::Result<int> {
++calls;
return Void::Result::fail("write uncertain");
},
[](const Void::Result::Result<int>&) {
return AttemptClassification{Outcome::dependency_failure, true};
},
{},
nullptr)
.run();
expect(!res1.has_value());
expect_eq(calls, 1);
expect_eq(bh->active_count(), std::size_t{0});
// Reset breaker (or let 2nd failure trip it on replay-safe call!).
// 2. Replay-safe read retries through limits until breaker trips open!
calls = 0;
ResiliencePipeline read_pipe = write_pipe;
read_pipe.retry.replay_safe = true;
read_pipe.retry.max_attempts = 5;
auto res2 = run_pipeline_coro(
read_pipe,
[&]() -> Void::Result::Result<int> {
++calls;
return Void::Result::fail("transient downstream");
},
[](const Void::Result::Result<int>&) {
return AttemptClassification{Outcome::dependency_failure, true};
},
{},
nullptr)
.run();
// 1st attempt failed before this test -> breaker already had 1 failure, so
// this attempt trips breaker Open on attempt #1, then attempt #2 fails with circuit_open!
expect(!res2.has_value());
expect_eq(calls, 1);
expect_eq(res2.error().code().value,
static_cast<std::int32_t>(ResilienceErrorCode::circuit_open));
expect_eq(bh->active_count(), std::size_t{0});
// 3. Replay-safe succeeds on attempt #3 within shared total deadline.
(void)clock.advance(5s); // cooldown elapsed -> HalfOpen probe closes breaker on 1st success!
auto br2 = Breaker::create(BreakerConfig{10, 5s, 1, 1}, clock);
require(br2.has_value());
calls = 0;
delays.clear();
ResiliencePipeline ok_pipe = read_pipe;
ok_pipe.breaker = &*br2;
ok_pipe.retry.max_attempts = 3;
ok_pipe.wait_fn = [&](std::chrono::nanoseconds d, const Async::OperationOptions&) {
delays.push_back(d);
(void)clock.advance(d);
return true;
};
Async::OperationOptions bounded_opts{};
bounded_opts.deadline = clock.now() + 5000ms;
auto res3 = run_pipeline_coro(
ok_pipe,
[&]() -> Void::Result::Result<int> {
++calls;
if (calls < 3) {
return Void::Result::fail("retryable");
}
return 99;
},
[](const Void::Result::Result<int>& r) {
return r.has_value()
? AttemptClassification{Outcome::success, false}
: AttemptClassification{Outcome::dependency_failure, true};
},
bounded_opts,
nullptr)
.run();
require(res3.has_value());
expect_eq(*res3, 99);
expect_eq(calls, 3);
expect_eq(delays.size(), std::size_t{2});
expect(delays[0] <= 100ms);
expect(delays[1] <= 200ms);
}