"""Tests on Lab 09's logic and recorded runs (2 November 2026, Apple M4 Max, Docker Desktop with
16 vCPU, Postgres 18.6): 02_sync_replication.py (synchronous_commit levels; replica1 paused for
8 s) and 05_quorum.py (a 3-node quorum store with a 0-20 ms injected delay). The quorum checks
mirror the lab's own tests; the counts are the recorded results.
Run: pytest test_quorum_practice.py"""
from quorum_practice import (every_read_meets_every_write, first_k, longest_gap, newest, newest_acked, overlaps,
                             stale_reads, survives, wilson)


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


def raises(fn, exc):
    try:
        fn()
    except exc:
        return True
    return False


def test_overlaps_for_three_copies():
    assert overlaps(3, 2, 2) and overlaps(3, 1, 3) and overlaps(3, 3, 1)
    assert not overlaps(3, 1, 1) and not overlaps(3, 1, 2) and not overlaps(3, 2, 1)
    assert raises(lambda: overlaps(3, 0, 2), ValueError)
    assert raises(lambda: overlaps(3, 2, 4), ValueError)


def test_the_rule_matches_every_read_and_write_set_for_five_nodes():
    # the lab checks the same thing for N = 5
    for r in range(1, 6):
        for w in range(1, 6):
            assert every_read_meets_every_write(5, r, w) == overlaps(5, r, w), (r, w)


def test_newest_keeps_the_highest_version():
    assert newest([{"version": 1}, {"version": 3}, {"version": 2}])["version"] == 3
    assert newest([{"version": 2, "node": "a"}, {"version": 2, "node": "b"}])["node"] == "a"
    assert raises(lambda: newest([]), ValueError)


def test_first_k_takes_the_fastest():
    answers = [(0.03, True, "kv1"), (0.01, True, "kv2"), (0.02, True, "kv3")]
    assert first_k(answers, 1) == ["kv2"]
    assert first_k(answers, 2) == ["kv2", "kv3"]
    assert first_k(answers, 3) == ["kv2", "kv3", "kv1"]


def test_first_k_tolerates_failures_until_it_cant():
    one_down = [(0.001, False, None), (0.02, True, "kv2"), (0.03, True, "kv1")]
    assert first_k(one_down, 2) == ["kv2", "kv1"]
    # W = 3 with kv3 stopped: fails as soon as kv3's error comes back, without waiting for the others
    assert raises(lambda: first_k(one_down, 3), RuntimeError)
    two_down = [(0.01, False, None), (0.01, False, None), (0.02, True, "kv1")]
    assert raises(lambda: first_k(two_down, 2), RuntimeError)


def test_newest_acked_ignores_failed_and_later_writes():
    writes = [(1.0, 1, True), (2.0, 2, True), (2.5, 3, False), (3.0, 4, True)]
    assert newest_acked([0.5, 1.0, 2.7, 3.5], writes) == [-1, 1, 2, 4]


def test_stale_reads_r1_w1_style():
    # v2 is confirmed by one node at 2.0; a read at 2.1 asks a node that doesn't have it yet
    writes = [(1.0, 1, True), (2.0, 2, True)]
    reads = [(1.5, 1), (2.1, 1), (2.2, 2), (1.9, 1)]
    assert stale_reads(reads, writes) == 1


def test_no_confirmed_write_means_no_answer_not_zero():
    # W = 3 with a node down: 725 saves, none confirmed, but the live nodes stored them anyway
    writes = [(0.01 * i, i, False) for i in range(1, 726)]
    reads = [(1.0, 90), (2.0, 190)]
    assert stale_reads(reads, writes) is None


def test_wilson_matches_the_recorded_intervals():
    lo, hi = wilson(3338, 14600)                    # R = 1, W = 1: 22.9% stale
    assert close(lo, 0.22188999564417325) and close(hi, 0.23551304822340743)
    lo, hi = wilson(689, 14579)                     # R = 1, W = 2: 4.7%
    assert close(lo, 0.04393292093630828) and close(hi, 0.050825126768193965)
    lo, hi = wilson(0, 16136)                       # R = 2, W = 2: none, but not "never"
    assert lo == 0.0 and close(hi, 0.0002380196841584864)
    assert raises(lambda: wilson(1, 0), ValueError) and raises(lambda: wilson(5, 4), ValueError)


def test_which_settings_survive_one_node_down():
    # recorded with kv3 stopped: R1W1 and R2W2 kept both; W = 3 confirmed 0 of 725; R = 3 answered 0 of 4,220
    assert survives(2, 1, 1) == {"writes": True, "reads": True}
    assert survives(2, 2, 2) == {"writes": True, "reads": True}
    assert survives(2, 1, 3) == {"writes": False, "reads": True}
    assert survives(2, 3, 1) == {"writes": True, "reads": False}
    assert survives(3, 3, 3) == {"writes": True, "reads": True}


def test_longest_gap_is_the_freeze():
    # four writers; replica1 paused: the four commits in flight finish together 8.1 s later
    ends = [0.1, 0.2, 0.3, 0.4, 8.5, 8.5, 8.5, 8.5, 8.6]
    assert close(longest_gap(ends), 8.1)
    assert close(longest_gap([3.0, 1.0, 2.5, 2.035]), 1.035)  # unsorted input
    assert raises(lambda: longest_gap([1.0]), ValueError)
