Homework · Runs in your browser

The system design toolkit: percentiles, capacity, latency paths, recall and NDCG, two-stage ranking, cache and batching

Build the calculators you would reach for in an ML system design round, with nothing but the standard library: a nearest-rank percentile, a Little’s-law server count, the latency of a request path with parallel calls, cost per million requests, recall@k and NDCG@k, a two-stage ranker, an LRU cache hit-rate simulator, batch latency and throughput, the best batch under a latency cap, and a timeout with a fallback. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest. Every function has its rules in the docstring.

Hints:

  • Percentile: nearest rank is the value at position ceil(p / 100 x n) in the sorted list, counting from 1. Check: for 1 to 10, p90 is 9 and p95 is 10. Floating-point products such as 0.7 x 10 can land just above 7, so a rank that should be exactly 7 must not become 8.
  • Servers: in flight = qps x latency, and each server carries concurrency x target utilisation. Round up the number of servers, but do not let float noise turn an exact 7 into 8. Check: 400 qps, 0.05 s, 4 at once, 50% load gives 10.
  • Path latency: steps add, calls inside a list run in parallel and cost their maximum. Check: [5, [10, 20], 3] is 28.
  • Recall@k divides by the number of relevant items, not by k, and counts a repeated item once. If nothing is relevant, return 0.0.
  • NDCG@k: DCG sums gain / log2(rank + 1) with rank starting at 1. The ideal sorts all the gains, not only the ones you ranked. An item missing from the gains has gain 0 but still uses up a slot. If the ideal is 0, return 0.0. Check: ranking gains (1, 3) in that order gives about 0.7967.
  • Two-stage: only the first n_candidates are scored at all. Sort by score from high to low and break ties by the retriever’s order. Check: an item outside the candidates can never appear, however high its score.
  • LRU: a hit also refreshes the key. When the cache is over capacity, drop the key used least recently. Check: [“a”, “b”, “a”, “c”, “a”] with capacity 2 has 2 hits in 5 requests.
  • Batch: latency = fixed + per_item x batch. The best batch is the largest that fits the cap, and the cap is inclusive. Check: fixed 8 ms, 0.5 ms per item, cap 20 ms gives 24.
  • Timeout: a call at exactly the timeout is not cut. A cut call is served at timeout + fallback.
  • Try it: change the funnel in the lesson script to pass 100 candidates and predict the recall before you run it.

Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.

Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.

Show a solution

Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.

import math
from collections import OrderedDict


def percentile(values, p):
    """Nearest-rank percentile: sort, take the value at rank ceil(p / 100 * n), counting from 1.

    p must satisfy 0 < p <= 100 and values must not be empty, otherwise ValueError.
    The input list is not changed.
    """
    if len(values) == 0:
        raise ValueError("percentile of an empty list")
    if not 0 < p <= 100:
        raise ValueError("p must satisfy 0 < p <= 100")
    s = sorted(values)
    rank = max(1, math.ceil(p / 100 * len(s) - 1e-9))
    return s[rank - 1]


def servers_needed(qps, latency_s, concurrency, target_util):
    """Servers needed to carry qps requests per second at an average latency of latency_s.

    Little's law: requests in flight = qps x latency_s. One server handles `concurrency`
    requests at once but is only loaded to target_util (0 < target_util <= 1) of that.
    Return the smallest whole number of servers, and at least 1 for any qps > 0 (0 for qps == 0).
    Negative qps or latency, concurrency < 1, or target_util outside (0, 1] raise ValueError.
    """
    if qps < 0 or latency_s < 0 or concurrency < 1 or not 0 < target_util <= 1:
        raise ValueError("bad capacity inputs")
    if qps == 0:
        return 0
    in_flight = qps * latency_s
    return max(1, math.ceil(in_flight / (concurrency * target_util) - 1e-9))


def path_latency(stages):
    """Latency of a request path in ms.

    stages is a list. Each item is either a number (a step run alone) or a list of numbers
    (calls run in parallel, which cost the slowest of them). Steps run one after another and
    their costs add. An empty parallel list costs 0. A negative number raises ValueError.
    """
    total = 0.0
    for st in stages:
        group = st if isinstance(st, (list, tuple)) else [st]
        if any(g < 0 for g in group):
            raise ValueError("negative latency")
        total += max(group) if len(group) else 0.0
    return total


def cost_per_million_requests(servers, price_per_hour, qps):
    """Dollars to serve one million requests: servers x price_per_hour / (qps x 3600) x 1e6.

    qps must be positive, servers and price must not be negative; otherwise ValueError.
    """
    if qps <= 0 or servers < 0 or price_per_hour < 0:
        raise ValueError("bad cost inputs")
    return servers * price_per_hour / (qps * 3600) * 1_000_000


def recall_at_k(ranked, relevant, k):
    """Share of the relevant items that appear in the first k entries of ranked.

    Duplicates in ranked count once. If relevant is empty return 0.0. k < 1 raises ValueError.
    k larger than the list simply uses the whole list.
    """
    if k < 1:
        raise ValueError("k must be at least 1")
    rel = set(relevant)
    if not rel:
        return 0.0
    return len(set(ranked[:k]) & rel) / len(rel)


def ndcg_at_k(ranked, gains, k):
    """NDCG@k with linear gain and a log2 discount.

    gains maps item -> gain (an item that is missing has gain 0). DCG sums gain / log2(rank + 1)
    over the first k entries of ranked (rank starts at 1). The ideal DCG sorts all gains in
    gains from high to low and takes the first k. Return DCG / ideal, or 0.0 when the ideal is 0.
    A repeated item counts once, at its first position. k < 1 raises ValueError.
    """
    if k < 1:
        raise ValueError("k must be at least 1")
    seen = set()
    dcg = 0.0
    for i, item in enumerate(ranked[:k]):
        if item in seen:
            continue
        seen.add(item)
        dcg += gains.get(item, 0) / math.log2(i + 2)
    ideal_gains = sorted(gains.values(), reverse=True)[:k]
    ideal = sum(g / math.log2(i + 2) for i, g in enumerate(ideal_gains))
    return dcg / ideal if ideal > 0 else 0.0


def two_stage(retrieved, scores, n_candidates, k):
    """Two-stage ranking.

    Keep the first n_candidates of retrieved (the retriever's order), score each with
    scores[item], sort by score from high to low, and return the first k. Ties keep the
    retriever's order. An item with no entry in scores is not allowed (KeyError is fine).
    n_candidates and k must be at least 1, otherwise ValueError.
    """
    if n_candidates < 1 or k < 1:
        raise ValueError("n_candidates and k must be at least 1")
    cands = retrieved[:n_candidates]
    order = sorted(range(len(cands)), key=lambda i: (-scores[cands[i]], i))
    return [cands[i] for i in order[:k]]


def lru_hit_rate(requests, capacity):
    """Hit rate of a least-recently-used cache over a sequence of keys.

    A request is a hit when its key is in the cache; either way the key becomes the most
    recently used, and the oldest key is dropped when the cache is over capacity.
    Return hits / len(requests); 0.0 for no requests or capacity 0. capacity < 0 raises ValueError.
    """
    if capacity < 0:
        raise ValueError("capacity must not be negative")
    if len(requests) == 0 or capacity == 0:
        return 0.0
    cache = OrderedDict()
    hits = 0
    for key in requests:
        if key in cache:
            hits += 1
            cache.move_to_end(key)
        else:
            cache[key] = True
            if len(cache) > capacity:
                cache.popitem(last=False)
    return hits / len(requests)


def batch_stats(batch_size, fixed_ms, per_item_ms):
    """Latency and throughput of one batch: latency = fixed_ms + per_item_ms x batch_size.

    Return (latency_ms, items_per_second) where items_per_second = batch_size / latency x 1000.
    batch_size < 1 or a negative cost raises ValueError, as does a zero latency.
    """
    if batch_size < 1 or fixed_ms < 0 or per_item_ms < 0:
        raise ValueError("bad batch inputs")
    latency = fixed_ms + per_item_ms * batch_size
    if latency <= 0:
        raise ValueError("latency must be positive")
    return latency, batch_size / latency * 1000


def best_batch_size(max_batch, fixed_ms, per_item_ms, latency_cap_ms):
    """Largest batch size from 1 to max_batch whose batch latency is at most latency_cap_ms.

    Return 0 when even a batch of 1 is too slow. max_batch < 1 raises ValueError.
    """
    if max_batch < 1:
        raise ValueError("max_batch must be at least 1")
    best = 0
    for b in range(1, max_batch + 1):
        latency, _ = batch_stats(b, fixed_ms, per_item_ms)
        if latency <= latency_cap_ms + 1e-9:
            best = b
    return best


def timeout_fallback(latencies, timeout_ms, fallback_ms):
    """Apply a timeout with a fallback to a list of model latencies.

    A call with latency <= timeout_ms is served at that latency. A slower call is cut at
    timeout_ms and then the fallback runs, so it is served at timeout_ms + fallback_ms.
    Return (served_latencies, fallback_rate). Empty input gives ([], 0.0). Negative values
    raise ValueError.
    """
    if timeout_ms < 0 or fallback_ms < 0 or any(x < 0 for x in latencies):
        raise ValueError("negative latency")
    if len(latencies) == 0:
        return [], 0.0
    served, used = [], 0
    for x in latencies:
        if x <= timeout_ms:
            served.append(x)
        else:
            served.append(timeout_ms + fallback_ms)
            used += 1
    return served, used / len(latencies)
Show the tests (test_starter.py)

Python

import math

import pytest

from starter import (
    batch_stats,
    best_batch_size,
    cost_per_million_requests,
    lru_hit_rate,
    ndcg_at_k,
    path_latency,
    percentile,
    recall_at_k,
    servers_needed,
    timeout_fallback,
    two_stage,
)


def close(a, b, tol=1e-9):
    return abs(a - b) <= tol


# ---- percentile --------------------------------------------------------------


def test_percentile_uses_nearest_rank():
    vals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    assert percentile(vals, 50) == 5
    assert percentile(vals, 90) == 9
    assert percentile(vals, 95) == 10
    assert percentile(vals, 100) == 10
    assert percentile(vals, 10) == 1
    assert percentile(vals, 11) == 2


def test_percentile_survives_float_rounding_at_exact_ranks():
    vals = list(range(1, 11))
    assert percentile(vals, 70) == 7
    assert percentile(vals, 30) == 3
    hundred = list(range(1, 101))
    for p in (7, 14, 28, 29, 57, 58):
        assert percentile(hundred, p) == p


def test_percentile_sorts_and_does_not_change_the_input():
    vals = [9, 1, 5, 3, 7]
    assert percentile(vals, 50) == 5
    assert percentile(vals, 100) == 9
    assert percentile(vals, 20) == 1
    assert vals == [9, 1, 5, 3, 7]


def test_percentile_small_inputs_and_duplicates():
    assert percentile([42], 1) == 42
    assert percentile([42], 100) == 42
    assert percentile([42], 0.0000001) == 42
    assert percentile([1, 2], 0.000000001) == 1
    assert percentile([3, 3, 3], 50) == 3
    assert percentile([1, 100], 50) == 1
    assert percentile([1, 100], 51) == 100
    assert percentile([5, 1, 5, 1], 75) == 5
    assert percentile([5, 1, 5, 1], 50) == 1


def test_percentile_tail_is_larger_than_the_mean():
    vals = [10] * 99 + [1000]
    assert percentile(vals, 99) == 10
    assert percentile(vals, 100) == 1000
    assert sum(vals) / len(vals) > 10


def test_percentile_validation():
    for bad in (0, -5, 100.5, 101):
        with pytest.raises(ValueError):
            percentile([1, 2, 3], bad)
    with pytest.raises(ValueError):
        percentile([], 50)


# ---- servers_needed ----------------------------------------------------------


def test_servers_needed_littles_law():
    assert servers_needed(100, 0.06, 8, 0.5) == 2
    assert servers_needed(694.4, 0.06, 8, 0.5) == 11
    assert servers_needed(1000, 0.1, 10, 1.0) == 10
    assert servers_needed(1000, 0.1, 10, 0.5) == 20


def test_servers_needed_rounds_up_but_not_on_float_noise():
    assert servers_needed(30, 0.1, 1, 1) == 3
    assert servers_needed(100, 0.07, 1, 1) == 7
    assert servers_needed(31, 0.1, 1, 1) == 4
    assert servers_needed(3, 1, 1, 1) == 3
    assert servers_needed(7, 1, 2, 1) == 4
    assert servers_needed(8, 1, 2, 1) == 4


def test_servers_needed_at_least_one_when_there_is_traffic():
    assert servers_needed(0.001, 0.001, 100, 1.0) == 1
    assert servers_needed(0, 0.1, 4, 0.5) == 0
    assert servers_needed(5, 0, 4, 0.5) == 1


def test_servers_needed_moves_the_right_way():
    base = servers_needed(500, 0.08, 4, 0.6)
    assert servers_needed(1000, 0.08, 4, 0.6) > base
    assert servers_needed(500, 0.16, 4, 0.6) > base
    assert servers_needed(500, 0.08, 8, 0.6) < base
    assert servers_needed(500, 0.08, 4, 0.3) > base
    assert base == 17


def test_servers_needed_validation():
    bad = [(-1, 0.1, 1, 1), (1, -0.1, 1, 1), (1, 0.1, 0, 1), (1, 0.1, 1, 0), (1, 0.1, 1, 1.01), (1, 0.1, 1, -0.5)]
    for args in bad:
        with pytest.raises(ValueError):
            servers_needed(*args)


# ---- path_latency ------------------------------------------------------------


def test_path_latency_adds_steps_and_takes_the_max_of_parallel_calls():
    assert close(path_latency([5, [10, 20], 3]), 28.0)
    assert close(path_latency([5, 10, 20]), 35.0)
    assert close(path_latency([[5, 10, 20]]), 20.0)
    assert close(path_latency([[4, 9], [7, 2]]), 16.0)


def test_path_latency_edge_cases():
    assert path_latency([]) == 0
    assert path_latency([[]]) == 0
    assert close(path_latency([[], 5]), 5.0)
    assert close(path_latency([(3, 8), 2]), 10.0)
    assert close(path_latency([[7]]), 7.0)
    assert close(path_latency([0, [0, 0]]), 0.0)


def test_path_latency_validation():
    with pytest.raises(ValueError):
        path_latency([5, -1])
    with pytest.raises(ValueError):
        path_latency([[3, -2]])


# ---- cost --------------------------------------------------------------------


def test_cost_per_million_requests():
    assert close(cost_per_million_requests(1, 3.6, 1.0), 1000.0)
    assert close(cost_per_million_requests(10, 0.36, 100.0), 10.0)
    assert close(cost_per_million_requests(2, 1.0, 50.0), 2 / (50 * 3600) * 1e6)
    assert close(cost_per_million_requests(0, 1.0, 10.0), 0.0)
    assert close(cost_per_million_requests(4, 0.0, 10.0), 0.0)


def test_cost_per_million_requests_scales_with_servers_and_traffic():
    a = cost_per_million_requests(5, 2.0, 100.0)
    assert close(cost_per_million_requests(10, 2.0, 100.0), 2 * a)
    assert close(cost_per_million_requests(5, 2.0, 200.0), a / 2)
    assert close(cost_per_million_requests(5, 4.0, 100.0), 2 * a)


def test_cost_per_million_requests_validation():
    for args in ((1, 1, 0), (1, 1, -3), (-1, 1, 5), (1, -1, 5)):
        with pytest.raises(ValueError):
            cost_per_million_requests(*args)


# ---- recall_at_k -------------------------------------------------------------


def test_recall_at_k_counts_relevant_items_in_the_top_k():
    ranked = ["a", "b", "c", "d", "e"]
    assert close(recall_at_k(ranked, ["a", "e"], 1), 0.5)
    assert close(recall_at_k(ranked, ["a", "e"], 4), 0.5)
    assert close(recall_at_k(ranked, ["a", "e"], 5), 1.0)
    assert close(recall_at_k(ranked, ["b"], 1), 0.0)
    assert close(recall_at_k(ranked, ["b"], 2), 1.0)
    assert close(recall_at_k(ranked, ["a", "b", "z"], 2), 2 / 3)


def test_recall_at_k_divides_by_all_relevant_items_not_by_k():
    assert close(recall_at_k(["a", "b", "c"], ["a", "x", "y", "z"], 3), 0.25)
    assert close(recall_at_k(["a", "b", "c"], ["a"], 3), 1.0)


def test_recall_at_k_edge_cases():
    assert recall_at_k([], ["a"], 5) == 0.0
    assert recall_at_k(["a"], [], 5) == 0.0
    assert recall_at_k([], [], 3) == 0.0
    assert close(recall_at_k(["a", "b"], ["a", "b"], 100), 1.0)
    assert close(recall_at_k(["a", "a", "a"], ["a", "b"], 3), 0.5)
    assert close(recall_at_k(["a", "a", "b"], ["a", "b"], 2), 0.5)
    assert close(recall_at_k(["a", "b"], ["a", "a"], 1), 1.0)
    assert close(recall_at_k(("a", "b"), ("b",), 2), 1.0)


def test_recall_at_k_grows_with_k_and_validates():
    ranked = list(range(20))
    rel = [3, 8, 15]
    values = [recall_at_k(ranked, rel, k) for k in range(1, 22)]
    assert values == sorted(values)
    assert close(values[-1], 1.0)
    for k in (0, -1):
        with pytest.raises(ValueError):
            recall_at_k(ranked, rel, k)


# ---- ndcg_at_k ---------------------------------------------------------------


def test_ndcg_hand_computed_value():
    gains = {"a": 1, "b": 3}
    dcg = 1 / 1 + 3 / math.log2(3)
    ideal = 3 / 1 + 1 / math.log2(3)
    assert close(ndcg_at_k(["a", "b"], gains, 2), dcg / ideal)
    assert close(ndcg_at_k(["b", "a"], gains, 2), 1.0)


def test_ndcg_discount_is_log2_of_rank_plus_one():
    gains = {"x": 1}
    assert close(ndcg_at_k(["x"], gains, 1), 1.0)
    assert close(ndcg_at_k(["y", "x"], gains, 2), 1 / math.log2(3))
    assert close(ndcg_at_k(["y", "z", "x"], gains, 3), 1 / math.log2(4))
    assert close(ndcg_at_k(["y", "z", "w", "x"], gains, 4), 1 / math.log2(5))


def test_ndcg_k_cuts_both_the_list_and_the_ideal():
    gains = {"a": 3, "b": 2, "c": 1}
    assert close(ndcg_at_k(["c", "b", "a"], gains, 1), 1 / 3)
    dcg2 = 1 + 2 / math.log2(3)
    ideal2 = 3 + 2 / math.log2(3)
    assert close(ndcg_at_k(["c", "b", "a"], gains, 2), dcg2 / ideal2)
    assert close(ndcg_at_k(["a", "b", "c"], gains, 2), 1.0)
    assert close(ndcg_at_k(["a", "b", "c"], gains, 50), 1.0)


def test_ndcg_unknown_items_have_gain_zero_and_use_up_a_slot():
    gains = {"a": 2}
    assert close(ndcg_at_k(["q", "a"], gains, 2), 1 / math.log2(3))
    assert ndcg_at_k(["q", "r"], gains, 2) == 0.0
    assert ndcg_at_k([], gains, 3) == 0.0


def test_ndcg_with_no_relevant_items_is_zero_not_an_error():
    assert ndcg_at_k(["a", "b"], {}, 2) == 0.0
    assert ndcg_at_k(["a", "b"], {"a": 0, "b": 0}, 2) == 0.0


def test_ndcg_ideal_uses_all_gains_even_if_not_ranked():
    gains = {"a": 1, "b": 1, "c": 1}
    assert close(ndcg_at_k(["a"], gains, 3), 1 / (1 + 1 / math.log2(3) + 0.5))


def test_ndcg_repeated_item_counts_once():
    gains = {"a": 1, "b": 1}
    once = ndcg_at_k(["a", "x", "b"], gains, 3)
    twice = ndcg_at_k(["a", "a", "b"], gains, 3)
    assert close(twice, (1 + 1 / 2) / (1 + 1 / math.log2(3)))
    assert twice < 1.0
    assert once > 0


def test_ndcg_between_zero_and_one_and_validates():
    gains = {i: i % 4 for i in range(10)}
    for k in (1, 3, 10):
        v = ndcg_at_k(list(range(10)), gains, k)
        assert 0.0 <= v <= 1.0
    with pytest.raises(ValueError):
        ndcg_at_k(["a"], {"a": 1}, 0)


# ---- two_stage ---------------------------------------------------------------


def test_two_stage_reranks_the_candidates_by_the_second_score():
    retrieved = ["a", "b", "c", "d", "e"]
    scores = {"a": 0.1, "b": 0.9, "c": 0.5, "d": 0.99, "e": 0.7}
    assert two_stage(retrieved, scores, 3, 2) == ["b", "c"]
    assert two_stage(retrieved, scores, 5, 2) == ["d", "b"]
    assert two_stage(retrieved, scores, 5, 5) == ["d", "b", "e", "c", "a"]


def test_two_stage_items_outside_the_candidates_never_appear():
    retrieved = ["a", "b", "c", "d"]
    scores = {"a": 0, "b": 0, "c": 0, "d": 100}
    assert "d" not in two_stage(retrieved, scores, 3, 4)
    assert two_stage(retrieved, scores, 4, 1) == ["d"]


def test_two_stage_ties_keep_the_retriever_order():
    retrieved = ["p", "q", "r", "s"]
    scores = {"p": 1, "q": 1, "r": 2, "s": 1}
    assert two_stage(retrieved, scores, 4, 4) == ["r", "p", "q", "s"]
    assert two_stage(retrieved, scores, 4, 2) == ["r", "p"]


def test_two_stage_handles_counts_larger_than_the_list():
    retrieved = ["a", "b"]
    scores = {"a": 1, "b": 2}
    assert two_stage(retrieved, scores, 10, 10) == ["b", "a"]
    assert two_stage([], {}, 5, 5) == []


def test_two_stage_does_not_change_its_inputs_and_validates():
    retrieved = ["a", "b", "c"]
    scores = {"a": 3, "b": 2, "c": 1}
    two_stage(retrieved, scores, 3, 3)
    assert retrieved == ["a", "b", "c"]
    for n, k in ((0, 1), (1, 0), (-1, 2), (2, -1)):
        with pytest.raises(ValueError):
            two_stage(retrieved, scores, n, k)


def test_two_stage_recall_can_never_beat_the_candidate_list():
    retrieved = list(range(30))
    scores = {i: (i * 7) % 11 for i in retrieved}
    rel = [25, 27, 2]
    final = two_stage(retrieved, scores, 10, 10)
    assert recall_at_k(final, rel, 10) <= recall_at_k(retrieved, rel, 10)
    assert recall_at_k(two_stage(retrieved, scores, 30, 30), rel, 30) == 1.0


# ---- lru_hit_rate ------------------------------------------------------------


def test_lru_hit_rate_basic():
    assert close(lru_hit_rate(["a", "a", "a", "a"], 1), 0.75)
    assert close(lru_hit_rate(["a", "b", "a", "b"], 2), 0.5)
    assert close(lru_hit_rate(["a", "b", "c", "a", "b", "c"], 3), 0.5)
    assert close(lru_hit_rate(["a", "b", "c", "d"], 10), 0.0)


def test_lru_evicts_the_least_recently_used_key():
    assert close(lru_hit_rate(["a", "b", "c", "a"], 2), 0.0)
    assert close(lru_hit_rate(["a", "b", "a", "c", "a"], 2), 0.4)
    assert close(lru_hit_rate(["a", "b", "a", "c", "b"], 2), 0.2)
    assert close(lru_hit_rate(["a", "b", "c", "a", "b", "c"], 2), 0.0)


def test_lru_a_hit_refreshes_the_key():
    assert close(lru_hit_rate(["a", "b", "a", "c", "a", "d", "a"], 2), 3 / 7)
    assert close(lru_hit_rate(["a", "b", "a", "c", "b"], 2), 1 / 5)


def test_lru_capacity_edges():
    assert lru_hit_rate(["a", "a", "a"], 0) == 0.0
    assert lru_hit_rate([], 5) == 0.0
    assert lru_hit_rate([], 0) == 0.0
    assert close(lru_hit_rate(["a", "a"], 5), 0.5)
    assert close(lru_hit_rate(["a", "b", "a", "b", "a", "b"], 100), 4 / 6)
    with pytest.raises(ValueError):
        lru_hit_rate(["a"], -1)


def test_lru_a_larger_cache_never_hurts_on_a_cyclic_stream():
    stream = [i % 6 for i in range(60)]
    rates = [lru_hit_rate(stream, c) for c in range(1, 8)]
    assert rates == sorted(rates)
    assert rates[4] == 0.0
    assert close(rates[5], 54 / 60)
    assert close(rates[6], 54 / 60)


def test_lru_works_with_any_hashable_key():
    assert close(lru_hit_rate([(1, 2), (1, 2), "x", 5, 5], 3), 0.4)
    assert close(lru_hit_rate(list("abcabc"), 3), 0.5)


# ---- batching ----------------------------------------------------------------


def test_batch_stats_latency_and_throughput():
    lat, thr = batch_stats(16, 8, 0.5)
    assert close(lat, 16.0)
    assert close(thr, 1000.0)
    lat, thr = batch_stats(1, 8, 0.5)
    assert close(lat, 8.5)
    assert close(thr, 1000 / 8.5)
    lat, thr = batch_stats(64, 8, 0.5)
    assert close(lat, 40.0)
    assert close(thr, 1600.0)


def test_batch_stats_zero_fixed_cost_gives_constant_throughput():
    for b in (1, 2, 10):
        lat, thr = batch_stats(b, 0, 2.0)
        assert close(lat, 2.0 * b)
        assert close(thr, 500.0)


def test_batch_stats_zero_per_item_cost_scales_throughput_with_the_batch():
    lat, thr = batch_stats(10, 5.0, 0)
    assert close(lat, 5.0)
    assert close(thr, 2000.0)


def test_batch_stats_validation():
    for args in ((0, 1, 1), (-2, 1, 1), (1, -1, 1), (1, 1, -1), (3, 0, 0)):
        with pytest.raises(ValueError):
            batch_stats(*args)


def test_best_batch_size_is_the_largest_that_fits_the_cap():
    assert best_batch_size(100, 8, 0.5, 20) == 24
    assert best_batch_size(100, 8, 0.5, 20.4) == 24
    assert best_batch_size(100, 8, 0.5, 20.5) == 25
    assert best_batch_size(10, 8, 0.5, 1000) == 10
    assert best_batch_size(100, 8, 0.5, 8.5) == 1


def test_best_batch_size_nothing_fits():
    assert best_batch_size(100, 8, 0.5, 8.4) == 0
    assert best_batch_size(5, 50, 1, 10) == 0


def test_best_batch_size_float_cap_exactly_met():
    assert best_batch_size(50, 1.0, 0.1, 1.3) == 3
    assert best_batch_size(50, 0, 0.1, 0.3) == 3


def test_best_batch_size_validation():
    with pytest.raises(ValueError):
        best_batch_size(0, 1, 1, 10)


# ---- timeout and fallback ----------------------------------------------------


def test_timeout_fallback_serves_slow_calls_at_timeout_plus_fallback():
    served, rate = timeout_fallback([10, 20, 30, 200], 50, 5)
    assert served == [10, 20, 30, 55]
    assert close(rate, 0.25)


def test_timeout_fallback_a_call_exactly_at_the_timeout_is_not_cut():
    served, rate = timeout_fallback([50, 51], 50, 5)
    assert served == [50, 55]
    assert close(rate, 0.5)


def test_timeout_fallback_all_fast_and_all_slow():
    served, rate = timeout_fallback([1, 2, 3], 10, 5)
    assert served == [1, 2, 3]
    assert rate == 0.0
    served, rate = timeout_fallback([100, 200], 10, 5)
    assert served == [15, 15]
    assert rate == 1.0


def test_timeout_fallback_zero_fallback_cost_and_empty_input():
    served, rate = timeout_fallback([5, 500], 20, 0)
    assert served == [5, 20]
    assert close(rate, 0.5)
    assert timeout_fallback([], 10, 5) == ([], 0.0)


def test_timeout_fallback_does_not_change_the_input_and_validates():
    vals = [1, 99]
    timeout_fallback(vals, 10, 1)
    assert vals == [1, 99]
    for args in (([1], -1, 1), ([1], 1, -1), ([-1], 1, 1)):
        with pytest.raises(ValueError):
            timeout_fallback(*args)