decider-2b / training /tests /test_server.py
Jeetu456's picture
Decider 2B
cd02163
Raw History Blame Contribute Delete
7.77 kB
"""API tests on a tiny trained model (CPU): routes, auth, validation, Jev limits, batching, splitting,
rate limits, metrics."""
import concurrent.futures
import os
import sys
CODE, ADAPTER = sys.argv[1], sys.argv[2]
import torch # noqa: E402
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
os.environ.update(DECIDER_ADAPTER=ADAPTER, DECIDER_DEVICE=DEVICE, DECIDER_API_KEYS="key-one,key-two",
DECIDER_RATE_RPM="1000", DECIDER_MAX_WAIT_MS="30")
sys.path.insert(0, CODE)
from fastapi.testclient import TestClient # noqa: E402
import server # noqa: E402
GOOD = {"Authorization": "Bearer key-one"}
BODY = {"model": "decider-2b",
"state": {"invoice": {"vendor": "Acme", "total": 1250.0, "status": "overdue"}},
"questions": {
"status": {"type": "choice", "instructions": "What is the invoice status?",
"criteria": {"paid": "Invoice is paid.", "overdue": "Invoice is past due.", "draft": "Not sent."}},
"large": {"type": "noul", "instructions": "The total is above 1000 USD."},
"urgency": {"type": "score", "instructions": "How urgent is it?", "criteria": ["Can wait", "This week", "Today"]}}}
def check(name, condition, detail=""):
print(("PASS " if condition else "FAIL ") + name + (f" ({detail})" if detail and not condition else ""))
if not condition:
raise SystemExit(1)
with TestClient(server.app) as client:
check("health", client.get("/health").status_code == 200)
ready = client.get("/ready")
check("ready after warm-up", ready.status_code == 200, ready.text)
check("models lists limits", client.get("/v1/models").json()["data"][0]["limits"]["questions"] == 128)
check("no key -> 401", client.post("/v1/systemone", json=BODY).status_code == 401)
check("wrong key -> 401", client.post("/v1/systemone", json=BODY, headers={"Authorization": "Bearer nope"}).status_code == 401)
r = client.post("/v1/systemone", json=BODY, headers=GOOD)
check("valid request -> 200", r.status_code == 200, r.text)
out = r.json()
print(" response:", out)
a = out["answers"]
check("choice answer shape", a["status"]["type"] == "choice" and a["status"]["choice"] in BODY["questions"]["status"]["criteria"]
and abs(sum(a["status"]["probabilities"].values()) - 1) < 1e-4 and "confidence" in a["status"])
check("noul answer shape", a["large"]["type"] == "noul" and 0 <= a["large"]["noul"] <= 1)
check("score answer shape", a["urgency"]["type"] == "score" and 0 <= a["urgency"]["score"] <= 2
and set(a["urgency"]["legend"]) == {"0", "1", "2"} and len(a["urgency"]["probabilities"]) == 3)
check("usage", out["usage"]["input_tokens"] > 0 and out["usage"]["output_tokens"] == 0)
check("request id header", "x-request-id" in r.headers)
r2 = client.post("/v1/decisions", json=BODY, headers={"Authorization": "Bearer key-two"})
check("/v1/decisions alias gives the same answers", r2.status_code == 200 and
abs(r2.json()["answers"]["large"]["noul"] - a["large"]["noul"]) < 1e-3)
check("state as a list of strings", client.post("/v1/systemone", headers=GOOD, json=dict(BODY, state=["first note", "second note"])).status_code == 200)
bad = [
("not JSON", b"{oops", None),
("missing state", None, {"questions": BODY["questions"]}),
("empty questions", None, {"state": "x", "questions": {}}),
("unknown type", None, {"state": "x", "questions": {"q": {"type": "rank", "instructions": "?"}}}),
("choice with one option", None, {"state": "x", "questions": {"q": {"type": "choice", "criteria": {"a": "only"}}}}),
("score not a list", None, {"state": "x", "questions": {"q": {"type": "score", "criteria": {"a": 1}}}}),
("noul without statement", None, {"state": "x", "questions": {"q": {"type": "noul"}}}),
("noul with option criteria", None, {"state": "x", "questions": {"q": {"type": "noul", "instructions": "x", "criteria": {"a": "b"}}}}),
("129 questions", None, {"state": "x", "questions": {f"q{i}": {"type": "noul", "instructions": "x"} for i in range(129)}}),
]
for name, raw, body in bad:
r = client.post("/v1/systemone", headers=GOOD, content=raw) if raw else client.post("/v1/systemone", headers=GOOD, json=body)
check(f"{name} -> 400", r.status_code == 400 and r.json()["error"]["type"] == "invalid_request_error", r.text)
clef_noul = {"state": "x", "questions": {"q": {"type": "noul", "instructions": "x", "criteria": {"true": "yes", "false": "no"}}}}
check("Clef-style noul criteria accepted", client.post("/v1/systemone", headers=GOOD, json=clef_noul).status_code == 200)
big_state = "lorem ipsum dolor " * 11500 # about 34k tokens
r = client.post("/v1/systemone", headers=GOOD, json={"state": big_state, "questions": {"q": {"type": "noul", "instructions": "x"}}})
check("state + question over 32k -> 413", r.status_code == 413, r.text)
r = client.post("/v1/systemone", headers=GOOD, json={"state": "lorem ipsum dolor " * 4000, "questions": {
f"q{i}": {"type": "noul", "instructions": "word " * 700} for i in range(120)}})
check("request over 64k -> 413", r.status_code == 413, r.text)
# A request bigger than the trained length per pass is split into several passes, not cut.
many = {"state": "The device list is long. " * 600, "questions": {
f"q{i}": {"type": "choice", "instructions": f"Question number {i} about the state?",
"criteria": {"a": "first answer option", "b": "second answer option", "c": "third answer option"}}
for i in range(128)}}
engine = server.engine
pending, passes = engine.prepare(many)
r = client.post("/v1/systemone", headers=GOOD, json=many)
check(f"128 questions over the trained length -> {len(passes)} passes, all answered",
r.status_code == 200 and len(r.json()["answers"]) == 128 and len(passes) > 1, f"{r.status_code} {len(passes)}")
# Dynamic batching: concurrent requests share GPU batches and give the same answers as alone.
alone = {}
variants = []
for i in range(12):
body = dict(BODY, state={"invoice": {"vendor": f"Vendor {i}", "total": 100.0 * i, "status": "overdue"}})
variants.append(body)
alone[i] = client.post("/v1/systemone", headers=GOOD, json=body).json()
before = dict(engine.stats)
with concurrent.futures.ThreadPoolExecutor(12) as pool:
together = list(pool.map(lambda b: client.post("/v1/systemone", headers=GOOD, json=b).json(), variants))
batches = engine.stats["batches"] - before["batches"]
passes_run = engine.stats["passes"] - before["passes"]
check(f"12 concurrent requests ran in {batches} batches", batches < passes_run, f"{batches} batches for {passes_run} passes")
diff = max(abs(alone[i]["answers"]["large"]["noul"] - together[i]["answers"]["large"]["noul"]) for i in range(12))
check("batched answers match single answers", diff < (2e-2 if DEVICE == "cuda" else 1e-3), f"max diff {diff}")
metrics = client.get("/metrics").text
check("metrics exported", "decider_requests_total" in metrics and "decider_batch_passes_bucket" in metrics)
server.limiter.limits["requests"] = 5
server.limiter.buckets.clear()
codes = [client.post("/v1/systemone", headers=GOOD, json=BODY) for _ in range(8)]
limited = [r for r in codes if r.status_code == 429]
check("rate limit -> 429 with Retry-After", limited and "retry-after" in limited[0].headers,
str([r.status_code for r in codes]))
other = client.post("/v1/systemone", headers={"Authorization": "Bearer key-two"}, json=BODY)
check("limits are per key", other.status_code == 200, other.text)
print("SERVER TESTS OK")