"""Tests on Lab 08's logic and recorded runs (31 October 2026, Apple M4 Max, Docker Desktop with
16 vCPU): 03_staleness.py (8 readers, one item, Redis in front of Postgres) and 05_cdn.py (two
Varnish caches as CDN edges). The timelines are the lab's own staleness tests; the counts are
the recorded results.
Run: pytest test_stale_practice.py"""
from stale_practice import (fill, origin_share, percentile, read_cached, revalidation_share, stale_windows,
                            summarize, worst_case_stale_s)


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


def test_no_stale_reads():
    assert stale_windows([(1.1, 1), (1.2, 1), (2.1, 2)], [(1.0, 1), (2.0, 2)]) == [0.0, 0.0]


def test_window_is_last_stale_read_after_the_confirmation():
    # v2 confirmed at 2.0; reads sent at 2.1 and 2.5 still got v1; the read at 2.6 got v2
    w = stale_windows([(2.1, 1), (2.5, 1), (2.6, 2)], [(2.0, 2)])
    assert close(w[0], 0.5)


def test_reads_sent_before_the_confirmation_are_not_stale():
    assert stale_windows([(1.9, 1)], [(2.0, 2)]) == [0.0]


def test_a_newer_version_is_fresh_for_an_older_write():
    assert stale_windows([(2.2, 3)], [(2.0, 2), (2.1, 3)]) == [0.0, 0.0]


def test_percentile_is_linear():
    assert percentile([0.0, 1.0], 50) == 0.5
    assert percentile([3.0, 1.0, 2.0], 50) == 2.0
    assert close(percentile([0.0, 10.0], 99), 9.9)


def test_summarize_counts_zeros():
    # 80 changes with a slow copy: 10 went stale, the rest had a window of 0, so the median is 0
    windows = [0.0] * 70 + [0.30] * 9 + [0.325]
    s = summarize(windows)
    assert s["writes"] == 80 and s["writes_with_stale"] == 10
    assert s["p50_ms"] == 0
    assert close(s["max_ms"], 325.0, 1e-6)


def test_wipe_first_copies_the_old_price_back():
    # The planted bug: wipe, a reader misses and reads the old row, copies it up, then the change lands.
    board, book = {"item:7": {"version": 7}}, {"version": 7}
    board.pop("item:7")                                   # 1. wipe first
    assert read_cached(board, "item:7") is None          # 2. a reader misses...
    old = dict(book)                                     #    ...and reads the book: still v7
    fill(board, "item:7", old, guarded=False)            # 3. copies v7 back up
    book["version"] = 8                                  # 4. the change is saved
    assert read_cached(board, "item:7")["version"] == 7  # old until the timer runs out


def test_slow_copy_overwrites_write_through_unless_guarded():
    for guarded, expect in ((False, 7), (True, 8)):
        board = {}
        late = {"version": 7}                                       # reader A read v7, then paused
        board["item:7"] = {"version": 8}                            # writer: change, then write v8
        written = fill(board, "item:7", late, guarded=guarded)     # A's late copy
        assert written is (not guarded)
        assert board["item:7"]["version"] == expect


def test_tombstone_with_guarded_fill():
    board = {"item:7": {"min_version": 8}}             # instead of wiping: "v8 or newer only"
    assert read_cached(board, "item:7") is None         # readers treat the note as a miss
    assert fill(board, "item:7", {"version": 7}, guarded=True) is False   # the late v7 is refused
    assert fill(board, "item:7", {"version": 8}, guarded=True) is True    # v8 gets in
    assert read_cached(board, "item:7") == {"version": 8}


def test_guarded_fill_without_anything_to_compare():
    # After a plain wipe there's nothing to compare against, so even a guarded fill writes v7.
    board = {}
    assert fill(board, "item:7", {"version": 7}, guarded=True) is True


def test_origin_share_recorded():
    assert origin_share(30181, 0, 30181) == 1.0                         # no-store
    assert round(origin_share(6427, 10971, 30195), 3) == 0.576          # max-age=1
    assert round(origin_share(6451, 5287, 29871), 3) == 0.393           # max-age=5 with ETag
    assert round(origin_share(11738, 0, 29871), 3) == 0.393             # max-age=5, no ETag: same share
    assert round(origin_share(6372, 0, 29783), 3) == 0.214              # max-age=30


def test_revalidation_share_recorded():
    assert round(revalidation_share(6427, 10971), 2) == 0.63            # max-age=1: 63% were 304s
    assert round(revalidation_share(6451, 5287), 2) == 0.45             # max-age=5: 45%
    assert revalidation_share(6372, 0) == 0.0                           # max-age=30: no refetches
    assert revalidation_share(0, 0) == 0.0


def test_worst_case_is_the_timer():
    assert worst_case_stale_s(10, purge_arrived=True) == 0
    assert worst_case_stale_s(10, purge_arrived=False) == 10   # edge2's lost purge: 9,997 ms at the median
    assert worst_case_stale_s(2, purge_arrived=False, grace_s=10) == 12   # stale-while-revalidate=10 on top
