// packages/resilience/examples/demo.vk // Self-contained verification suite & runnable example for `resilience`. use [res = resilience] assert-true = fn [cond bool, label str] enum [ if not cond [ println (str/join ['[FAIL] ' label] '') os/exit 1 ] print (str/join ['[PASS] ' label] '') .ok ] // --- 1. Bounded LRU + TTL Cache (`new-cache`, `cache-put`, `cache-get`, `cache-stats`) --- // Capacity = 3 entries, default TTL = 500ms (500_000_000 ns) mut cache = res/new-cache 3 500000000 _ = res/cache-put/now mut cache 'k1' 'v1' 0 _ = res/cache-put/now mut cache 'k2' 'v2' 0 _ = res/cache-put/now mut cache 'k3' 'v3' 0 // Touch `k1` so recency order becomes [k2 (LRU), k3, k1 (MRU)] got_k1 = res/cache-get/now/or mut cache 'k1' 10000000 [ '' ] // Inserting `k4` must evict `k2` (the oldest LRU key) _ = res/cache-put/now mut cache 'k4' 'v4' 20000000 miss_k2 = res/cache-get/now/or mut cache 'k2' 30000000 [ 'MISS' ] keep_k3 = res/cache-get/now/or mut cache 'k3' 30000000 [ 'MISS' ] st1 = res/cache-stats cache _ = assert-true (got_k1 == 'v1' and miss_k2 == 'MISS' and keep_k3 == 'v3' and st1.evictions == 1 and st1.size == 3) 'bounded LRU cache promotes accessed keys to MRU and evicts oldest LRU entry' // Advance clock to t = 600ms (past 500ms TTL for k1, k3, k4) and verify lazy + sweep expiration exp_k1 = res/cache-get/now/or mut cache 'k1' 600000000 [ 'EXPIRED' ] swept = res/cache-sweep/now mut cache 600000000 st2 = res/cache-stats cache _ = assert-true (exp_k1 == 'EXPIRED' and swept == 2 and st2.size == 0 and st2.expirations == 3) 'TTL cache lazy expiration on get and eager sweep purge' // --- 2. GCRA & Token-Bucket Rate Limiters --- // 10 req/sec (100ms emission interval), burst = 3 (300ms tolerance window) mut gcra = res/new-gcra 10 3 d1 = res/allow-gcra?/now mut gcra 'tenant:acme' 0 d2 = res/allow-gcra?/now mut gcra 'tenant:acme' 0 d3 = res/allow-gcra?/now mut gcra 'tenant:acme' 0 d4 = res/allow-gcra?/now mut gcra 'tenant:acme' 0 d5 = res/allow-gcra?/now mut gcra 'tenant:acme' 40000000 // t = +40ms -> 60ms remaining wait d6 = res/allow-gcra?/now mut gcra 'tenant:acme' 100000000 // t = +100ms -> 1 cell recovered gcra_ok_1 = d1.allowed and d1.remaining == 2 and d2.allowed and d2.remaining == 1 and d3.allowed and d3.remaining == 0 and d3.reset_after_ms == 300 gcra_ok_2 = (not d4.allowed) and d4.retry_after_ms == 100 and (not d5.allowed) and d5.retry_after_ms == 60 and d6.allowed and d6.retry_after_ms == 0 _ = assert-true (gcra_ok_1 and gcra_ok_2) 'GCRA burst capacity, retry_after_ms, and reset_after_ms cell recovery math' mut tb = res/new-token-bucket/now 2 10 0 tb_ok = (res/allow-tokens?/now mut tb 2 0) and (not (res/allow-tokens?/now mut tb 1 0)) and (res/allow-tokens?/now mut tb 1 100000000) _ = assert-true tb_ok 'token-bucket burst consumption and monotonic refill' // --- 3. 3-State Circuit Breaker (`.closed -> .open -> .half_open -> .closed`) --- // Trips after 2 failures, stays open 500ms, requires 2 half-open probe successes to close mut cb = res/new-breaker 2 500000000 2 cb_calls_ch = chan/new 16 _ = res/call-with-breaker/now/or mut cb fn [] [ _ = chan/send cb_calls_ch 1 err 'upstream 503' ] 0 [ .err ] _ = res/call-with-breaker/now/or mut cb fn [] [ _ = chan/send cb_calls_ch 1 err 'upstream 503' ] 10000000 [ .err ] state_open = cb.state // Fast-fail while `.open` at t = 100ms (must NOT invoke the closure!) fast_reject = res/call-with-breaker/now/or mut cb fn [] [ _ = chan/send cb_calls_ch 1 'should-not-run' ] 100000000 [ 'FAST_REJECTED' ] mut backend_invocations = 0 while true [ c_tick = chan/recv/timeout/or cb_calls_ch 2ms [ 0 ] if c_tick == 0 [ break ] backend_invocations = backend_invocations + c_tick ] // At t = 510ms (> 500ms reset timeout), breaker enters `.half_open`; first probe fails -> trips back to `.open`! probe_fail_state = res/breaker-state/now cb 510000000 _ = res/call-with-breaker/now/or mut cb fn [] [ err 'still-down' ] 510000000 [ .err ] reopened = cb.state == .open // At t = 1020ms, two consecutive `.half_open` probes succeed -> transitions `.half_open -> .closed`! p1 = res/call-with-breaker/now mut cb fn [] [ 'probe-1-ok' ] 1020000000 mid_state = cb.state p2 = res/call-with-breaker/now mut cb fn [] [ 'probe-2-ok' ] 1030000000 final_state = cb.state cb_ok = state_open == .open and fast_reject == 'FAST_REJECTED' and backend_invocations == 2 and cb.total_rejected == 1 and probe_fail_state == .half_open and reopened and p1 == 'probe-1-ok' and mid_state == .half_open and p2 == 'probe-2-ok' and final_state == .closed _ = assert-true cb_ok 'Circuit Breaker full .closed -> .open -> .half_open (probe fail/recover) -> .closed lifecycle' // --- 4. Exponential Backoff + Full Jitter & Hedged Retry Policy --- b0 = res/backoff-delay-ms 25 150 0 b2 = res/backoff-delay-ms 25 150 2 b4 = res/backoff-delay-ms 25 150 4 bj = res/backoff-delay-ms/jitter/seed 25 150 3 true 99 tries_ch = chan/new 16 pol = res/RetryPolicy { max_attempts = 4, base_delay_ms = 5, max_delay_ms = 50, full_jitter = true, sleep_enabled = false, seed = 7 } ret_val = res/retry-with pol fn [attempt] [ _ = chan/send tries_ch 1 if attempt < 2 [ err 'transient-timeout' ] else [ 'recovered-on-3rd' ] ] mut tries = 0 while true [ t_tick = chan/recv/timeout/or tries_ch 2ms [ 0 ] if t_tick == 0 [ break ] tries = tries + t_tick ] hedged_val = res/hedged-call fn [] [ err 'primary-slow' ] fn [] [ 'backup-replica-ok' ] _ = assert-true (b0 == 25 and b2 == 100 and b4 == 150 and bj >= 0 and bj <= 150 and ret_val == 'recovered-on-3rd' and tries == 3 and hedged_val == 'backup-replica-ok') 'exponential backoff, Full Jitter bounds, retry-with recovery, and hedged-call fallback' // --- 5. Channel-Backed Thread-Safe Singleflight Across Concurrent `spawn` Workers --- sf = res/new-singleflight loads_ch = chan/new 16 mut tasks = [] mut wi = 0 while wi < 5 [ t = spawn [ res/singleflight-do sf 'profile:42' fn [] [ _ = chan/send loads_ch 1 _ = time/sleep 40ms 'user-profile-42' ] ] push mut tasks t wi = wi + 1 ] mut shared_cnt = 0 mut all_match = true mut ti = 0 while ti < (len tasks) [ out = task/await tasks[ti] if out.val != 'user-profile-42' [ all_match = false ] if out.shared [ shared_cnt = shared_cnt + 1 ] ti = ti + 1 ] // Count how many times the slow loader actually ran mut actual_loads = 0 while true [ tick = chan/recv/timeout/or loads_ch 5ms [ 0 ] if tick == 0 [ break ] actual_loads = actual_loads + tick ] _ = assert-true (all_match and actual_loads == 1 and shared_cnt >= 1) 'Singleflight coalesces 5 concurrent spawn workers into 1 upstream execution' print 'resilience: all verification checks passed'