"""Tests on Lab 04's recorded results (October 2026, Apple M4 Max, Docker Desktop with 16 vCPU):
01_kvstore.py (our stores killed and their files cut; 5,000 writes timed three ways) and
04_durability.py (Postgres commits per second, and Postgres killed 5 times per setting).
Run: pytest test_durability_practice.py"""
from durability_practice import (encode, lost_acknowledged, recover, share_lost, slowdown, survives,
                                 us_per_write)


def value(i):
    """The value the lab's crash-test writer stores under key i (kvstore/writer.py)."""
    return (f"value-{i}-" * 4).encode()


def first_records():
    """The first six records of store A's log, as the lab's store writes them."""
    return [encode(f"key-{i:08d}".encode(), value(i)) for i in range(6)]

# Exercise 3 of 01_kvstore.py: puts a second into store A on the Mac's SSD.
NO_FLUSH, FSYNC, FULL = 544415.244931907, 44643.90349481847, 212.4953449955155

# 04_durability.py: commits a second, and (acknowledged, lost) per kill.
ON_1, OFF_1, ON_16, OFF_16 = 2698.375, 2502.5, 8331.75, 15819.625
KILLS_ON = [(8339, 0), (7561, 0), (10796, 0), (5727, 0), (5380, 0)]
KILLS_OFF = [(29750, 3500), (33546, 138), (22434, 1650), (40034, 3237), (42849, 2638)]


def test_survives():
    # Our store said OK once the write reached the OS: no kill lost anything (260 kills).
    assert survives("os", "program killed")
    # Postgres with synchronous_commit off says OK while the write is in its own memory.
    assert not survives("program", "program killed")
    # A power cut empties everything but the disk; fsync on the Mac only reaches the drive cache.
    assert not survives("os", "power cut")
    assert not survives("drive cache", "power cut")
    assert survives("disk", "power cut")
    assert survives("drive cache", "program killed")


def test_encode_matches_the_lab():
    RECORDS = first_records()
    assert len(RECORDS[0]) == 56  # 12-byte header + 12-byte key + 32-byte value
    assert RECORDS[0][:4].hex() == "79064f0a"  # the crc32 kvstore/records.py writes
    assert RECORDS[0][4:12] == bytes([12, 0, 0, 0, 32, 0, 0, 0])


def test_recover_cuts():
    FILE = b"".join(first_records())
    assert recover(FILE) == (336, "clean")
    assert recover(FILE[:200]) == (168, "past end")  # half of the 4th record: dropped
    assert recover(FILE[:3 * 56 + 7]) == (168, "short header")
    assert recover(FILE[:5 * 56]) == (280, "clean")  # a cut exactly between records drops nothing
    # Every cut keeps exactly the records that were complete before it.
    for cut in range(1, len(FILE) + 1):
        kept, _ = recover(FILE[:cut])
        assert kept == 56 * (cut // 56)


def test_recover_corrupt_byte():
    bad = bytearray(b"".join(first_records()))
    bad[4 * 56 - 1] ^= 0xFF  # one byte of the 4th record's value
    assert recover(bytes(bad)) == (168, "checksum")


def test_price_of_a_flush():
    assert round(us_per_write(NO_FLUSH), 1) == 1.8
    assert round(us_per_write(FSYNC)) == 22
    assert round(us_per_write(FULL)) == 4706
    assert round(slowdown(NO_FLUSH, FSYNC)) == 12
    assert round(slowdown(NO_FLUSH, FULL)) == 2562  # "about 2,600 times slower"
    assert round(us_per_write(ON_1)) == 371  # one client: 0.37 ms per commit


def test_commits_per_second():
    assert round(ON_16 / ON_1, 1) == 3.1  # 16 clients, every commit still flushed
    assert round(slowdown(OFF_16, ON_16), 1) == 1.9  # waiting for the flush: 1.9x fewer commits at 16 clients
    assert OFF_1 < ON_1  # one client: no gain from skipping the wait


def test_kills():
    assert lost_acknowledged([1, 2, 3, 4], {1, 2, 4}) == 1
    assert lost_acknowledged([], set()) == 0
    assert share_lost(KILLS_ON) == 0
    assert sum(a for a, _ in KILLS_OFF) == 168613
    assert sum(l for _, l in KILLS_OFF) == 11163
    assert round(100 * share_lost(KILLS_OFF), 1) == 6.6
    assert all(l > 0 for _, l in KILLS_OFF)  # every kill lost acknowledged inserts
