From ab4803e2646df50896b493a8756d8338ee13458d Mon Sep 17 00:00:00 2001 From: Stephan Rehfeld Date: Fri, 20 Nov 2026 13:19:03 +0100 Subject: [PATCH] =?UTF-8?q?Kontingente,=20Z=C3=A4hler=20der=20Nutzung=20un?= =?UTF-8?q?d=20Super-Keys=20ohne=20Einschr=C3=A4nkungen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Kontingente begrenzen Token und Anfragen je Stunde, Tag, Woche, Monat und insgesamt (Kalenderzeiträume in Ortszeit), dazu Gültigkeit, Nutzungszeiten und Modelle; Keys werden einem Kontingent zugeordnet, ohne sind sie unbegrenzt - Eine Anfrage zählt beim Start (Prüfen und Zählen in einer Transaktion) und wird zurückgebucht, wenn sie die Engine nicht erreicht; ihre Token werden nach der Antwort gebucht; 429 bei ausgeschöpftem Kontingent, 403 sonst - usage_counters führt den Verbrauch je Key und Kontingent und Zeitraum; usage prune löscht alte Einzeleinträge, ohne die Kontingentstände zu ändern - Super-Keys haben kein Kontingent, übergehen Modellbeschränkungen, exklusive Nutzung und Modellzeitfenster und verdrängen notfalls gepinnte Modelle - CLI: quota create/list/show/remove, key create --quota, key quota, usage prune - Unit-Tests und tests/multispark/quota_test.py Co-Authored-By: Claude Opus 5.5 --- README.md | 62 ++++++- proxy/src/db.rs | 300 +++++++++++++++++++++++++++++++-- proxy/src/forward.rs | 13 ++ proxy/src/main.rs | 196 ++++++++++++++++++++- proxy/src/quota.rs | 299 ++++++++++++++++++++++++++++++++ proxy/src/routes.rs | 90 ++++++++-- proxy/src/scheduler.rs | 36 ++-- tests/multispark/README.md | 6 + tests/multispark/quota_test.py | 215 +++++++++++++++++++++++ 9 files changed, 1167 insertions(+), 50 deletions(-) create mode 100644 proxy/src/quota.rs create mode 100644 tests/multispark/quota_test.py diff --git a/README.md b/README.md index e054494..03c62b9 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,10 @@ Das Konzept steht in [projekt.md](projekt.md). Dieser Stand umfasst: verdrängt ungenutzte Modelle nach einer Mindestverweildauer, entlädt nie während laufender Anfragen und lässt Anfragen warten, bis ihr Modell geladen ist. - Zeitplan mit Pins (Modelle garantiert im Speicher), exklusiver Nutzung und - Modellzeitfenstern; Super-Keys, die trotzdem alles dürfen. + Modellzeitfenstern. +- Kontingente je Key: Token und Anfragen je Stunde, Tag, Woche, Monat und insgesamt, + Gültigkeit, Nutzungszeiten und Modelle; Zähler, die das Löschen alter Metadaten überstehen. +- Super-Keys, die unabhängig von Kontingenten, Zeitplan und Pins immer dürfen. - Audit-Log für Keys, den Zeitplan sowie Laden und Entladen von Modellen. - `omega-agent`: meldet den belegten Speicher eines Rechners (nvidia-smi, sonst `/proc/meminfo`) und startet und stoppt im Auftrag des Proxys die vLLM-Instanzen. @@ -68,8 +71,58 @@ curl -H "Authorization: Bearer $KEY" http://server:8000/vllm/v1/chat/completions curl -H "Authorization: Bearer $KEY" http://server:8000/omega/status ``` -Keys verwalten: `omega-proxy key create NAME [--super]`, `omega-proxy key list`, -`omega-proxy key revoke `. +Keys verwalten: `omega-proxy key create NAME [--quota ID | --super]`, `omega-proxy key list` +(mit Verbrauch), `omega-proxy key quota `, `omega-proxy key revoke `. + +## Kontingente + +Ein Kontingent regelt, wie viel die Keys nutzen dürfen, die ihm zugeordnet sind; mehrere Keys +können sich eines teilen. Ein Key ohne Kontingent ist unbegrenzt. + +```sh +# Praktikum: 20 000 Token am Tag, 60 Anfragen in der Stunde, nur werktags 8-18 Uhr, +# nur zwei Modelle, bis Semesterende +omega-proxy quota create praktikum-ki --tokens-day 20000 --requests-hour 60 \ + --weekly mo-fr --time 08:00-18:00 --until 2027-02-15 \ + --models ollama/qwen3:0.6b,vllm/qwen2.5-0.5b +omega-proxy key create student-mueller --quota 1 + +omega-proxy quota list +omega-proxy quota show 1 # Verbrauch je Zeitraum +omega-proxy quota remove 1 # nur ohne zugeordnete Keys +``` + +- Grenzen: `--tokens-{hour,day,week,month,total}` und `--requests-{hour,day,week,month,total}`. + Die Zeiträume sind Kalenderzeiträume in Ortszeit: Ein Tageskontingent beginnt um Mitternacht + neu, ein Wochenkontingent am Montag. +- `--from`/`--until` begrenzen die Gültigkeit, `--weekly`/`--time` die Nutzungszeiten, + `--models` die Modelle. +- Abrechnung: Eine Anfrage darf starten, solange das Kontingent nicht ausgeschöpft ist. Sie + zählt beim Start; erreicht sie die Engine nicht (Modell unbekannt oder nicht ladbar), wird + sie zurückgebucht. Ihre Token werden nach der Antwort gebucht, auch bei einem abgebrochenen + Stream. Die letzte Anfrage kann ein Token-Kontingent also leicht überschreiten. +- Antworten: 429 bei ausgeschöpftem Kontingent (mit dem Zeitpunkt, ab dem es wieder geht), 403 + außerhalb von Gültigkeit oder Nutzungszeiten und bei nicht freigegebenen Modellen. +- Gezählt werden nur Anfragen an ein Modell; Modelllisten und `/api/show` zählen nicht. + +### Datenhaltung der Nutzung + +- `usage`: eine Zeile je Anfrage (Zeitpunkt, Key, Kontingent, Engine, Modell, Pfad, Status, + Token, Dauer), ohne Inhalte. +- `usage_counters`: Anfragen und Token je Key und je Kontingent für jeden Zeitraum + (`hour:2026-11-20T12`, `day:2026-11-20`, `week:2026-W47`, `month:2026-11`, `total`). Gegen + diese Zähler wird geprüft; Prüfen und Zählen geschehen in einer Transaktion, damit + gleichzeitige Anfragen eine Grenze nicht gemeinsam überschreiten. +- `omega-proxy usage prune --older-than-days N` löscht alte Einzelzeilen. Die Zähler und damit + die Kontingentstände bleiben erhalten. + +## Super-Keys + +Super-Keys (`omega-proxy key create NAME --super`) dürfen immer: Sie haben kein Kontingent und +übergehen Modellbeschränkungen, exklusive Nutzung (Gruppen) und Modellzeitfenster. Fehlt ihnen +der Platz, verdrängen sie notfalls auch gepinnte Modelle, aber erst, wenn ungepinnte nicht +reichen; der Proxy lädt das gepinnte Modell danach von selbst wieder. Ihr Verbrauch wird beim Key +gezählt. ## Zeitplan @@ -87,8 +140,7 @@ dem Ende der Reservierung und der Anmerkung. Modelllisten bleiben abrufbar. **Modellzeitfenster:** Nur die genannten Modelle sind verfügbar; Anfragen an andere erhalten 403. -**Super-Keys** (`omega-proxy key create NAME --super`) dürfen trotz exklusiver Nutzung und -Modellzeitfenster alles. +**Super-Keys** dürfen trotz exklusiver Nutzung und Modellzeitfenster alles (siehe unten). ```sh # Pin: dauerhaft, einmalig, wöchentlich im Semester diff --git a/proxy/src/db.rs b/proxy/src/db.rs index 31cda58..91c9d99 100644 --- a/proxy/src/db.rs +++ b/proxy/src/db.rs @@ -3,12 +3,16 @@ use std::{ time::{SystemTime, UNIX_EPOCH}, }; -use anyhow::Result; +use anyhow::{Result, bail}; +use chrono::{DateTime, Local}; use rand::RngCore; use rusqlite::{Connection, OptionalExtension, params}; use sha2::{Digest, Sha256}; -use crate::schedule::{self, Entry, Kind, TimeSpec, Weekly}; +use crate::{ + quota::{Counter, Denial, Limits, Period, Quota}, + schedule::{self, Entry, Kind, TimeSpec, Weekly}, +}; /// SQLite-Datenbank. Die Zugriffe sind kurz, deshalb genügt eine Verbindung hinter einem Mutex. pub struct Db { @@ -19,10 +23,11 @@ pub struct ApiKey { pub id: i64, pub name: String, pub prefix: String, - pub created_at: i64, pub revoked: bool, /// Super-Keys dürfen unabhängig von allen Einschränkungen immer alles pub is_super: bool, + /// Kontingent, gegen das der Key abgerechnet wird; ohne ist er unbegrenzt + pub quota_id: Option, } /// Ein angemeldeter Key @@ -30,6 +35,7 @@ pub struct ApiKey { pub struct Caller { pub key_id: i64, pub is_super: bool, + pub quota_id: Option, } #[derive(Default)] @@ -42,6 +48,25 @@ pub struct Usage { pub prompt_tokens: Option, pub completion_tokens: Option, pub duration_ms: u64, + pub quota_id: Option, + /// Beginn einer gezählten Anfrage; ihre Token werden den Zeiträumen dieses Zeitpunkts gebucht + pub counted_at: Option>, +} + +/// Wessen Verbrauch gezählt wird +#[derive(Clone, Copy)] +pub enum Scope { + Key(i64), + Quota(i64), +} + +impl Scope { + fn parts(self) -> (&'static str, i64) { + match self { + Scope::Key(id) => ("key", id), + Scope::Quota(id) => ("quota", id), + } + } } pub fn now() -> i64 { @@ -103,6 +128,34 @@ impl Db { note TEXT NOT NULL, created_at INTEGER NOT NULL ); + CREATE TABLE IF NOT EXISTS quotas ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + valid_from INTEGER, + valid_until INTEGER, + days TEXT, + time_start TEXT, + time_end TEXT, + models TEXT, + tokens_hour INTEGER, tokens_day INTEGER, tokens_week INTEGER, tokens_month INTEGER, + tokens_total INTEGER, + requests_hour INTEGER, requests_day INTEGER, requests_week INTEGER, + requests_month INTEGER, requests_total INTEGER, + note TEXT NOT NULL, + created_at INTEGER NOT NULL + ); + -- Verbrauch je Key bzw. Kontingent und Zeitraum (z. B. day:2026-11-20). Die Zähler + -- bleiben erhalten, wenn alte Einträge in usage gelöscht werden. + CREATE TABLE IF NOT EXISTS usage_counters ( + scope TEXT NOT NULL, + scope_id INTEGER NOT NULL, + period TEXT NOT NULL, + requests INTEGER NOT NULL DEFAULT 0, + prompt_tokens INTEGER NOT NULL DEFAULT 0, + completion_tokens INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (scope, scope_id, period) + ); + CREATE INDEX IF NOT EXISTS usage_ts ON usage (ts); CREATE TABLE IF NOT EXISTS audit_log ( id INTEGER PRIMARY KEY, ts INTEGER NOT NULL, @@ -120,26 +173,36 @@ impl Db { } /// Legt einen Key an und gibt ihn im Klartext zurück. Gespeichert wird nur der Hash. - pub fn create_key(&self, name: &str, is_super: bool) -> Result<(i64, String)> { + pub fn create_key(&self, name: &str, is_super: bool, quota_id: Option) -> Result<(i64, String)> { + if is_super && quota_id.is_some() { + bail!("Super-Keys haben kein Kontingent"); + } + if let Some(id) = quota_id + && self.quota(id)?.is_none() + { + bail!("kein Kontingent mit ID {id}"); + } let mut bytes = [0u8; 24]; rand::rng().fill_bytes(&mut bytes); let key = format!("omega-{}", hex::encode(bytes)); let prefix = key[..14].to_string(); let conn = self.conn(); conn.execute( - "INSERT INTO api_keys (name, key_hash, prefix, created_at, is_super) VALUES (?1, ?2, ?3, ?4, ?5)", - params![name, hash_key(&key), prefix, now(), is_super], + "INSERT INTO api_keys (name, key_hash, prefix, created_at, is_super, quota_id) + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![name, hash_key(&key), prefix, now(), is_super, quota_id], )?; let id = conn.last_insert_rowid(); drop(conn); - self.audit("cli", "key.create", &format!("id={id} name={name} super={is_super}"))?; + self.audit("cli", "key.create", &format!("id={id} name={name} super={is_super} quota={quota_id:?}"))?; Ok((id, key)) } pub fn list_keys(&self) -> Result> { let conn = self.conn(); let mut stmt = conn.prepare( - "SELECT id, name, prefix, created_at, revoked_at IS NOT NULL, is_super FROM api_keys ORDER BY id", + "SELECT id, name, prefix, revoked_at IS NOT NULL, is_super, quota_id + FROM api_keys ORDER BY id", )?; let keys = stmt .query_map([], |r| { @@ -147,9 +210,9 @@ impl Db { id: r.get(0)?, name: r.get(1)?, prefix: r.get(2)?, - created_at: r.get(3)?, - revoked: r.get(4)?, - is_super: r.get(5)?, + revoked: r.get(3)?, + is_super: r.get(4)?, + quota_id: r.get(5)?, }) })? .collect::>()?; @@ -172,9 +235,9 @@ impl Db { Ok(self .conn() .query_row( - "SELECT id, is_super FROM api_keys WHERE key_hash = ?1 AND revoked_at IS NULL", + "SELECT id, is_super, quota_id FROM api_keys WHERE key_hash = ?1 AND revoked_at IS NULL", params![hash_key(key)], - |r| Ok(Caller { key_id: r.get(0)?, is_super: r.get(1)? }), + |r| Ok(Caller { key_id: r.get(0)?, is_super: r.get(1)?, quota_id: r.get(2)? }), ) .optional()?) } @@ -182,8 +245,8 @@ impl Db { pub fn record_usage(&self, u: &Usage) -> Result<()> { self.conn().execute( "INSERT INTO usage (ts, key_id, engine, model, path, status, prompt_tokens, - completion_tokens, duration_ms) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + completion_tokens, duration_ms, quota_id) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", params![ now(), u.key_id, @@ -193,7 +256,8 @@ impl Db { u.status, u.prompt_tokens, u.completion_tokens, - u.duration_ms + u.duration_ms, + u.quota_id ], )?; Ok(()) @@ -344,6 +408,204 @@ impl Db { Ok(changed > 0) } + pub fn set_key_quota(&self, key_id: i64, quota_id: Option) -> Result<()> { + if let Some(id) = quota_id + && self.quota(id)?.is_none() + { + bail!("kein Kontingent mit ID {id}"); + } + let changed = self.conn().execute( + "UPDATE api_keys SET quota_id = ?1 WHERE id = ?2 AND is_super = 0", + params![quota_id, key_id], + )?; + if changed == 0 { + bail!("kein Key mit ID {key_id}, oder es ist ein Super-Key"); + } + self.audit("cli", "key.quota", &format!("id={key_id} quota={quota_id:?}")) + } + + pub fn create_quota(&self, q: &Quota) -> Result { + let (days, start, end) = match &q.time.weekly { + Some(w) => ( + Some(schedule::days_str(&w.days)), + Some(w.start.format("%H:%M").to_string()), + Some(w.end.format("%H:%M").to_string()), + ), + None => (None, None, None), + }; + let models = q.models.as_ref().map(serde_json::to_string).transpose()?; + let limits: Vec> = Period::ALL + .iter() + .map(|p| q.tokens.get(*p)) + .chain(Period::ALL.iter().map(|p| q.requests.get(*p))) + .collect(); + let conn = self.conn(); + conn.execute( + "INSERT INTO quotas (name, valid_from, valid_until, days, time_start, time_end, models, + tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note, created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)", + params![ + q.name, q.time.from, q.time.until, days, start, end, models, limits[0], limits[1], limits[2], + limits[3], limits[4], limits[5], limits[6], limits[7], limits[8], limits[9], q.note, now() + ], + )?; + let id = conn.last_insert_rowid(); + drop(conn); + self.audit("cli", "quota.create", &format!("id={id} {}: {}", q.name, q.describe()))?; + Ok(id) + } + + fn quotas_where(&self, filter: &str, args: &[&dyn rusqlite::ToSql]) -> Result> { + let conn = self.conn(); + let mut stmt = conn.prepare(&format!( + "SELECT id, name, valid_from, valid_until, days, time_start, time_end, models, tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note + FROM quotas {filter} ORDER BY id" + ))?; + let mut rows = stmt.query(args)?; + let mut list = Vec::new(); + while let Some(r) = rows.next()? { + let weekly = match (r.get::<_, Option>(4)?, r.get::<_, Option>(5)?, r.get::<_, Option>(6)?) { + (Some(days), Some(start), Some(end)) => { + let (start, end) = schedule::parse_time_range(&format!("{start}-{end}"))?; + Some(Weekly { days: schedule::parse_days(&days)?, start, end }) + } + _ => None, + }; + let models: Option = r.get(7)?; + let (mut tokens, mut requests) = (Limits::default(), Limits::default()); + for (i, p) in Period::ALL.iter().enumerate() { + tokens.set(*p, r.get(8 + i)?); + requests.set(*p, r.get(13 + i)?); + } + list.push(Quota { + id: r.get(0)?, + name: r.get(1)?, + time: TimeSpec { from: r.get(2)?, until: r.get(3)?, weekly }, + models: models.map(|m| serde_json::from_str(&m)).transpose()?, + tokens, + requests, + note: r.get(18)?, + }); + } + Ok(list) + } + + pub fn quota(&self, id: i64) -> Result> { + Ok(self.quotas_where("WHERE id = ?1", &[&id])?.pop()) + } + + pub fn list_quotas(&self) -> Result> { + self.quotas_where("", &[]) + } + + /// Nur ein Kontingent, an dem keine Keys mehr hängen, kann entfernt werden. + pub fn remove_quota(&self, id: i64) -> Result<()> { + let conn = self.conn(); + let keys: i64 = conn.query_row("SELECT count(*) FROM api_keys WHERE quota_id = ?1", params![id], |r| r.get(0))?; + if keys > 0 { + bail!("am Kontingent {id} hängen noch {keys} Keys"); + } + if conn.execute("DELETE FROM quotas WHERE id = ?1", params![id])? == 0 { + bail!("kein Kontingent mit ID {id}"); + } + conn.execute("DELETE FROM usage_counters WHERE scope = 'quota' AND scope_id = ?1", params![id])?; + drop(conn); + self.audit("cli", "quota.remove", &format!("id={id}")) + } + + /// Verbrauch in den Zeiträumen, in die t fällt + fn counters(conn: &Connection, scope: Scope, t: DateTime) -> Result> { + let (scope, id) = scope.parts(); + let mut stmt = conn.prepare_cached( + "SELECT requests, prompt_tokens, completion_tokens FROM usage_counters + WHERE scope = ?1 AND scope_id = ?2 AND period = ?3", + )?; + Period::ALL + .iter() + .map(|p| { + let c = stmt + .query_row(params![scope, id, p.key(t)], |r| { + Ok(Counter { requests: r.get(0)?, prompt_tokens: r.get(1)?, completion_tokens: r.get(2)? }) + }) + .optional()? + .unwrap_or_default(); + Ok((*p, c)) + }) + .collect() + } + + pub fn usage_of(&self, scope: Scope, t: DateTime) -> Result> { + Self::counters(&self.conn(), scope, t) + } + + /// Addiert (oder bei negativen Werten subtrahiert) in allen Zeiträumen von t. + fn add(conn: &Connection, scope: Scope, t: DateTime, requests: i64, prompt: i64, completion: i64) -> Result<()> { + let (scope, id) = scope.parts(); + let mut stmt = conn.prepare_cached( + "INSERT INTO usage_counters (scope, scope_id, period, requests, prompt_tokens, completion_tokens) + VALUES (?1, ?2, ?3, ?4, ?5, ?6) + ON CONFLICT (scope, scope_id, period) DO UPDATE SET + requests = requests + excluded.requests, + prompt_tokens = prompt_tokens + excluded.prompt_tokens, + completion_tokens = completion_tokens + excluded.completion_tokens", + )?; + for p in Period::ALL { + stmt.execute(params![scope, id, p.key(t), requests, prompt, completion])?; + } + Ok(()) + } + + fn scopes(key_id: i64, quota_id: Option) -> Vec { + std::iter::once(Scope::Key(key_id)).chain(quota_id.map(Scope::Quota)).collect() + } + + /// Prüft das Kontingent und zählt die Anfrage, in einer Transaktion, damit gleichzeitige + /// Anfragen die Grenzen nicht gemeinsam überschreiten. `quota` ist None für Keys ohne + /// Kontingent und für Super-Keys; gezählt wird beim Key trotzdem. + pub fn begin_request(&self, key_id: i64, quota: Option<&Quota>, t: DateTime) -> Result> { + let mut conn = self.conn(); + let tx = conn.transaction()?; + if let Some(q) = quota + && let Err(denial) = q.check_usage(&Self::counters(&tx, Scope::Quota(q.id), t)?, t) + { + return Ok(Err(denial)); + } + for scope in Self::scopes(key_id, quota.map(|q| q.id)) { + Self::add(&tx, scope, t, 1, 0, 0)?; + } + tx.commit()?; + Ok(Ok(())) + } + + /// Nimmt eine gezählte Anfrage zurück, die die Engine nie erreicht hat (z. B. Modell nicht ladbar). + pub fn refund_request(&self, key_id: i64, quota_id: Option, t: DateTime) -> Result<()> { + let mut conn = self.conn(); + let tx = conn.transaction()?; + for scope in Self::scopes(key_id, quota_id) { + Self::add(&tx, scope, t, -1, 0, 0)?; + } + Ok(tx.commit()?) + } + + /// Bucht die Token einer beendeten Anfrage in die Zeiträume ihres Beginns. + pub fn book_tokens(&self, key_id: i64, quota_id: Option, t: DateTime, prompt: u64, completion: u64) -> Result<()> { + let mut conn = self.conn(); + let tx = conn.transaction()?; + for scope in Self::scopes(key_id, quota_id) { + Self::add(&tx, scope, t, 0, prompt as i64, completion as i64)?; + } + Ok(tx.commit()?) + } + + /// Löscht Einzeleinträge der Nutzung, die älter als `days` Tage sind. Die Zähler der + /// Kontingente und Keys bleiben unberührt. + pub fn prune_usage(&self, days: u32) -> Result { + let cutoff = now() - i64::from(days) * 86_400; + let deleted = self.conn().execute("DELETE FROM usage WHERE ts < ?1", params![cutoff])?; + self.audit("cli", "usage.prune", &format!("older_than_days={days} deleted={deleted}"))?; + Ok(deleted) + } + pub fn audit(&self, actor: &str, action: &str, detail: &str) -> Result<()> { self.conn().execute( "INSERT INTO audit_log (ts, actor, action, detail) VALUES (?1, ?2, ?3, ?4)", @@ -364,6 +626,12 @@ fn migrate(conn: &Connection) -> Result<()> { if !has_column(conn, "api_keys", "is_super")? { conn.execute("ALTER TABLE api_keys ADD COLUMN is_super INTEGER NOT NULL DEFAULT 0", [])?; } + if !has_column(conn, "api_keys", "quota_id")? { + conn.execute("ALTER TABLE api_keys ADD COLUMN quota_id INTEGER REFERENCES quotas(id)", [])?; + } + if !has_column(conn, "usage", "quota_id")? { + conn.execute("ALTER TABLE usage ADD COLUMN quota_id INTEGER", [])?; + } // Pins lagen bis zum gemeinsamen Zeitplan in einer eigenen Tabelle. let has_pins: bool = conn.query_row( "SELECT count(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = 'pins'", diff --git a/proxy/src/forward.rs b/proxy/src/forward.rs index da73395..6d0b9b7 100644 --- a/proxy/src/forward.rs +++ b/proxy/src/forward.rs @@ -72,6 +72,12 @@ pub async fn forward(http: &reqwest::Client, db: Arc, f: Forward) -> Respons tracing::warn!("{}: {e}", f.url); usage.status = StatusCode::BAD_GATEWAY.as_u16(); usage.duration_ms = started.elapsed().as_millis() as u64; + // Die Anfrage hat die Engine nie erreicht und zählt deshalb nicht. + if let Some(t) = usage.counted_at.take() + && let Err(e) = db.refund_request(usage.key_id, usage.quota_id, t) + { + tracing::warn!("Anfrage nicht zurückgebucht: {e:#}"); + } if f.record { record(&db, &usage); } @@ -100,10 +106,17 @@ pub async fn forward(http: &reqwest::Client, db: Arc, f: Forward) -> Respons .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()) } +/// Speichert die Anfrage und bucht ihre Token, falls sie gezählt wurde. fn record(db: &Db, usage: &Usage) { if let Err(e) = db.record_usage(usage) { tracing::warn!("Nutzung nicht gespeichert: {e:#}"); } + if let Some(t) = usage.counted_at { + let (prompt, completion) = (usage.prompt_tokens.unwrap_or(0), usage.completion_tokens.unwrap_or(0)); + if let Err(e) = db.book_tokens(usage.key_id, usage.quota_id, t, prompt, completion) { + tracing::warn!("Token nicht gebucht: {e:#}"); + } + } } /// Leitet den Antwortstrom weiter und sucht zeilenweise nach Token-Zahlen. Wird der Strom diff --git a/proxy/src/main.rs b/proxy/src/main.rs index c7025c1..dbecf7d 100644 --- a/proxy/src/main.rs +++ b/proxy/src/main.rs @@ -2,6 +2,7 @@ mod config; mod db; mod engines; mod forward; +mod quota; mod routes; mod schedule; mod scheduler; @@ -13,8 +14,9 @@ use clap::{Args, Parser, Subcommand}; use crate::{ config::Config, - db::Db, + db::{Db, Scope}, engines::Engine, + quota::{Limits, Period, Quota}, routes::AppState, schedule::{Entry, Kind, TimeSpec, Weekly}, scheduler::Scheduler, @@ -39,6 +41,67 @@ enum Command { /// Zeitplan: Pins, exklusive Nutzung und Modellzeitfenster #[command(subcommand)] Schedule(ScheduleCommand), + /// Kontingente: wie viel Keys nutzen dürfen + #[command(subcommand)] + Quota(QuotaCommand), + /// Gespeicherte Nutzung + #[command(subcommand)] + Usage(UsageCommand), +} + +/// Höchstwerte je Zeitraum (Kalenderzeiträume in Ortszeit); ohne Angabe unbegrenzt +#[derive(Args)] +struct LimitArgs { + #[arg(long)] + tokens_hour: Option, + #[arg(long)] + tokens_day: Option, + #[arg(long)] + tokens_week: Option, + #[arg(long)] + tokens_month: Option, + #[arg(long)] + tokens_total: Option, + #[arg(long)] + requests_hour: Option, + #[arg(long)] + requests_day: Option, + #[arg(long)] + requests_week: Option, + #[arg(long)] + requests_month: Option, + #[arg(long)] + requests_total: Option, +} + +#[derive(Subcommand)] +#[allow(clippy::large_enum_variant)] +enum QuotaCommand { + /// Kontingent anlegen; --from/--until begrenzen die Gültigkeit, --weekly/--time die Nutzungszeiten + Create { + name: String, + #[command(flatten)] + limits: LimitArgs, + /// Nur diese Modelle, als engine/modell, z. B. "ollama/qwen3:0.6b,vllm/qwen2.5-0.5b" + #[arg(long, value_delimiter = ',')] + models: Option>, + #[command(flatten)] + time: TimeArgs, + }, + List, + /// Verbrauch je Zeitraum + Show { id: i64 }, + /// Kontingent entfernen; es dürfen keine Keys mehr daran hängen + Remove { id: i64 }, +} + +#[derive(Subcommand)] +enum UsageCommand { + /// Einzeleinträge löschen, die älter als N Tage sind; die Zähler der Kontingente bleiben + Prune { + #[arg(long)] + older_than_days: u32, + }, } #[derive(Subcommand)] @@ -47,11 +110,17 @@ enum KeyCommand { Create { name: String, /// Super-Key: darf unabhängig von allen Einschränkungen immer alles - #[arg(long = "super")] + #[arg(long = "super", conflicts_with = "quota")] is_super: bool, + /// Kontingent, gegen das der Key abgerechnet wird; ohne ist er unbegrenzt + #[arg(long)] + quota: Option, }, + /// Keys mit Verbrauch heute und insgesamt List, Revoke { id: i64 }, + /// Kontingent eines Keys ändern: ID oder "none" für unbegrenzt + Quota { id: i64, quota: String }, } /// Wann ein Eintrag gilt; ohne Angaben dauerhaft @@ -119,20 +188,61 @@ async fn main() -> Result<()> { match cli.command { Command::Serve => serve(config, db).await, - Command::Key(KeyCommand::Create { name, is_super }) => { - let (id, key) = db.create_key(&name, is_super)?; + Command::Key(KeyCommand::Create { name, is_super, quota }) => { + let (id, key) = db.create_key(&name, is_super, quota)?; let kind = if is_super { "Super-Key" } else { "Key" }; println!("{kind} {id} ({name}): {key}"); Ok(()) } Command::Key(KeyCommand::List) => { + let now = chrono::Local::now(); + let quotas = db.list_quotas()?; + println!( + "{:>4} {:<20} {:<17} {:<10} {:<24} {:>10} {:>8} {:>12} {:>8}", + "ID", "Name", "Präfix", "Zustand", "Kontingent", "Token heute", "Anfr. heute", "Token gesamt", "Anfr. ges." + ); for k in db.list_keys()? { let state = if k.revoked { "widerrufen" } else { "aktiv" }; - let kind = if k.is_super { "super" } else { "" }; - println!("{:>4} {:<24} {}… {} {state:<10} {kind}", k.id, k.name, k.prefix, k.created_at); + let quota = match (k.is_super, k.quota_id) { + (true, _) => "Super-Key".to_string(), + (false, None) => "unbegrenzt".to_string(), + (false, Some(id)) => quotas + .iter() + .find(|q| q.id == id) + .map(|q| format!("{} (#{id})", q.name)) + .unwrap_or_else(|| format!("#{id} fehlt")), + }; + let usage = db.usage_of(Scope::Key(k.id), now)?; + let get = |p: Period| usage.iter().find(|(q, _)| *q == p).map(|(_, c)| *c).unwrap_or_default(); + let (day, total) = (get(Period::Day), get(Period::Total)); + println!( + "{:>4} {:<20} {}… {state:<10} {quota:<24} {:>10} {:>8} {:>12} {:>8}", + k.id, + k.name, + k.prefix, + day.tokens(), + day.requests, + total.tokens(), + total.requests + ); } Ok(()) } + Command::Key(KeyCommand::Quota { id, quota }) => { + let quota = match quota.as_str() { + "none" => None, + id => Some(id.parse().context("Kontingent als ID oder \"none\" angeben")?), + }; + db.set_key_quota(id, quota)?; + println!("Key {id}: Kontingent {}", quota.map(|q| format!("#{q}")).unwrap_or("unbegrenzt".into())); + Ok(()) + } + Command::Quota(cmd) => quota_command(config, db, cmd).await, + Command::Usage(UsageCommand::Prune { older_than_days }) => { + let deleted = db.prune_usage(older_than_days)?; + println!("{deleted} Einträge gelöscht; die Zähler der Kontingente und Keys bleiben erhalten"); + Ok(()) + } Command::Key(KeyCommand::Revoke { id }) => { if !db.revoke_key(id)? { bail!("kein aktiver Key mit ID {id}"); @@ -281,6 +391,80 @@ async fn add_entry(config: Config, db: Arc, cmd: ScheduleCommand) -> Result< Ok(()) } +async fn quota_command(config: Config, db: Arc, cmd: QuotaCommand) -> Result<()> { + let now = chrono::Local::now(); + match cmd { + QuotaCommand::Create { name, limits, models, time } => { + let models = match models { + None => None, + Some(models) => { + // Der Scheduler fragt die Engines, welche Modelle es gibt. + let sched = Scheduler::new(config.nodes, config.scheduler, db.clone())?; + sched.reconcile().await; + let mut normalized = Vec::new(); + for m in &models { + let (engine, engine_name, model) = parse_model(m)?; + if sched.nodes_offering(engine, &model).is_empty() { + bail!("{engine_name}/{model} wird auf keinem Rechner angeboten"); + } + normalized.push(format!("{engine_name}/{model}")); + } + Some(normalized) + } + }; + let tokens = Limits { + hour: limits.tokens_hour, + day: limits.tokens_day, + week: limits.tokens_week, + month: limits.tokens_month, + total: limits.tokens_total, + }; + let requests = Limits { + hour: limits.requests_hour, + day: limits.requests_day, + week: limits.requests_week, + month: limits.requests_month, + total: limits.requests_total, + }; + let quota = Quota { id: 0, name, time: time_spec(&time, now)?, models, tokens, requests, note: time.note }; + let id = db.create_quota("a)?; + println!("Kontingent {id}: {}: {}", quota.name, quota.describe()); + Ok(()) + } + QuotaCommand::List => { + let keys = db.list_keys()?; + for q in db.list_quotas()? { + let n = keys.iter().filter(|k| k.quota_id == Some(q.id) && !k.revoked).count(); + println!("{:>4} {:<24} {n} Keys {}", q.id, q.name, q.describe()); + } + Ok(()) + } + QuotaCommand::Show { id } => { + let q = db.quota(id)?.with_context(|| format!("kein Kontingent mit ID {id}"))?; + println!("{} (#{id}): {}", q.name, q.describe()); + println!("{:<10} {:>12} {:>12} {:>10} {:>10} endet", "Zeitraum", "Token", "Grenze", "Anfragen", "Grenze"); + for (p, c) in db.usage_of(Scope::Quota(id), now)? { + let limit = |l: Option| l.map(|v| v.to_string()).unwrap_or("-".into()); + let end = p.end(now).map(|t| t.format("%d.%m.%Y %H:%M").to_string()).unwrap_or_default(); + println!( + "{:<10} {:>12} {:>12} {:>10} {:>10} {end}", + p.id(), + c.tokens(), + limit(q.tokens.get(p)), + c.requests, + limit(q.requests.get(p)) + ); + } + Ok(()) + } + QuotaCommand::Remove { id } => { + db.remove_quota(id)?; + println!("Kontingent {id} entfernt"); + Ok(()) + } + } +} + async fn serve(config: Config, db: Arc) -> Result<()> { let sched = Scheduler::new(config.nodes, config.scheduler, db.clone())?; sched.spawn_reconciler(); diff --git a/proxy/src/quota.rs b/proxy/src/quota.rs new file mode 100644 index 0000000..dc65fc5 --- /dev/null +++ b/proxy/src/quota.rs @@ -0,0 +1,299 @@ +//! Kontingente: wie viel ein Key nutzen darf. +//! +//! Ein Kontingent begrenzt Token und Anfragen je Stunde, Tag, Woche, Monat und insgesamt, kann +//! zeitlich gelten (Beginn, Ablauf, Nutzungszeiten) und die Modelle einschränken. Mehrere Keys +//! können sich ein Kontingent teilen. Die Zeiträume sind Kalenderzeiträume in Ortszeit: Ein +//! Tageskontingent beginnt um Mitternacht neu, ein Wochenkontingent am Montag. +//! +//! Abgerechnet wird wie folgt: Eine Anfrage darf starten, solange das Kontingent nicht +//! ausgeschöpft ist. Sie zählt beim Start als Anfrage; ihre Token werden nach der Antwort gebucht. +//! Die letzte Anfrage kann ein Token-Kontingent also leicht überschreiten. + +use chrono::{DateTime, Datelike, Duration, Local, NaiveDate, NaiveTime, TimeZone, Timelike}; + +use crate::schedule::TimeSpec; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Period { + Hour, + Day, + Week, + Month, + Total, +} + +impl Period { + pub const ALL: [Period; 5] = [Period::Hour, Period::Day, Period::Week, Period::Month, Period::Total]; + + /// Spaltenname und Kurzform auf der Kommandozeile + pub fn id(self) -> &'static str { + match self { + Period::Hour => "hour", + Period::Day => "day", + Period::Week => "week", + Period::Month => "month", + Period::Total => "total", + } + } + + fn phrase(self) -> &'static str { + match self { + Period::Hour => "in dieser Stunde", + Period::Day => "heute", + Period::Week => "in dieser Woche", + Period::Month => "in diesem Monat", + Period::Total => "insgesamt", + } + } + + /// Schlüssel des Zeitraums, in den t fällt, z. B. "day:2026-11-20" + pub fn key(self, t: DateTime) -> String { + match self { + Period::Hour => t.format("hour:%Y-%m-%dT%H").to_string(), + Period::Day => t.format("day:%Y-%m-%d").to_string(), + Period::Week => t.format("week:%G-W%V").to_string(), + Period::Month => t.format("month:%Y-%m").to_string(), + Period::Total => "total".into(), + } + } + + /// Beginn des nächsten Zeitraums; None für "insgesamt" + pub fn end(self, t: DateTime) -> Option> { + let midnight = |d: NaiveDate| Local.from_local_datetime(&d.and_time(NaiveTime::MIN)).earliest(); + let today = t.date_naive(); + match self { + Period::Hour => Some(t.with_minute(0)?.with_second(0)?.with_nanosecond(0)? + Duration::hours(1)), + Period::Day => midnight(today.succ_opt()?), + Period::Week => midnight(today + Duration::days(7 - today.weekday().num_days_from_monday() as i64)), + Period::Month => { + let (y, m) = if today.month() == 12 { (today.year() + 1, 1) } else { (today.year(), today.month() + 1) }; + midnight(NaiveDate::from_ymd_opt(y, m, 1)?) + } + Period::Total => None, + } + } +} + +/// Höchstwerte je Zeitraum; None heißt unbegrenzt +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Limits { + pub hour: Option, + pub day: Option, + pub week: Option, + pub month: Option, + pub total: Option, +} + +impl Limits { + pub fn get(&self, p: Period) -> Option { + match p { + Period::Hour => self.hour, + Period::Day => self.day, + Period::Week => self.week, + Period::Month => self.month, + Period::Total => self.total, + } + } + + pub fn set(&mut self, p: Period, v: Option) { + match p { + Period::Hour => self.hour = v, + Period::Day => self.day = v, + Period::Week => self.week = v, + Period::Month => self.month = v, + Period::Total => self.total = v, + } + } + + fn describe(&self, unit: &str) -> Vec { + Period::ALL + .iter() + .filter_map(|p| self.get(*p).map(|v| format!("{v} {unit}/{}", p.id()))) + .collect() + } +} + +/// Verbrauch in einem Zeitraum +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Counter { + pub requests: u64, + pub prompt_tokens: u64, + pub completion_tokens: u64, +} + +impl Counter { + pub fn tokens(&self) -> u64 { + self.prompt_tokens + self.completion_tokens + } +} + +#[derive(Clone, Debug)] +pub struct Quota { + pub id: i64, + pub name: String, + /// Beginn, Ablauf und Nutzungszeiten + pub time: TimeSpec, + /// Erlaubte Modelle als "engine/modell"; None heißt alle + pub models: Option>, + pub tokens: Limits, + pub requests: Limits, + pub note: String, +} + +/// Warum eine Anfrage nicht starten darf +#[derive(Debug, PartialEq)] +pub enum Denial { + /// Nicht erlaubt: abgelaufen, außerhalb der Nutzungszeiten, Modell nicht freigegeben (403) + Forbidden(String), + /// Kontingent für einen Zeitraum ausgeschöpft (429) + Exhausted(String), +} + +fn fmt(t: DateTime) -> String { + t.format("%d.%m.%Y %H:%M").to_string() +} + +impl Quota { + /// Zeitraum, Nutzungszeiten und Modelle; `model` als "engine/modell" + pub fn check_access(&self, model: &str, now: DateTime) -> Result<(), Denial> { + let at = |ts: i64| Local.timestamp_opt(ts, 0).single(); + if let Some(from) = self.time.from.filter(|f| now.timestamp() < *f).and_then(at) { + return Err(Denial::Forbidden(format!("Kontingent {} gilt erst ab {}", self.name, fmt(from)))); + } + if let Some(until) = self.time.until.filter(|u| now.timestamp() >= *u).and_then(at) { + return Err(Denial::Forbidden(format!("Kontingent {} ist am {} abgelaufen", self.name, fmt(until)))); + } + if !self.time.active_at(now) { + return Err(Denial::Forbidden(format!( + "Kontingent {} ist nur zu diesen Zeiten nutzbar: {}", + self.name, + self.time.describe() + ))); + } + if let Some(models) = &self.models + && !models.iter().any(|m| m == model) + { + return Err(Denial::Forbidden(format!( + "{model} ist mit dem Kontingent {} nicht nutzbar; freigegeben: {}", + self.name, + models.join(", ") + ))); + } + Ok(()) + } + + /// Ist in jedem Zeitraum noch etwas übrig? `usage` enthält den Verbrauch der laufenden Zeiträume. + pub fn check_usage(&self, usage: &[(Period, Counter)], now: DateTime) -> Result<(), Denial> { + for (period, counter) in usage { + let checks = [ + (self.tokens.get(*period), counter.tokens(), "Token"), + (self.requests.get(*period), counter.requests, "Anfragen"), + ]; + for (limit, used, unit) in checks { + if let Some(limit) = limit + && used >= limit + { + let again = period.end(now).map(|t| format!(", wieder ab {}", fmt(t))).unwrap_or_default(); + return Err(Denial::Exhausted(format!( + "Kontingent {} ausgeschöpft: {used} von {limit} {unit} {}{again}", + self.name, + period.phrase() + ))); + } + } + } + Ok(()) + } + + pub fn describe(&self) -> String { + let mut parts = self.tokens.describe("Token"); + parts.extend(self.requests.describe("Anfragen")); + if parts.is_empty() { + parts.push("ohne Mengengrenzen".into()); + } + if self.time.from.is_some() || self.time.until.is_some() || self.time.weekly.is_some() { + parts.push(self.time.describe()); + } + if let Some(models) = &self.models { + parts.push(format!("Modelle: {}", models.join(", "))); + } + parts.join("; ") + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::schedule::{Weekly, parse_days, parse_time_range, parse_when}; + + fn at(s: &str) -> DateTime { + parse_when(s, Local::now()).unwrap() + } + + fn quota() -> Quota { + Quota { + id: 1, + name: "KI-Praktikum".into(), + time: TimeSpec::default(), + models: None, + tokens: Limits { day: Some(1000), ..Default::default() }, + requests: Limits { hour: Some(3), ..Default::default() }, + note: String::new(), + } + } + + #[test] + fn period_keys_and_ends() { + // Freitag, 20.11.2026, KW 47 + let t = at("2026-11-20 12:34:56"); + assert_eq!(Period::Hour.key(t), "hour:2026-11-20T12"); + assert_eq!(Period::Day.key(t), "day:2026-11-20"); + assert_eq!(Period::Week.key(t), "week:2026-W47"); + assert_eq!(Period::Month.key(t), "month:2026-11"); + assert_eq!(Period::Hour.end(t), Some(at("2026-11-20 13:00"))); + assert_eq!(Period::Day.end(t), Some(at("2026-11-21"))); + assert_eq!(Period::Week.end(t), Some(at("2026-11-23"))); + assert_eq!(Period::Month.end(t), Some(at("2026-12-01"))); + assert_eq!(Period::Month.end(at("2026-12-31 23:59")), Some(at("2027-01-01"))); + assert_eq!(Period::Week.end(at("2026-11-23 00:00")), Some(at("2026-11-30")), "Montag gehört zur neuen Woche"); + // ISO-Woche über den Jahreswechsel: Do 31.12.2026 liegt in KW 53 von 2026 + assert_eq!(Period::Week.key(at("2026-12-31 10:00")), "week:2026-W53"); + } + + #[test] + fn usage_limits() { + let q = quota(); + let now = at("2026-11-20 12:30"); + let usage = |requests: u64, tokens: u64| { + vec![ + (Period::Hour, Counter { requests, prompt_tokens: 0, completion_tokens: 0 }), + (Period::Day, Counter { requests, prompt_tokens: tokens / 2, completion_tokens: tokens - tokens / 2 }), + ] + }; + assert!(q.check_usage(&usage(2, 999), now).is_ok()); + let Err(Denial::Exhausted(m)) = q.check_usage(&usage(3, 0), now) else { panic!() }; + assert_eq!(m, "Kontingent KI-Praktikum ausgeschöpft: 3 von 3 Anfragen in dieser Stunde, wieder ab 20.11.2026 13:00"); + let Err(Denial::Exhausted(m)) = q.check_usage(&usage(0, 1000), now) else { panic!() }; + assert!(m.contains("1000 von 1000 Token heute, wieder ab 21.11.2026 00:00"), "{m}"); + } + + #[test] + fn access() { + let now = at("2026-11-20 12:30"); + let mut q = quota(); + q.models = Some(vec!["ollama/qwen3:0.6b".into()]); + assert!(q.check_access("ollama/qwen3:0.6b", now).is_ok()); + assert!(matches!(q.check_access("vllm/x", now), Err(Denial::Forbidden(_)))); + + q.time.until = Some(at("2026-11-20 12:00").timestamp()); + let Err(Denial::Forbidden(m)) = q.check_access("ollama/qwen3:0.6b", now) else { panic!() }; + assert_eq!(m, "Kontingent KI-Praktikum ist am 20.11.2026 12:00 abgelaufen"); + + q.time.until = None; + let (start, end) = parse_time_range("08:00-12:00").unwrap(); + q.time.weekly = Some(Weekly { days: parse_days("mo-fr").unwrap(), start, end }); + let Err(Denial::Forbidden(m)) = q.check_access("ollama/qwen3:0.6b", now) else { panic!() }; + assert!(m.contains("nur zu diesen Zeiten nutzbar: wöchentlich mo,di,mi,do,fr 08:00-12:00"), "{m}"); + assert!(q.check_access("ollama/qwen3:0.6b", at("2026-11-20 11:59")).is_ok()); + } +} diff --git a/proxy/src/routes.rs b/proxy/src/routes.rs index cc078c7..4ae7c5b 100644 --- a/proxy/src/routes.rs +++ b/proxy/src/routes.rs @@ -12,10 +12,13 @@ use axum::{ routing::{any, get}, }; use futures_util::future::join_all; +use chrono::{DateTime, Local}; use serde_json::{Value, json}; use crate::{ db::{Caller, Db, Usage}, + engines::normalize_model, + quota::Denial, engines::Engine, forward::{Forward, forward}, scheduler::{SchedError, Scheduler}, @@ -210,6 +213,44 @@ async fn merged_list(st: &AppState, engine: Engine, path: &str, field: &str) -> } } +fn denial(engine: Engine, d: Denial) -> Response { + match d { + Denial::Forbidden(m) => engine_error(engine, StatusCode::FORBIDDEN, &m), + Denial::Exhausted(m) => engine_error(engine, StatusCode::TOO_MANY_REQUESTS, &m), + } +} + +/// Prüft das Kontingent und zählt die Anfrage. Liefert den Zeitpunkt, in dessen Zeiträume die +/// Anfrage und später ihre Token gebucht werden. +#[allow(clippy::result_large_err)] +fn admit( + st: &AppState, + caller: Caller, + quota_id: Option, + engine: Engine, + model: &str, +) -> Result, Response> { + let now = Local::now(); + let internal = |e: anyhow::Error| { + tracing::error!("Kontingent: {e:#}"); + engine_error(engine, StatusCode::INTERNAL_SERVER_ERROR, "interner Fehler") + }; + let quota = match quota_id.map(|id| st.db.quota(id)).transpose().map_err(internal)? { + Some(None) => { + return Err(engine_error(engine, StatusCode::FORBIDDEN, "Das Kontingent dieses Keys existiert nicht mehr")); + } + quota => quota.flatten(), + }; + if let Some(q) = "a { + let model = format!("{}/{}", engine.as_str(), normalize_model(engine, model)); + q.check_access(&model, now).map_err(|d| denial(engine, d))?; + } + match st.db.begin_request(caller.key_id, quota.as_ref(), now).map_err(internal)? { + Ok(()) => Ok(now), + Err(d) => Err(denial(engine, d)), + } +} + fn is_openai_path(engine: Engine, path: &str) -> bool { path.starts_with("/v1/") || (engine != Engine::Ollama && !path.starts_with("/api/")) } @@ -234,23 +275,50 @@ async fn handle( let mut target = None; let mut guard = None; + let mut counted = None; + // Super-Keys werden keinem Kontingent belastet. + let quota_id = caller.filter(|c| !c.is_super).and_then(|c| c.quota_id); if let Some(model) = &model { - // Exklusive Nutzung und Modellzeitfenster, bevor ein Modell geladen wird - if let Some(caller) = caller - && let Err(message) = st.sched.check_access(caller, engine, model) - { - return engine_error(engine, StatusCode::FORBIDDEN, &message); + // /api/show liest nur Metadaten, braucht kein geladenes Modell und zählt nicht. + let inference = !(engine == Engine::Ollama && path == "/api/show"); + // Super-Keys dürfen notfalls auch gepinnte Modelle verdrängen. + let override_pins = caller.is_some_and(|c| c.is_super); + + // Exklusive Nutzung und Modellzeitfenster, dann das Kontingent; alles, bevor ein Modell + // geladen wird + if let Some(caller) = caller { + if let Err(message) = st.sched.check_access(caller, engine, model) { + return engine_error(engine, StatusCode::FORBIDDEN, &message); + } + if inference { + match admit(&st, caller, quota_id, engine, model) { + Ok(t) => counted = Some(t), + Err(response) => return response, + } + } } - let key = match st.sched.locate(engine, model).await { + // Eine Anfrage, die die Engine nicht erreicht, zählt nicht. + let refund = || { + if let (Some(caller), Some(t)) = (caller, counted) + && let Err(e) = st.db.refund_request(caller.key_id, quota_id, t) + { + tracing::warn!("Anfrage nicht zurückgebucht: {e:#}"); + } + }; + + let key = match st.sched.locate(engine, model, override_pins).await { Ok(key) => key, - Err(e) => return engine_error(engine, StatusCode::NOT_FOUND, &e.to_string()), + Err(e) => { + refund(); + return engine_error(engine, StatusCode::NOT_FOUND, &e.to_string()); + } }; target = st.sched.model_url(&key); - // /api/show liest nur Metadaten und braucht kein geladenes Modell. - if !(engine == Engine::Ollama && path == "/api/show") { - match st.sched.acquire(key).await { + if inference { + match st.sched.acquire(key, override_pins).await { Ok(g) => guard = Some(g), Err(e) => { + refund(); let status = match e { SchedError::UnknownModel(_) => StatusCode::NOT_FOUND, SchedError::Timeout(_) => StatusCode::SERVICE_UNAVAILABLE, @@ -308,6 +376,8 @@ async fn handle( engine: engine.as_str(), model, path: path.clone(), + quota_id, + counted_at: counted, ..Default::default() }; // Unauthentifizierte Statusabfragen ("/", /api/version) werden nicht verbucht. diff --git a/proxy/src/scheduler.rs b/proxy/src/scheduler.rs index b9a1709..bf9478e 100644 --- a/proxy/src/scheduler.rs +++ b/proxy/src/scheduler.rs @@ -192,7 +192,7 @@ impl Scheduler { /// Wählt unter den Rechnern, die das Modell anbieten: zuerst einen, auf dem es schon /// geladen ist oder gerade lädt, dann den mit dem meisten freien Speicher, zuletzt den, /// auf dem am meisten ungenutzter Speicher verdrängt werden kann. - fn choose_node(&self, engine: Engine, model: &str) -> Option { + fn choose_node(&self, engine: Engine, model: &str, override_pins: bool) -> Option { let inner = self.lock(); let key = |node| ModelKey { node, engine, model: model.to_string() }; let candidates: Vec = self @@ -217,7 +217,9 @@ impl Scheduler { let slots = inner.slots.iter().filter(|(k, _)| k.node == i); let used: u64 = slots.clone().map(|(_, s)| s.mb).sum(); let evictable: u64 = slots - .filter(|(k, s)| s.state == SlotState::Loaded && s.in_flight == 0 && !inner.pinned.contains(k)) + .filter(|(k, s)| { + s.state == SlotState::Loaded && s.in_flight == 0 && (override_pins || !inner.pinned.contains(k)) + }) .map(|(_, s)| s.mb) .sum(); let free = inner.budget_mb[i].unwrap_or(0) as i64 - used as i64; @@ -232,13 +234,15 @@ impl Scheduler { /// Sucht den Rechner für das Modell. Ein neu installiertes Modell wird über einen /// erneuten Abgleich gefunden. - pub async fn locate(&self, engine: Engine, model: &str) -> Result { + /// + /// Mit `override_pins` (Super-Keys) zählen auch gepinnte Modelle als verdrängbar. + pub async fn locate(&self, engine: Engine, model: &str, override_pins: bool) -> Result { let model = normalize_model(engine, model); - let node = match self.choose_node(engine, &model) { + let node = match self.choose_node(engine, &model, override_pins) { Some(node) => node, None => { self.reconcile().await; - self.choose_node(engine, &model) + self.choose_node(engine, &model, override_pins) .ok_or_else(|| SchedError::UnknownModel(model.clone()))? } }; @@ -282,7 +286,9 @@ impl Scheduler { } /// Wartet, bis das Modell geladen ist, und reserviert es für eine Anfrage. - pub async fn acquire(self: &Arc, key: ModelKey) -> Result { + /// Mit `override_pins` (Super-Keys) dürfen auch gepinnte Modelle verdrängt werden, aber erst, + /// wenn ungepinnte nicht reichen. + pub async fn acquire(self: &Arc, key: ModelKey, override_pins: bool) -> Result { let deadline = tokio::time::Instant::now() + Duration::from_secs(self.cfg.max_wait_secs); let _waiting = WaitingGuard::new(self.clone(), key.clone()); loop { @@ -299,7 +305,7 @@ impl Scheduler { return Ok(Guard { sched: self.clone(), key }); } Some(_) => Action::Wait, - None => self.plan(&mut inner, &key), + None => self.plan(&mut inner, &key, override_pins), } }; @@ -351,7 +357,7 @@ impl Scheduler { /// Entscheidet, ob das Modell sofort geladen werden kann oder erst andere weichen müssen. /// In beiden Fällen wird der Platz sofort für das Modell reserviert, damit ihn keine andere /// wartende Anfrage belegt, während die Verdrängten entladen werden. - fn plan(&self, inner: &mut Inner, key: &ModelKey) -> Action { + fn plan(&self, inner: &mut Inner, key: &ModelKey, override_pins: bool) -> Action { let need = self.estimate_mb(inner, key); // Ohne bekannten Speicher wird nichts geladen, auch kein gepinntes Modell. let Some(budget) = inner.budget_mb[key.node] else { @@ -389,15 +395,19 @@ impl Scheduler { && s.state == SlotState::Loaded && s.in_flight == 0 && s.loaded_at.elapsed() >= min_resident - && !inner.pinned.contains(k) + && (override_pins || !inner.pinned.contains(k)) + }) + .map(|(k, s)| { + let order = (inner.pinned.contains(k), inner.waiting.get(k).copied().unwrap_or(0) > 0, s.last_used); + (order, k.clone(), s.mb) }) - .map(|(k, s)| (inner.waiting.get(k).copied().unwrap_or(0) > 0, s.last_used, k.clone(), s.mb)) .collect(); - candidates.sort_by_key(|(has_waiters, last_used, _, _)| (*has_waiters, *last_used)); + // Gepinnte zuletzt, dann solche mit Wartenden, dann die am längsten ungenutzten + candidates.sort_by_key(|(order, _, _)| *order); let mut victims = Vec::new(); let mut freed = 0; - for (_, _, k, mb) in candidates { + for (_, k, mb) in candidates { if used - freed + need <= budget { break; } @@ -697,7 +707,7 @@ impl Scheduler { let name = &sched.nodes[key.node].name; tracing::info!("{name}: lade gepinntes Modell {}/{}", key.engine.as_str(), key.model); // Wie eine Anfrage: wartet auf Platz und gibt das Modell sofort wieder frei. - if let Err(e) = sched.acquire(key.clone()).await { + if let Err(e) = sched.acquire(key.clone(), false).await { tracing::warn!("{name}: gepinntes Modell {} nicht geladen: {e}", key.model); sched.audit("pin.load_failed", &format!("{name} {} {}: {e}", key.engine.as_str(), key.model)); } diff --git a/tests/multispark/README.md b/tests/multispark/README.md index f8e6e5b..127b904 100644 --- a/tests/multispark/README.md +++ b/tests/multispark/README.md @@ -21,6 +21,7 @@ tests/multispark/stop.sh # Zeitplan; vor jedem Test stop.sh und start.sh, damit die Datenbank leer ist (cd tests/multispark && python3 pin_test.py) (cd tests/multispark && python3 schedule_test.py) +(cd tests/multispark && python3 quota_test.py) ``` Szenarien: parallele Ladevorgänge auf verschiedenen Sparks, Wahl des Sparks (geladen, dann @@ -34,3 +35,8 @@ Beginn eines Zeitraums und Freigabe nach dessen Ende, Entfernen von Pins. `schedule_test.py` prüft exklusive Nutzung und Modellzeitfenster: Abweisung anderer Keys bzw. Modelle mit Ende und Anlass, Super-Keys, Ablehnung überschneidender Einträge und nicht verfügbarer Pins, Ende nach Ablauf und ein wöchentliches Fenster über Mitternacht. + +`quota_test.py` prüft die Kontingente: Grenzen für Anfragen und Token, Übereinstimmung der +Zähler mit den Einzeleinträgen (auch gestreamt), gleichzeitige Anfragen gegen eine Grenze, +Rückbuchung, Modelle, Gültigkeit und Nutzungszeiten, Löschen alter Metadaten und Super-Keys, die +gepinnte Modelle verdrängen. diff --git a/tests/multispark/quota_test.py b/tests/multispark/quota_test.py new file mode 100644 index 0000000..4a4c93f --- /dev/null +++ b/tests/multispark/quota_test.py @@ -0,0 +1,215 @@ +"""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}")