File size: 2,435 Bytes
a4f1ca1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""Aggregate daily usage counts of the predict routes (squadds_ml_api.usage): no network (mocked CommitScheduler), counts only,
responses unchanged (the legacy oracle in test_legacy.py stays the check of the responses)."""
import json
import threading
from pathlib import Path

from squadds_ml_api.usage import Usage

OLIVIA = "transmon_cross_hamiltonian_inverse"
S = {"qubit_frequency_GHz": 4.85, "anharmonicity_MHz": -205.0}


class _Scheduler:
    def __init__(self, folder):
        self.folder_path, self.lock = Path(folder), threading.Lock()
        self.folder_path.mkdir(parents=True, exist_ok=True)


def test_counts_only(client, tmp_path):
    old = client.app.state.usage
    client.app.state.usage = Usage("api", scheduler=_Scheduler(tmp_path / "api"))
    try:
        h = {"x-forwarded-for": "198.51.100.7"}
        legacy = client.post("/predict", json={"model_id": OLIVIA, "inputs": {**S, "anharmonicity_MHz": -211.5}}, headers=h)
        again = client.post("/predict", json={"model_id": OLIVIA, "inputs": {**S, "anharmonicity_MHz": -211.5}}, headers=h)
        assert legacy.status_code == again.status_code == 200 and legacy.json() == again.json()
        assert set(legacy.json()) == {"model_id", "display_name", "predictions", "metadata"}
        assert client.post("/predict", json={"model_id": "secret-name-xyz", "inputs": S}, headers=h).status_code == 400
        assert client.post(f"/v1/models/{OLIVIA}/predict", json={"inputs": {**S, "anharmonicity_MHz": -212.5}}).status_code == 200
        assert client.post(f"/v1/models/{OLIVIA}/predict", json={"inputs": {"qubit_frequency_GHz": "x"}}).status_code in (400, 422)
        assert client.post("/v1/models/nope/predict", json={"inputs": {}}).status_code == 404
        client.get("/v1/models")
        files = list((tmp_path / "api").glob("*.json"))
        assert len(files) == 1
        text = files[0].read_text()
        row = json.loads(text)
        assert row["calls_by_route"] == {"legacy": 3, "v1": 3}
        assert row["calls_by_model"] == {OLIVIA: 4, "other": 2}
        assert row["refusals"] == {"invalid_input": 2, "unknown_model": 1} and row["cache_hits"] == 1
        assert row["latency_s"]["n"] == 3 and row["distinct_users"] == 2
        for s in ("198.51.100.7", "testclient", "secret-name-xyz", "nope"):
            assert s not in text, s
        print("example row:", json.dumps(row))
    finally:
        client.app.state.usage = old