|
| 1 | +"""Phase 10.0 — per-AI latency percentiles in /metrics. |
| 2 | +
|
| 3 | +Hub maintains a small ring buffer (last 200 latencies) per AI; /metrics |
| 4 | +exposes p50, p95, p99 computed on demand. Tail-latency visibility for |
| 5 | +operators — avg + max alone hides the actual pain. |
| 6 | +""" |
| 7 | + |
| 8 | +import asyncio |
| 9 | +import socket |
| 10 | +import threading |
| 11 | +import time |
| 12 | + |
| 13 | +import pytest |
| 14 | + |
| 15 | +try: |
| 16 | + import fastapi # noqa |
| 17 | + import uvicorn # noqa |
| 18 | + import httpx # noqa |
| 19 | + DEPS_AVAILABLE = True |
| 20 | +except ImportError: |
| 21 | + DEPS_AVAILABLE = False |
| 22 | + |
| 23 | +if DEPS_AVAILABLE: |
| 24 | + from zhub.server import create_app, Hub |
| 25 | +from zhub import publish |
| 26 | + |
| 27 | + |
| 28 | +def _free_port() -> int: |
| 29 | + with socket.socket() as s: |
| 30 | + s.bind(("", 0)) |
| 31 | + return s.getsockname()[1] |
| 32 | + |
| 33 | + |
| 34 | +# --- pure unit tests on Hub.percentile() helper --------------------------- |
| 35 | + |
| 36 | +def test_percentile_empty_returns_zero(): |
| 37 | + h = Hub() |
| 38 | + assert h.compute_percentile("nope", 50) == 0 |
| 39 | + |
| 40 | + |
| 41 | +def test_percentile_p50_p95_p99_against_known_distribution(): |
| 42 | + h = Hub() |
| 43 | + # Inject 100 sorted-ish samples 1..100ms |
| 44 | + for ms in range(1, 101): |
| 45 | + h.record_latency("ai", float(ms)) |
| 46 | + p50 = h.compute_percentile("ai", 50) |
| 47 | + p95 = h.compute_percentile("ai", 95) |
| 48 | + p99 = h.compute_percentile("ai", 99) |
| 49 | + # Standard nearest-rank: p50 ≈ 50, p95 ≈ 95, p99 ≈ 99 (give ±1 leeway) |
| 50 | + assert 49 <= p50 <= 51, f"p50={p50}" |
| 51 | + assert 94 <= p95 <= 96, f"p95={p95}" |
| 52 | + assert 98 <= p99 <= 100, f"p99={p99}" |
| 53 | + |
| 54 | + |
| 55 | +def test_latency_ring_buffer_bounded(): |
| 56 | + """Only the last 200 latencies are kept — older ones get pushed out |
| 57 | + so the percentile reflects recent behavior, not lifetime history.""" |
| 58 | + h = Hub() |
| 59 | + # 100 small samples (1ms), then 200 large samples (1000ms) |
| 60 | + for _ in range(100): |
| 61 | + h.record_latency("ai", 1.0) |
| 62 | + for _ in range(200): |
| 63 | + h.record_latency("ai", 1000.0) |
| 64 | + # Older 1ms samples should be evicted; p50 should be near 1000 |
| 65 | + p50 = h.compute_percentile("ai", 50) |
| 66 | + assert 900 <= p50 <= 1100, f"p50={p50} (ring buffer should have evicted small samples)" |
| 67 | + |
| 68 | + |
| 69 | +# --- end-to-end: percentiles surface in /metrics + /api/dashboard --------- |
| 70 | + |
| 71 | +@pytest.fixture |
| 72 | +def hub(): |
| 73 | + if not DEPS_AVAILABLE: |
| 74 | + pytest.skip("fastapi/uvicorn/httpx not installed") |
| 75 | + port = _free_port() |
| 76 | + app = create_app() |
| 77 | + |
| 78 | + def run(): |
| 79 | + config = uvicorn.Config(app, host="127.0.0.1", port=port, |
| 80 | + log_level="warning") |
| 81 | + asyncio.run(uvicorn.Server(config).serve()) |
| 82 | + |
| 83 | + threading.Thread(target=run, daemon=True).start() |
| 84 | + for _ in range(30): |
| 85 | + try: |
| 86 | + with socket.create_connection(("127.0.0.1", port), timeout=0.1): |
| 87 | + break |
| 88 | + except OSError: |
| 89 | + time.sleep(0.1) |
| 90 | + yield port |
| 91 | + |
| 92 | + |
| 93 | +@pytest.mark.asyncio |
| 94 | +async def test_metrics_includes_percentiles_per_ai(hub): |
| 95 | + pub = publish( |
| 96 | + name="pct-bot", description="x", |
| 97 | + chat_handler=lambda m, o: "ok", |
| 98 | + hub_url=f"ws://127.0.0.1:{hub}", |
| 99 | + ) |
| 100 | + for _ in range(50): |
| 101 | + if pub.api_key: |
| 102 | + break |
| 103 | + await asyncio.sleep(0.1) |
| 104 | + |
| 105 | + async with httpx.AsyncClient(timeout=5.0) as c: |
| 106 | + for _ in range(5): |
| 107 | + await c.post( |
| 108 | + f"http://127.0.0.1:{hub}/{pub.name}/v1/chat/completions", |
| 109 | + json={"messages": [{"role": "user", "content": "x"}]}, |
| 110 | + headers={"Authorization": f"Bearer {pub.api_key}"}, |
| 111 | + ) |
| 112 | + m = (await c.get(f"http://127.0.0.1:{hub}/metrics")).json() |
| 113 | + |
| 114 | + by_ai = m["by_ai"] |
| 115 | + assert pub.name in by_ai |
| 116 | + e = by_ai[pub.name] |
| 117 | + for k in ("p50_latency_ms", "p95_latency_ms", "p99_latency_ms"): |
| 118 | + assert k in e, f"missing {k!r}: {e!r}" |
| 119 | + assert isinstance(e[k], int) |
| 120 | + |
| 121 | + |
| 122 | +@pytest.mark.asyncio |
| 123 | +async def test_dashboard_includes_percentiles(hub): |
| 124 | + pub = publish( |
| 125 | + name="dash-pct-bot", description="x", |
| 126 | + chat_handler=lambda m, o: "ok", |
| 127 | + hub_url=f"ws://127.0.0.1:{hub}", |
| 128 | + ) |
| 129 | + for _ in range(50): |
| 130 | + if pub.api_key: |
| 131 | + break |
| 132 | + await asyncio.sleep(0.1) |
| 133 | + |
| 134 | + async with httpx.AsyncClient(timeout=5.0) as c: |
| 135 | + for _ in range(3): |
| 136 | + await c.post( |
| 137 | + f"http://127.0.0.1:{hub}/{pub.name}/v1/chat/completions", |
| 138 | + json={"messages": [{"role": "user", "content": "x"}]}, |
| 139 | + headers={"Authorization": f"Bearer {pub.api_key}"}, |
| 140 | + ) |
| 141 | + d = (await c.get(f"http://127.0.0.1:{hub}/api/dashboard")).json() |
| 142 | + |
| 143 | + by_ai = d["by_ai"] |
| 144 | + assert pub.name in by_ai |
| 145 | + e = by_ai[pub.name] |
| 146 | + for k in ("p50_latency_ms", "p95_latency_ms", "p99_latency_ms"): |
| 147 | + assert k in e |
0 commit comments