lietzsche;stokes

updated 2026-11-26·6 min read

Verification, Fuzzing & Simulation Harness

10,000-case IEEE-754 float fuzzing battery, Criterion micro-benchmark parser, and RFC-2439 BGP route flap dampening simulator.

Static AST checks catch cardinality drift before a branch merges, but edge proxies also break at runtime on things a schema diff can’t see: NaN values casting to 0u8 and slipping past bot thresholds, subnormal floats forcing x86 ALUs into ~100x microcode assist stalls, heap allocations evicting L1D cache lines, and process crashes tripping BGP route dampening.

The Stokes Verification Harness (stokes/harness) runs three automated checks before sealing stokes.lock and CONFORMANCE.md:

  1. 10,000-Case IEEE-754 Float Fuzz Battery

    Sweeps quiet and signaling NaNs, +/-infinity, and subnormal bit patterns to enforce fail-secure sanitization (100.0).

  2. Criterion Benchmark Regression Gate

    Parses target/criterion JSON outputs against the 16-item slice baseline (7.66 ns in-place vs 29.74 ns heap) and fails if latency exceeds the 10% tolerance (8.43 ns).

  3. RFC-2439 BGP Route Flap Simulator

    Tracks carrier penalty budgets and 15-minute half-life decay to confirm three-tier degradation avoids carrier route dampening.

10,000-Case IEEE-754 Float Fuzzing Battery

The NaN Threat Bypass & Subnormal CPU Traps

In unpatched Rust or C++, casting a non-finite float to u8 silently produces zero (f32::NAN as u8 == 0), so a malformed NaN score walks straight past < 50 bot gates. Subnormal floats (0<∣x∣<2−126≈1.1754944×10−380 < |x| < 2^{-126} \approx 1.1754944 \times 10^{-38}) hit a different trap: they force x86 ALUs into microcode assist execution, slowing arithmetic by roughly 100x.

Stokes checks both hardware Flush-to-Zero / Denormals-Are-Zero (FTZ/DAZ) setup and a fail-secure sanitize_signal_float guard:

Vulnerable Cast

// Vulnerable: NaN casts to 0u8
let entropy_score: f32 = f32::NAN;
let threat_level = entropy_score as u8;
if threat_level < 50 {
    allow_request();
}

Hardened Sanitization Guard

#[inline(always)]
pub fn sanitize_signal_float(val: f32, fail_secure_default: f32) -> f32 {
    if val.is_finite() && !val.is_subnormal() {
        val.clamp(0.0, 100.0)
    } else {
        fail_secure_default
    }
}
Hardware FTZ/DAZ Registers & 10,000-Case Float Fuzz Battery
// crates/cloudflame-proxy/src/engine/traffic_evaluator.rs
#[inline(always)]
pub fn configure_hardware_float_registers() {
    #[cfg(target_arch = "x86_64")]
    unsafe {
        use std::arch::x86_64::*;
        _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
        _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
    }
}
# stokes/harness/float_fuzz_battery.py
def run_battery(num_random_cases: int = 10000) -> dict[str, Any]:
    """Execute 10,000-case IEEE-754 fuzzing suite."""
    adversarial_cases = _generate_adversarial_cases()
    passed = 0
    failed = 0

    for val, desc in adversarial_cases:
        result = sanitize_signal_float(val, fail_secure_default=100.0)
        if math.isnan(val) or math.isinf(val) or (0.0 < abs(val) < 1.1754944e-38):
            if result != 100.0:
                failed += 1
                continue
        passed += 1

    for _ in range(num_random_cases):
        bits = random.getrandbits(32)
        val = _pack_f32_bits(bits)
        result = sanitize_signal_float(val, fail_secure_default=100.0)
        assert 0.0 <= result <= 100.0
        passed += 1

    return {"total": passed + failed, "passed": passed, "failed": failed}

The battery covers Quiet NaNs (0x7FC00000), Signaling NaNs (0x7FBFFFFF), Negative Quiet NaNs (0xFFC00000), infinities (±∞\pm\infty), and subnormal bit patterns (0x00000001, 0x007FFFFF, 0x80000001).

Criterion Benchmark Regression Gate

CriterionRunner parses target/criterion/.../estimates.json and checks the in_place_select_nth result against the 7.66 ns reference baseline from the 16-item in_place_select_nth_boundary_16 benchmark in ingest_benchmark.rs (failing above 8.43 ns, a 10% tolerance; when Criterion output isn’t on disk, it falls back to those two offline reference constants):

16-Item Slice Method (ingest_benchmark.rs)Latency (p50)Heap AllocationCache Lines (200-item full array)L1D OccupancyAllocator Lock Impact
Heap Vector (heap_allocated_vec_boundary_16)29.74 nsDynamic275 lines (17,600 B)53.7% of 32 KBAllocates and drops Vec
In-Place Partition (in_place_select_nth_boundary_16)7.66 ns0 B25 lines (1,600 B)4.8% of 32 KBZero allocator invocations
Delta3.88x faster100% eliminated90.9% fewerFits in L1DDeterministic stack execution

Because REGRESSION_THRESHOLD = 1.10, any PR pushing median in_place_select_nth past 8.43 ns trips the gate before lockfile signing:

CriterionRunner Regression Gate (Python)
# stokes/harness/criterion_runner.py
class CriterionRunner:
    REFERENCE_INPLACE_NS = 7.66
    REFERENCE_HEAP_NS = 29.74
    REGRESSION_THRESHOLD = 1.10  # 10% tolerance

    def run(self) -> dict[str, Any]:
        inplace_ns = self._parse_criterion_bench("in_place_select_nth")
        speedup = self.REFERENCE_HEAP_NS / inplace_ns
        regression = inplace_ns > (self.REFERENCE_INPLACE_NS * self.REGRESSION_THRESHOLD)
        return {
            "inplace_ns": inplace_ns,
            "heap_ns": self.REFERENCE_HEAP_NS,
            "speedup": speedup,
            "regression": regression,
        }

RFC-2439 BGP Route Flap Dampening (RFD) Simulator

When an edge proxy crashes from an unhandled slice overflow, listening sockets drop and local BGP daemons withdraw Anycast prefixes from Tier-1 transit carriers (such as AS3356, AS1299, or AS2914). Each flap adds penalty points that decay exponentially over a 15-minute half-life:

P(t)=P(0)⋅2−t/thalfP(t) = P(0) \cdot 2^{-t / t_{\text{half}}}

State ParameterThreshold ValueCarrier Action & Impact
Withdrawal Penalty (PwithdrawP_{\text{withdraw}})1,000 points per flapAdded immediately on prefix withdrawal or link drop
Exponential Half-Life (thalft_{\text{half}})15 minutes (900 s)Exponential penalty decay rate
Suppression Ceiling (PsuppressP_{\text{suppress}})2,000 pointsPrefix suppressed from global routing tables for 15 to 30 minutes
Reuse Threshold (PreuseP_{\text{reuse}})750 pointsRoute un-suppressed once decayed below threshold

Three Protective Traffic-Steering Tiers

ChaosEngine validates that faults remain isolated without reaching carrier route dampening (P<1,500P < 1,500):

  1. Tier 1: In-Memory L7 Degradation: Dual-Zone select_nth_unstable_by sheds excess low-priority fields in-place and ArcSwap rolls back corrupt updates without touching BGP routes.
  2. Tier 2: Local L4 Draining: Host failures trip /healthz so L4 balancers (Maglev/Unimog) drain flows locally without withdrawing Anycast prefixes.
  3. Tier 3: Controlled POP Evacuation: Scheduled maintenance triggers AS-Path prepends or RFC 8326 graceful shutdown within the simulated penalty budget.
ChaosEngine BGP Flap Simulator (Python)
# stokes/harness/chaos_engine.py
class ChaosEngine:
    BGP_WITHDRAW_PENALTY = 1000
    BGP_SUPPRESS_THRESHOLD = 2000
    BGP_REUSE_THRESHOLD = 750
    BGP_HALFLIFE_SECONDS = 900

    def simulate_bgp_route_flap(self, prefix: str = "198.51.100.0/24") -> BGPFlapEvent:
        self._bgp_penalty += self.BGP_WITHDRAW_PENALTY
        is_suppressed = self._bgp_penalty >= self.BGP_SUPPRESS_THRESHOLD
        return BGPFlapEvent(
            prefix=prefix,
            as_path=["AS13335", "AS3356"],
            penalty_points=int(self._bgp_penalty),
            suppressed=is_suppressed,
            flap_count=len(self._bgp_events) + 1,
        )

Verification Guarantees Summary

Invariant SubsystemVerification ToolingAcceptance Criteria
Float Sanitizationfloat_fuzz_battery.py (10,000 cases)100% fail-secure to 100.0; zero NaN bypasses
16-Item Partition Gatecriterion_runner.py (Criterion JSON)<= 8.43 ns (10% over 7.66 ns 16-item baseline); 0 B heap allocation
Carrier BGP Stabilitychaos_engine.py (RFC-2439 simulator)Simulated RFD penalty < 1,500; zero route dampening
Schema Boundsstokes verify --strict (AST engine)Emitted column count fits downstream buffer capacity

See Cloudflame Case Study for the full incident benchmark and Verification Latency & Memory Benchmarks for Criterion measurements.

Search wiki and portfolio

type to search across all entries.