"""Tests on Lab 07's setup and recorded runs (30–31 October 2026, Apple M4 Max, Docker Desktop with
16 vCPU, HAProxy 3.2): 02_algorithms.py (four servers with 4 slots and 10 ms of work each, s2 five
times slower; then equal servers with uneven requests) and 01_proxy_overhead.py Exercise 3 (2,000
keep-alive requests through L4 and L7). The simulation tests use seed 0; the lab's own simulation
(numpy, median of 5 seeds) predicted the same shapes: s2 share 25% / 9.8% / 10.8% at 400 req/s.
Run: pytest test_balance_practice.py"""
import random

from balance_practice import (backlog_wait_s, capacity_rps, imbalance, p99_by_kind, percentile, pick,
                              simulate, slow_server_sets_p99, spread, summarize)

SLOW = (1, 5, 1, 1)  # s2 is 5× slower


def test_capacity():
    assert capacity_rps(4, 10, (1, 1, 1, 1)) == 1600
    assert capacity_rps(4, 10, SLOW) == 1280  # 400 + 80 + 400 + 400
    assert round(capacity_rps(4, 10, (5,))) == 80  # the slow server alone


def test_backlog_wait():
    # Round robin sends s2 a quarter: 100 req/s at 400, 200 at 800. It serves 80. 20 s runs.
    assert backlog_wait_s(100, 80, 20) == 5.0  # measured p99: 5.4 s
    assert backlog_wait_s(200, 80, 20) == 30.0  # measured p99: 30.8 s
    assert backlog_wait_s(39, 80, 20) == 0.0  # least connections sent it about 39 a second


def test_pick_round_robin_takes_turns():
    state, rng = {"next": 0}, random.Random(0)
    picks = [pick("round_robin", [0, 9, 0, 0], state, rng) for _ in range(8)]
    assert picks == [0, 1, 2, 3, 0, 1, 2, 3]  # ignores the 9 requests piled up at s2


def test_pick_least_conn():
    state, rng = {"next": 0}, random.Random(0)
    assert pick("least_conn", [3, 1, 2, 2], state, rng) == 1
    assert state["next"] == 2
    # A tie: scan from the pointer, so ties rotate instead of always going to the first server.
    assert pick("least_conn", [1, 1, 1, 1], state, rng) == 2
    assert pick("least_conn", [1, 1, 0, 1], {"next": 3}, rng) == 2


def test_pick_random_and_p2c():
    rng = random.Random(1)
    seen = {pick("random", [0, 0, 0, 0], {"next": 0}, rng) for _ in range(200)}
    assert seen == {0, 1, 2, 3}
    rng = random.Random(2)
    inflight = [0, 50, 0, 0]
    picks = [pick("p2c", inflight, {"next": 0}, rng) for _ in range(600)]
    # s2 is picked only if both draws are s2, which can't happen: the two draws differ.
    assert 1 not in picks
    rng = random.Random(3)
    picks = [pick("p2c", [5, 6, 7, 8], {"next": 0}, rng) for _ in range(600)]
    assert 3 not in picks  # the busiest of four always loses its comparison


def test_round_robin_collapses_at_31_percent():
    r = summarize(simulate(400, SLOW, "round_robin", seed=0), slow_index=1)
    assert abs(r["slow_share"] - 0.25) < 0.005  # a quarter, whatever happens to s2
    assert r["p99_ms"] > 3000  # the lab: 5,039 ms simulated, 5,433 ms on HAProxy


def test_least_conn_and_p2c_survive():
    lc = summarize(simulate(400, SLOW, "least_conn", seed=0), slow_index=1)
    p2c = summarize(simulate(400, SLOW, "p2c", seed=0), slow_index=1)
    assert 0.08 < lc["slow_share"] < 0.12  # the lab: 9.8%
    assert 0.08 < p2c["slow_share"] < 0.14  # the lab: 10.8% simulated, 12.8% on HAProxy
    assert 49 < lc["p99_ms"] < 70  # the lab: 50 simulated, 53 on HAProxy
    assert 49 < p2c["p99_ms"] < 70


def test_random_is_worse_than_round_robin_at_light_load():
    rr = summarize(simulate(200, SLOW, "round_robin", seed=0), slow_index=1)
    rnd = summarize(simulate(200, SLOW, "random", seed=0), slow_index=1)
    assert rnd["p99_ms"] > rr["p99_ms"] + 15  # the lab: 89 vs. 57 ms on HAProxy


def test_percentile():
    assert abs(percentile(list(range(1, 101)), 99) - 99.01) < 1e-9
    assert percentile([3, 1, 2], 50) == 2
    assert percentile([10], 99) == 10


def test_slow_server_sets_p99():
    # Even the best policies sent s2 8–16% of requests; each takes 50 ms.
    assert slow_server_sets_p99(0.082)  # least connections at 800 req/s
    assert slow_server_sets_p99(0.156)  # two choices at 200 req/s
    assert not slow_server_sets_p99(0.005)  # below 1%: out of p99
    assert slow_server_sets_p99(0.005, q=99.9)  # but still in p99.9


def test_p99_by_kind():
    # 95% quick (5 ms), 5% big (100 ms). Quick ones that waited behind a big one take 28 ms.
    lat = [5.0] * 930 + [28.0] * 20 + [100.0] * 50
    kinds = ["quick"] * 950 + ["big"] * 50
    p = p99_by_kind(lat, kinds)
    assert p["all"] == 100.0  # the big requests are the p99, whatever the balancer did
    assert p["big"] == 100.0
    assert p["quick"] == 28.0  # the quick ones show the waiting
    lat2 = [5.0] * 950 + [100.0] * 50
    assert p99_by_kind(lat2, kinds)["all"] == 100.0  # same overall p99 ...
    assert p99_by_kind(lat2, kinds)["quick"] == 5.0  # ... very different quick p99


def test_spread_l4_and_l7():
    # The recorded run: [0, 0, 0, 2000] and [998, 1002, 0, 0] through L4 (HAProxy's pointer had
    # moved on, so which server gets the bus differs); [500, 500, 500, 500] through L7.
    assert sorted(spread(2000, 1, "L4")) == [0, 0, 0, 2000]
    assert sorted(spread(2000, 2, "L4")) == [0, 0, 1000, 1000]
    assert spread(2000, 4, "L4") == [500, 500, 500, 500]
    for conns in (1, 2, 4, 16):
        assert spread(2000, conns, "L7") == [500, 500, 500, 500]


def test_imbalance():
    assert imbalance([0, 0, 0, 2000]) == 4.0
    assert imbalance([998, 1002, 0, 0]) == 2.004
    assert round(imbalance([499, 505, 498, 498]), 2) == 1.01
    assert round(imbalance([499, 493, 493, 515]), 2) == 1.03
