"""Test der Kontingente und Super-Keys über drei simulierte Sparks.""" import datetime import json import os import sqlite3 import subprocess import sys import threading import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from common import ask, check, failures, status # noqa: E402 BIN = "../../target/debug/omega-proxy" def cli(*args): r = subprocess.run([BIN, "-c", "proxy.toml", *args], capture_output=True, text=True) out = (r.stdout + r.stderr).strip().splitlines() return r.returncode, out def quota(name, *args): code, out = cli("quota", "create", name, *args) assert code == 0, out print(f" {out[-1]}") return int(out[-1].split()[1].rstrip(":")) def key(name, *args): code, out = cli("key", "create", name, *args) assert code == 0, out return int(out[-1].split()[1]), out[-1].split()[-1] def message(body): try: e = json.loads(body)["error"] return e["message"] if isinstance(e, dict) else e except Exception: return body.decode(errors="replace")[:100] def counters(scope, scope_id): """Verbrauch insgesamt laut Zählern""" db = sqlite3.connect("run/test.db") row = db.execute("SELECT requests, prompt_tokens + completion_tokens FROM usage_counters " "WHERE scope = ? AND scope_id = ? AND period = 'total'", (scope, scope_id)).fetchone() db.close() return row or (0, 0) def from_rows(quota_id): """Verbrauch laut Einzeleinträgen""" db = sqlite3.connect("run/test.db") row = db.execute("SELECT count(*), coalesce(sum(prompt_tokens + completion_tokens), 0) FROM usage " "WHERE quota_id = ? AND model IS NOT NULL", (quota_id,)).fetchone() db.close() return row def stream_llama(model, key_): """Gestreamte OpenAI-Anfrage an llama-server; liefert Status und Token laut usage-Chunk""" import urllib.request req = urllib.request.Request( "http://127.0.0.1:8000/llamacpp/v1/chat/completions", data=json.dumps({"model": model, "stream": True, "max_tokens": 4, "messages": [{"role": "user", "content": "hi"}]}).encode(), headers={"Content-Type": "application/json", "Authorization": f"Bearer {key_}"}) with urllib.request.urlopen(req, timeout=120) as r: tokens = None for line in r.read().decode().splitlines(): if line.startswith("data: {") and '"usage"' in line: u = json.loads(line[6:]).get("usage") if u: tokens = u["prompt_tokens"] + u["completion_tokens"] return r.status, tokens print("1) Anfragen-Grenze: 3 je Stunde") q1 = quota("anfragen", "--requests-hour", "3") k1, K1 = key("student1", "--quota", str(q1)) codes = [ask("ollama", "smollm2:135m", key=K1)[0] for _ in range(3)] st, _, b = ask("ollama", "smollm2:135m", key=K1) print(f" {codes} -> [{st}] {message(b)}") check(codes == [200] * 3 and st == 429 and "3 von 3 Anfragen in dieser Stunde, wieder ab" in message(b), "drei Anfragen, die vierte erhält 429 mit Zeitpunkt der Freigabe") print("2) Token-Grenze: 50 je Tag; eine Anfrage darf starten, solange etwas übrig ist") q2 = quota("token", "--tokens-day", "50") k2, K2 = key("student2", "--quota", str(q2)) results = [] for _ in range(4): st, _, b = ask("ollama", "smollm2:135m", key=K2) results.append((st, counters("quota", q2)[1])) if st != 200: print(f" [{st}] {message(b)}") break print(f" (Status, Token danach): {results}") used = [t for s, t in results if s == 200] check(results[-1][0] == 429 and used[-1] >= 50 and (len(used) < 2 or used[-2] < 50), "Anfragen laufen, bis 50 Token erreicht sind; die letzte überschreitet leicht, danach 429") print("3) Zähler stimmen mit den Einzeleinträgen überein, auch gestreamt") q3 = quota("stream") k3, K3 = key("student3", "--quota", str(q3)) st, streamed = stream_llama("smollm2-135m", K3) st2, _, _ = ask("ollama", "smollm2:135m", key=K3) time.sleep(0.5) print(f" gestreamt: {streamed} Token; Zähler {counters('quota', q3)}; Einzeleinträge {from_rows(q3)}") check(st == 200 and st2 == 200 and counters("quota", q3) == from_rows(q3) and counters("quota", q3)[1] > streamed, "Anfragen und Token der Zähler gleich der Summe der Einzeleinträge") for q in (q1, q2): check(counters("quota", q) == from_rows(q), f"auch für Kontingent {q}: {counters('quota', q)}") check(counters("key", k3) == counters("quota", q3), "Key und Kontingent zählen gleich") print("4) Gleichzeitige Anfragen: 12 parallel gegen eine Grenze von 5") q4 = quota("parallel", "--requests-hour", "5") _, K4 = key("student4", "--quota", str(q4)) codes = [] lock = threading.Lock() def one(): st = ask("ollama", "smollm2:135m", key=K4)[0] with lock: codes.append(st) threads = [threading.Thread(target=one) for _ in range(12)] for t in threads: t.start() for t in threads: t.join() print(f" {sorted(codes)}") check(codes.count(200) == 5 and codes.count(429) == 7, "genau 5 erfolgreich, 7 abgewiesen") print("5) Rückbuchung: Anfragen, die die Engine nicht erreichen, zählen nicht") q5 = quota("rueck", "--requests-total", "2") _, K5 = key("student5", "--quota", str(q5)) codes = [ask("ollama", "gibtsnicht", key=K5)[0] for _ in range(3)] check(codes == [404] * 3 and counters("quota", q5)[0] == 0, f"3 × unbekanntes Modell {codes}, Zähler {counters('quota', q5)}") check(ask("ollama", "smollm2:135m", key=K5)[0] == 200, "danach geht eine echte Anfrage durch") print("6) Modelle, Gültigkeit und Nutzungszeiten") q6 = quota("nur-smollm", "--models", "ollama/smollm2:135m") _, K6 = key("student6", "--quota", str(q6)) st, _, b = ask("ollama", "qwen3:0.6b", key=K6) print(f" [{st}] {message(b)}") check(st == 403 and "nicht nutzbar" in message(b), "nicht freigegebenes Modell: 403") check(ask("ollama", "smollm2:135m", key=K6)[0] == 200, "freigegebenes Modell: 200") q7 = quota("kurz", "--until", "+4s") _, K7 = key("student7", "--quota", str(q7)) check(ask("ollama", "smollm2:135m", key=K7)[0] == 200, "vor Ablauf: 200") time.sleep(5) st, _, b = ask("ollama", "smollm2:135m", key=K7) print(f" [{st}] {message(b)}") check(st == 403 and "abgelaufen" in message(b), "nach Ablauf: 403") q8 = quota("spaeter", "--from", "+1h") _, K8 = key("student8", "--quota", str(q8)) st, _, b = ask("ollama", "smollm2:135m", key=K8) check(st == 403 and "gilt erst ab" in message(b), f"vor Beginn: 403 ({message(b)})") now = datetime.datetime.now() day = ["mo", "di", "mi", "do", "fr", "sa", "so"][now.weekday()] later = (now + datetime.timedelta(hours=1)).strftime("%H:%M") later2 = (now + datetime.timedelta(hours=2)).strftime("%H:%M") q9 = quota("abends", "--weekly", day, "--time", f"{later}-{later2}") _, K9 = key("student9", "--quota", str(q9)) st, _, b = ask("ollama", "smollm2:135m", key=K9) check(st == 403 and "nur zu diesen Zeiten" in message(b), f"außerhalb der Nutzungszeiten: 403 ({message(b)})") print("7) Alte Metadaten löschen: Kontingentstände bleiben") before = counters("quota", q1) code, out = cli("usage", "prune", "--older-than-days", "0") print(f" {out[-1]}") check(from_rows(q1)[0] == 0 and counters("quota", q1) == before, f"Einzeleinträge weg, Zähler {counters('quota', q1)}") st, _, _ = ask("ollama", "smollm2:135m", key=K1) check(st == 429, "Kontingent 1 bleibt ausgeschöpft") code, out = cli("quota", "show", str(q1)) print(" " + "\n ".join(out)) code, out = cli("key", "list") print(" " + "\n ".join(out[:4])) print("8) Super-Key verdrängt notfalls gepinnte Modelle; der Pin stellt sich danach wieder her") _, SUPER = key("admin", "--super") for args in (["vllm/smollm2-360m"], ["llamacpp/qwen3-0.6b"]): code, out = cli("schedule", "pin", *args) print(f" {out[-1]}") def spark1(): return {m["engine"] + "/" + m["model"]: m["pinned"] for n in status() if n["name"] == "spark1" for m in n["models"] if m["state"] == "loaded"} end = time.time() + 30 while time.time() < end and not ("vllm/smollm2-360m" in spark1() and "llamacpp/qwen3-0.6b" in spark1()): time.sleep(0.5) time.sleep(6) # Mindestverweildauer print(f" spark1 vorher: {spark1()}") st, dt, _ = ask("llamacpp", "smollm2-135m", key=SUPER) after = spark1() print(f" Super-Key, llamacpp/smollm2-135m (nur spark1) -> [{st}, {dt:.1f} s]; spark1: {after}") check(st == 200 and "llamacpp/smollm2-135m" in after, "Super-Key wird bedient") check(not ("vllm/smollm2-360m" in after and "llamacpp/qwen3-0.6b" in after), "dafür wurde ein gepinntes Modell verdrängt") end = time.time() + 40 while time.time() < end and not ("vllm/smollm2-360m" in spark1() and "llamacpp/qwen3-0.6b" in spark1()): time.sleep(0.5) print(f" spark1 danach: {spark1()}") check("vllm/smollm2-360m" in spark1() and "llamacpp/qwen3-0.6b" in spark1(), "beide gepinnten Modelle sind wieder geladen") check(counters("key", int(cli("key", "list")[1][-1].split()[0]))[0] >= 1, "Super-Key zählt beim Key") print("ERGEBNIS:", "alles bestanden" if not failures else f"{len(failures)} Fehler: {failures}")