"""Test von Token-Zählung (llama.cpp nativ, Abbrüche) und Aufzeichnung für Debugging. Erwartet in proxy.toml: max_duration_secs = 40, ready_secs = 20, max_entry_kb = 4. """ import json import os import sqlite3 import subprocess import sys import time import urllib.request sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from common import P, check, failures # noqa: E402 BIN = "../../target/debug/omega-proxy" SECRET = "GEHEIMNIS-4711" def cli(*args, user=None): cmd = [BIN, "-c", "proxy.toml"] + (["--as", user] if user else []) + list(args) r = subprocess.run(cmd, capture_output=True, text=True) return r.returncode, (r.stdout + r.stderr).strip().splitlines() def ok(*args, user=None): code, out = cli(*args, user=user) assert code == 0, (args, out) return out def denied(text, *args, user=None): code, out = cli(*args, user=user) msg = " ".join(out) check(code != 0 and text in msg, f"{user or 'system'}: {' '.join(args)} abgelehnt ({msg[:100]})") def db(sql, *args): con = sqlite3.connect("run/test.db") rows = con.execute(sql, args).fetchall() con.close() return rows def post(path, body, key, read=None): """POST; mit read=n werden nur n Bytes gelesen und die Verbindung dann geschlossen (Abbruch).""" req = urllib.request.Request(P + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}"}) try: r = urllib.request.urlopen(req, timeout=120) except urllib.error.HTTPError as e: return e.code, e.read() if read is not None: data = r.read(read) r.close() return r.status, data return r.status, r.read() def counters(quota_id): row = db("SELECT requests, prompt_tokens + completion_tokens FROM usage_counters " "WHERE scope = 'quota' AND scope_id = ? AND period = 'total'", quota_id) return row[0] if row else (0, 0) def rows(quota_id): return db("SELECT count(*), coalesce(sum(prompt_tokens + completion_tokens), 0) FROM usage " "WHERE quota_id = ? AND model IS NOT NULL", quota_id)[0] print("1) Token der eigenen Endpunkte von llama-server") out = ok("quota", "create", "zaehlung") qz = int(out[-1].split()[1].rstrip(":")) KZ = ok("key", "create", "zaehlung", "--quota", str(qz))[-1].split()[-1] st1, b1 = post("/llamacpp/completion", {"model": "smollm2-135m", "prompt": "Hello", "n_predict": 4}, KZ) st2, b2 = post("/llamacpp/completion", {"model": "smollm2-135m", "prompt": "Hello", "n_predict": 4, "stream": True}, KZ) native = db("SELECT path, prompt_tokens, completion_tokens FROM usage WHERE quota_id = ?", qz) print(f" {native}") check(st1 == 200 and st2 == 200 and len(native) == 2 and all(p and c for _, p, c in native), "/completion zählt Token, gestreamt und nicht gestreamt") check(counters(qz) == rows(qz), f"Zähler {counters(qz)} = Einzeleinträge {rows(qz)}") print("2) Abbrüche: die Anfrage zählt, ihre Token nicht") before = counters(qz) st, data = post("/api/generate", {"model": "smollm2:135m", "prompt": "Write a long story", "options": {"num_predict": 400}}, KZ, read=300) st2, data2 = post("/llamacpp/v1/chat/completions", {"model": "smollm2-135m", "stream": True, "max_tokens": 400, "messages": [{"role": "user", "content": "Write a long story"}]}, KZ, read=300) time.sleep(3) aborted = db("SELECT engine, path, aborted, prompt_tokens, completion_tokens FROM usage WHERE quota_id = ? " "ORDER BY id DESC LIMIT 2", qz) print(f" {aborted}; Zähler vorher {before}, nachher {counters(qz)}") check(all(a == 1 and p is None and c is None for _, _, a, p, c in aborted), "beide als abgebrochen ohne Token gespeichert") check(counters(qz) == (before[0] + 2, before[1]), "zwei Anfragen mehr, keine Token mehr") check(counters(qz) == rows(qz), "Zähler weiter gleich den Einzeleinträgen") print("3) Aufzeichnung: nur für eigene Keys, mit Grenzen") ok("user", "add", "anna", "--email", "anna@th-nuernberg.de", user="admin") qa = ok("quota", "create", "anna-rec", "--user", "anna")[-1].split()[1].rstrip(":") out = ok("key", "create", "laptop", "--quota", qa, user="anna") k1, K1 = int(out[-1].split()[1]), out[-1].split()[-1] out = ok("key", "create", "handy", "--quota", qa, user="anna") k2, K2 = int(out[-1].split()[1]), out[-1].split()[-1] denied("nur der Inhaber", "recording", "start", str(k1), "--count", "3") denied("gehört nicht admin", "recording", "start", str(k1), "--count", "3", user="admin") denied("1 bis 100", "recording", "start", str(k1), "--count", "101", user="anna") print(f" {ok('recording', 'start', str(k1), '--count', '3', user='anna')[-1]}") check(any("zeichnet auf: noch 3 von 3" in line for line in ok("key", "list", user="anna")), "Key-Übersicht zeigt die Aufzeichnung") print("4) Drei Anfragen werden aufgezeichnet, verschlüsselt; danach endet die Aufzeichnung") st, _ = post("/api/chat", {"model": "smollm2:135m", "stream": False, "options": {"num_predict": 5}, "messages": [{"role": "user", "content": f"Sag {SECRET}"}]}, K1) st2, _ = post("/llamacpp/v1/chat/completions", {"model": "smollm2-135m", "stream": True, "max_tokens": 5, "messages": [{"role": "user", "content": "Hallo"}]}, K1) line = next(line for line in ok("key", "list", user="anna") if "laptop" in line) check(st == 200 and st2 == 200 and "noch 1 von 3" in line, f"nach zwei Anfragen: {line.split(' ')[-1].strip()}") blobs = db("SELECT data FROM recording_entries") check(len(blobs) == 2 and not any(SECRET.encode() in b[0] or b"smollm2" in b[0] for b in blobs), "Einträge liegen verschlüsselt in der Datenbank") st3, _ = post("/api/generate", {"model": "smollm2:135m", "stream": False, "prompt": "x" * 6000, "options": {"num_predict": 3}}, K1) time.sleep(0.5) st4, _ = post("/api/generate", {"model": "smollm2:135m", "stream": False, "prompt": "nicht mehr", "options": {"num_predict": 3}}, K1) rec = ok("recording", "list", user="anna") print(f" {rec}") check(len(rec) == 1 and "3 von 3" in rec[0] and "bereit bis" in rec[0] and "alle Anfragen aufgezeichnet" in rec[0], "nach drei Anfragen beendet und bereit; die vierte wird nicht aufgezeichnet") mail = ok("outbox", "list", user="admin") print(" " + "\n ".join(mail)) check(any("anna@th-nuernberg.de" in line for line in mail) and not any(SECRET in line for line in mail) and any("http://localhost:8000/recordings/" in line for line in mail), "Benachrichtigung an anna mit Link, ohne Inhalte") print("5) Herunterladen: nur der Inhaber, danach gelöscht") rid = rec[0].split()[0] denied("nur der Inhaber", "recording", "download", rid, "--out", "run/x.jsonl") denied("gehört nicht admin", "recording", "download", rid, "--out", "run/x.jsonl", user="admin") print(f" {ok('recording', 'download', rid, '--out', 'run/rec.jsonl', user='anna')[-1]}") entries = [json.loads(line) for line in open("run/rec.jsonl")] for e in entries: print(f" {e['endpoint']:<36} aborted={e['aborted']} truncated={e['truncated']} " f"response={json.dumps(e['response'])[:70]}") check(len(entries) == 3, "drei Einträge") check(SECRET in json.dumps(entries[0]["request"]) and entries[0]["response"].get("message"), "Eintrag 1: Anfrage im Original, Antwort von Ollama") check(entries[1]["response"].get("stream") is True and entries[1]["response"]["content"], f"Eintrag 2: gestreamte Antwort zusammengesetzt ({entries[1]['response'].get('content')!r})") check(entries[2]["truncated"] is True, "Eintrag 3: über 4 KB, abgeschnitten") check(db("SELECT count(*) FROM recording_entries")[0][0] == 0 and db("SELECT wrapped_key IS NULL FROM recordings WHERE id = ?", int(rid))[0][0] == 1, "Einträge und Schlüssel nach dem Download gelöscht") denied("nicht mehr verfügbar", "recording", "download", rid, "--out", "run/x.jsonl", user="anna") print("6) Stoppen, Ablauf der Bereitstellung und Höchstdauer (40 s)") t0 = time.time() ok("recording", "start", str(k2), "--count", "50", user="anna") ok("recording", "start", str(k1), "--count", "5", user="anna") post("/api/generate", {"model": "smollm2:135m", "stream": False, "prompt": "eins", "options": {"num_predict": 3}}, K1) print(f" {ok('recording', 'stop', str(k1), user='anna')[-1]}") time.sleep(max(0, 47 - (time.time() - t0))) rec = ok("recording", "list", user="anna") print(" " + "\n ".join(rec)) stopped = next(line for line in rec if "vom Benutzer beendet" in line) expired = next(line for line in rec if "Höchstdauer" in line) check("gelöscht" in stopped, "gestoppte Aufzeichnung nach Ablauf der Bereitstellung gelöscht") check("bereit bis" in expired, "zweite Aufzeichnung nach 40 s beendet und bereit") denied("nicht mehr verfügbar", "recording", "download", stopped.split()[0], "--out", "run/x.jsonl", user="anna") print("7) Audit-Log") log = ok("audit", "list", "--limit", "100", user="admin") for action in ["recording.start", "recording.end", "recording.ready", "recording.download", "recording.delete"]: check(any(action in line for line in log), f"{action} verzeichnet") print("ERGEBNIS:", "alles bestanden" if not failures else f"{len(failures)} Fehler: {failures}")