# Resilience implementation plan Status: planning only; all feature tasks PLANNED. Source baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24. Applies [requirements](../REQUIREMENTS.md) R-005, R-009, R-012, R-014–R-016 and [architecture](../ARCHITECTURE.md) C-02–C-05, C-11, C-13. ## Current primitives and gaps `Void::Resilience` is a native header implementation with no declared module dependencies in [module.cmake](../../../src/Resilience/module.cmake). [Resilience.hpp](../../../include/Void/Resilience/Resilience.hpp) gathers [TokenBucket](../../../include/Void/Resilience/RateLimiter.hpp), [KeyedRateLimiter](../../../include/Void/Resilience/KeyedRateLimiter.hpp), [CircuitBreaker](../../../include/Void/Resilience/CircuitBreaker.hpp), and [ResourceMonitor](../../../include/Void/Resilience/ResourceMonitor.hpp). Injected steady-clock functions already support deterministic tests. Keyed buckets can be capped but default to historical unbounded `max_keys == 0`; cleanup scans the map. ResourceMonitor invokes threshold callbacks outside its mutex and clamps over-release. Important implementation gaps: `CircuitBreaker::allow()` admits all callers after transitioning to HalfOpen; its comment about one probe is not enforced by a lease. Late outcomes are not associated with a breaker generation. Token costs/configuration are not validated for negatives/NaN. ResourceMonitor compares `usage_ + amount`, which needs overflow-safe subtraction, and callback setters need synchronized publication. These are proposed repairs, not claims that the current tests expose every issue. Existing [breaker tests](../../../tests/standalone/Resilience/CircuitBreaker.cpp), [bucket tests](../../../tests/standalone/Resilience/RateLimiter.cpp), [keyed tests](../../../tests/standalone/Resilience/KeyedRateLimiter.cpp), and [monitor tests](../../../tests/standalone/Resilience/ResourceMonitor.cpp) exercise transitions, refill, cap/cleanup and hysteresis. Scoped graph coverage reported matching metadata/no recorded gaps for these paths; implementation and test source were inspected. ## Native policy model and NEW APIs Keep synchronous admission primitives standard-library-only, with no scheduler or logging dependency. Put cancellable waits/composition in an optional Async adapter; retries reuse Functional's policy owner rather than creating a second retry engine. Metrics flow through optional [Observability](../subsystems/Observability.md) hooks outside locks. ```cpp // NEW illustrative Void::Resilience shapes; Result follows C-02. struct BucketConfig { double capacity{100}; double refill_per_second{100}; }; struct Admission { bool allowed; std::chrono::nanoseconds retry_after; }; class Permit { // move-only; exactly one outcome; release on destruction void finish(Outcome); // success, dependency_failure, neutral }; class Breaker { Result acquire(); // refusal is CircuitOpen, never an empty success }; class Bulkhead { Result try_acquire(); // limits active plus admitted waiting work }; // Async adapter uses Async-owned OperationOptions and Time-owned Clock. ``` Select consecutive-failure breaker initially: five failures opens; 5-second cooldown; one simultaneous HalfOpen permit; two sequential successful probes close. A permit captures generation and probe identity. Old-generation completions release resources but cannot close a newer Open state. Abandoning a probe is neutral and releases its slot; it does not leave the breaker permanently HalfOpen. Timeout counts only when classified as dependency failure; local overload/caller stop/auth rejection are neutral. Callbacks run outside locks and do not change the recorded outcome on observer failure. Token refill uses `max(last, now)` so a clock moving backwards cannot cause later double credit. Validate finite positive capacity/cost, finite nonnegative refill and cost ≤ capacity. Zero refill is a finite non-refilling bucket, not an unlimited rate. Costs use checked arithmetic; a failed multi-limit admission rolls back every reservation. NEW keyed defaults: 10,000 keys, maximum encoded key 256 bytes, 5-minute idle retention; cleanup processes at most 256 entries/turn using a maintained cursor. At cap reject new keys; do not evict an active client's bucket and reset its quota. Keys must be normalized by the caller and must not become raw high-cardinality metrics labels. Composition order: deadline/stop check → rate admission → bulkhead → breaker permit → one attempt → classify outcome → release permits → retry policy decides next attempt. A retry re-enters limits and shares the original total deadline. Default adapter: three attempts total, full jitter with 100 ms base and 2-second cap, only explicitly retryable and replay-safe work. No retry of an unknown write without identity/dedup support. No queue is created by `try_acquire`; asynchronous waiting is explicit FIFO admission. Default bulkhead is 64 active and 128 waiting; expired waiters are removed before admission. ## Ownership, limits and failures Permits own their reservation until finish/destruction; the limiter state is retained until the last permit returns. Closing stops admission, cancels waiters, and joins owned adapter tasks without destroying in-use state. Observers cannot borrow a dead limiter. Resource budgets count queue, executing attempts and delayed retries separately; default aggregate adapter retention is 8 MiB. Monitoring uses `amount > limit - usage` after invariant checks. New strict permits reject over-release; legacy clamping remains an adapter behavior. Default hysteresis remains high 90%, low 70%, with validated ordering. | Fault | Decision | Evidence gate | | --- | --- | --- | | Invalid/NaN config or negative cost | Configuration/input error; consume nothing | Boundary/property tests | | Key/queue cap full | Overload with retry hint when computable | Churn cannot reset live quotas | | Stop while waiting/retrying | Remove waiter/timer, one cancelled result | Stop vs grant/retry race | | Failure races with cooldown probe | Generation decides, one active probe | Hundreds of concurrent acquisitions | | Observer throws/reenters | Isolate observer error; reservation remains correct | Reentrant acquire/release tests | | Dependency outage | Open breaker, bounded retry traffic | Deterministic outage/recovery history | | Clock regresses / integer overflow | No refill gain / reject reservation | Min/max integer and reversed time | ## Task DAG | ID | Phase / dependencies | Implementation and acceptance | Recommended role | | --- | --- | --- | --- | | M-RESILIENCE-01 | P0; baseline | Record existing semantics and reproduce probe, invalid-cost and overflow gaps with meaningful regressions | sol_implementer | | M-RESILIENCE-02 | P1; M-RESILIENCE-01, Functional/Time contracts | Validated configurations and machine-readable admission errors; ordinary use needs no runtime | sol_implementer | | M-RESILIENCE-03 | P2; M-RESILIENCE-02 | Generation-bound RAII permits, bounded keyed cleanup, monitor synchronization; races and arithmetic tests pass | astra_implementer | | M-RESILIENCE-04 | P2; M-RESILIENCE-03, Async foundations | Optional bulkhead/wait/retry adapter; finite queues, total deadline, stop/join verified | sol_implementer | | M-RESILIENCE-05 | P3; M-RESILIENCE-04, Net/RPC foundations | Network policy recipes and observations; retries cannot amplify beyond configured attempt/admission budgets | sol_implementer | | M-RESILIENCE-06 | P4; M-RESILIENCE-05, Replication gate | Partition/recovery workloads separate local overload from peer failure; limits never substitute for quorum safety | astra_implementer | ## Validation and migration CURRENT tests are the four linked source suites in existing VoidTests; no execution is claimed here. PROPOSED verification adds deterministic model histories, concurrency and sanitizer tests, callback reentrancy, cancelled FIFO waiters and bounded cleanup work. Targets are added in implementation before advertising runner commands; use [VALIDATION](../VALIDATION.md). Benchmark hot-key contention, high key churn, empty/full admission, retry storms and observer overhead; capture p50/p95/p99, throughput, allocations, peak RSS/CPU and build cost per [PERFORMANCE](../PERFORMANCE.md). Major-release migration changes zero/unbounded configuration to an explicit policy and replaces boolean breaker admission with a permit. Existing synchronous methods receive deprecated wrappers where semantics can be preserved; do not promise a one-probe guarantee through an API that cannot retain probe ownership. Ship comparison fixtures and a rollback switch for the optional composition layer; never discard active reservations on policy replacement. See [MIGRATION](../MIGRATION.md), [Net](Net.md) and [Messaging](../subsystems/Messaging.md).