81 lines
2.3 KiB
Python
81 lines
2.3 KiB
Python
|
|
"""V0: PlaneClock + LatencyHistogram unit tests."""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import sys
|
||
|
|
|
||
|
|
sys.path.insert(0, "/mnt/dolphinng5_predict")
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
from prod.clean_arch.violet.clock import LatencyHistogram, PlaneClock
|
||
|
|
|
||
|
|
|
||
|
|
def test_planeclock_seq_monotonic_and_stamp():
|
||
|
|
c = PlaneClock("scan", staleness_budget_ns=10)
|
||
|
|
assert c.seq == 0 and c.last_mono_ns == -1
|
||
|
|
assert c.tick(now_ns=100) == 1
|
||
|
|
assert c.tick(now_ns=200) == 2
|
||
|
|
assert c.seq == 2 and c.last_mono_ns == 200
|
||
|
|
|
||
|
|
|
||
|
|
def test_planeclock_age_math_with_injected_now():
|
||
|
|
c = PlaneClock("venue", staleness_budget_ns=1_000)
|
||
|
|
c.tick(now_ns=5_000)
|
||
|
|
assert c.age_ns(now_ns=5_400) == 400
|
||
|
|
# clock never goes backwards in age
|
||
|
|
assert c.age_ns(now_ns=4_000) == 0
|
||
|
|
|
||
|
|
|
||
|
|
def test_planeclock_staleness_boundary_is_strict():
|
||
|
|
"""age == budget → NOT stale; age > budget → stale (MHS FIX-9 lesson:
|
||
|
|
a threshold equal to the natural refresh period must not flap)."""
|
||
|
|
c = PlaneClock("ob", staleness_budget_ns=1_000)
|
||
|
|
c.tick(now_ns=0)
|
||
|
|
assert c.is_stale(now_ns=1_000) is False # exactly at budget
|
||
|
|
assert c.is_stale(now_ns=1_001) is True # one ns past
|
||
|
|
|
||
|
|
|
||
|
|
def test_planeclock_never_ticked_is_not_stale():
|
||
|
|
c = PlaneClock("account", staleness_budget_ns=1)
|
||
|
|
assert c.age_ns(now_ns=10**12) == -1
|
||
|
|
assert c.is_stale(now_ns=10**12) is False # "not yet alive" ≠ "stale"
|
||
|
|
|
||
|
|
|
||
|
|
def test_planeclock_snapshot_shape():
|
||
|
|
c = PlaneClock("scan", staleness_budget_ns=500)
|
||
|
|
c.tick(now_ns=1)
|
||
|
|
s = c.snapshot()
|
||
|
|
for key in ("name", "seq", "last_mono_ns", "age_ns", "stale", "budget_ns"):
|
||
|
|
assert key in s
|
||
|
|
|
||
|
|
|
||
|
|
def test_histogram_exact_percentiles():
|
||
|
|
h = LatencyHistogram("t")
|
||
|
|
for v in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
|
||
|
|
h.record(v)
|
||
|
|
assert h.percentile_ns(0.50) == 5
|
||
|
|
assert h.percentile_ns(0.90) == 9
|
||
|
|
assert h.percentile_ns(0.99) == 10
|
||
|
|
assert h.count == 10
|
||
|
|
|
||
|
|
|
||
|
|
def test_histogram_reservoir_overflow_counts_but_drops():
|
||
|
|
h = LatencyHistogram("t", reservoir=5)
|
||
|
|
for v in range(10):
|
||
|
|
h.record(v)
|
||
|
|
assert h.count == 10
|
||
|
|
d = h.to_dict()
|
||
|
|
assert d["retained"] == 5 and d["overflow_dropped"] == 5
|
||
|
|
|
||
|
|
|
||
|
|
def test_histogram_report_contains_percentiles():
|
||
|
|
h = LatencyHistogram("xyz")
|
||
|
|
h.record(1_000_000) # 1 ms
|
||
|
|
r = h.report()
|
||
|
|
assert "xyz" in r and "p99" in r
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
raise SystemExit(pytest.main([__file__, "-v"]))
|