diff --git a/Makefile b/Makefile index 3b89e79..cb02386 100644 --- a/Makefile +++ b/Makefile @@ -9,7 +9,7 @@ LDFLAGS ?= PREFIX ?= /usr/local J_WITH_TLS ?= auto -SRC = src/compress.c src/config.c src/conn.c src/http.c src/cache.c src/opencode.c src/junction.c +SRC = src/compress.c src/price.c src/config.c src/conn.c src/http.c src/cache.c src/opencode.c src/junction.c OBJ = $(SRC:.c=.o) TOOLS = tools/junction-wol diff --git a/examples/prices.conf b/examples/prices.conf new file mode 100644 index 0000000..9fc7acc --- /dev/null +++ b/examples/prices.conf @@ -0,0 +1,64 @@ +# junction — Preise und Budgets +# +# Alle Werte in US-Dollar pro Million Token. Quelle: die Preisseite des Anbieters, +# abgerufen am 5. November 2026 (ollama.com/pricing). Preise ändern sich — diese Datei +# ist eine Abschrift, keine Messung. Wer sie nicht pflegt, bekommt alte Zahlen. +# +# Spalten: modell input cached_input output [schlüssel=wert …] +# +# offpeak=IN,OUT Preis außerhalb der Hauptzeit (bei Ollama: werktags 12–18 UTC +# und das ganze Wochenende sind NICHT off-peak) +# budget=USD Monatsbudget oder Gegenwert, den der Anbieter dem Modell zubilligt +# requests=N/5h Anzahl Anfragen pro Zeitfenster +# +# Modelle ohne Eintrag kosten nicht 0, sondern unbekannt — das steht so im Log. +# +# --- Ollama Cloud (Pay as you go), Preise pro Million Token --------------------- +clef 0.24 0.24 0.24 +deepseek-v4.1-flash 0.30 0.006 1.20 offpeak=0.15,0.60 +deepseek-v4-pro 1.32 0.044 3.96 offpeak=0.66,1.98 +gemma4 0.14 0.05 0.40 +glm-5.3 1.40 0.26 4.40 +glm-5.3-flash 0.15 0.03 0.50 +glm-5.2 1.40 0.26 4.40 +gpt-oss:120b 0.15 0.014 0.60 +gpt-oss:20b 0.07 0.035 0.30 +kimi-k3.1-pro 2.00 0.20 10.00 +kimi-k3 3.00 0.30 15.00 +kimi-k2.7-code 0.95 0.19 4.00 +kimi-k2.6 0.95 0.16 4.00 +mimo-v2.6-flash 0.14 0.0028 0.28 +mimo-v2.6-pro 0.435 0.0036 0.87 +minimax-m3.1-flash 0.15 0.015 0.60 +minimax-m3 0.60 0.12 2.40 +minimax-m2.7 0.30 0.06 1.20 +mistral-large-4 0.70 0.07 2.10 +mistral-large-3 0.50 0.00 1.50 +muse-spark-open 1.25 0.15 4.25 +nemotron-3-nano 0.06 0.00 0.24 +nemotron-3-super 0.015 0.015 0.60 +nemotron-3-ultra 0.10 0.10 3.00 + +# --- OpenCode Go: Abo, kein Tokenpreis ------------------------------------------ +# +# Go kostet 10 USD im Monat (Go Plus 40) und begrenzt nicht das Geld, sondern die +# Anfragen pro Modell. Die Spalte budget ist hier der Gegenwert, den OpenCode dem Modell +# zubilligt, requests die Grenze pro Fünf-Stunden-Fenster. Ein Tokenpreis existiert +# nicht — deshalb in=out=0 und damit Kosten 0. Wer echte Kosten braucht, nimmt die +# Console (Pay as you go), nicht Go. +kimi-k3-go 0 0 0 budget=15 requests=110/5h +kimi-k3.1-pro-go 0 0 0 budget=15 requests=147/5h +deepseek-v4-pro-go 0 0 0 budget=15 requests=1050/5h +hy4-go 0 0 0 budget=60 requests=2710/5h +claude-haiku-5.5-go 0 0 0 budget=15 requests=3850/5h +minimax-m3.1-flash-go 0 0 0 budget=20 requests=3880/5h +gpt-6-luna-go 0 0 0 budget=15 requests=4230/5h +qwen3.7-plus-go 0 0 0 budget=60 requests=4300/5h +glm-5.3-flash-go 0 0 0 budget=60 requests=6320/5h +mimo-v2.6-flash-go 0 0 0 budget=60 requests=30100/5h +deepseek-v4.1-flash-go 0 0 0 budget=100 requests=43330/5h +muse-spark-open-go 0 0 0 budget=60 requests=45300/5h + +# Kein "*"-Eintrag: ein Modell ohne Zeile kostet unbekannt, nicht null. Lokale Boxen +# lassen sich bei Bedarf mit ihrem Modellnamen und 0.0 eintragen — dann steht dort +# ausdrücklich "kostenlos" statt "vielleicht". diff --git a/src/cache.c b/src/cache.c index 6a8c609..16015e2 100644 --- a/src/cache.c +++ b/src/cache.c @@ -189,6 +189,96 @@ int j_cache_put(uint64_t key, const char *head, size_t head_len, return 0; } +/* ---------------------------------------------------------------- Single-Flight + * + * Zwei Agenten, die gleichzeitig dieselbe Frage stellen, kosten heute zweimal Geld. + * Hier wartet der zweite auf den ersten und bedient sich danach aus dem Cache. + * + * Die Tabelle ist klein und absichtlich begrenzt: sie hält nur Schlüssel, keine + * Antworten. Ist sie voll, verhält sich jede Anfrage wie bisher — lieber ein Aufruf + * zu viel als eine Anfrage, die auf einen Platz wartet, den es nicht gibt. */ +#define J_FLIGHT_SLOTS 64 + +static pthread_cond_t g_fl_cond = PTHREAD_COND_INITIALIZER; +static struct { uint64_t key; int waiters; int done; } g_fl[J_FLIGHT_SLOTS]; +static unsigned long g_joined; + +static int fl_find(uint64_t key) +{ + for (int i = 0; i < J_FLIGHT_SLOTS; i++) + if (g_fl[i].key == key) return i; + return -1; +} + +static int fl_free(void) +{ + for (int i = 0; i < J_FLIGHT_SLOTS; i++) + if (g_fl[i].key == 0) return i; + return -1; +} + +int j_cache_flight_begin(uint64_t key) +{ + if (!key) return 1; + LOCK_CACHE(); + int i = fl_find(key); + if (i >= 0) { g_fl[i].waiters++; UNLOCK_CACHE(); return 0; } + i = fl_free(); + if (i < 0) { UNLOCK_CACHE(); return 1; } + g_fl[i].key = key; + g_fl[i].waiters = 0; + g_fl[i].done = 0; + UNLOCK_CACHE(); + return 1; +} + +int j_cache_flight_wait(uint64_t key, double timeout_s) +{ + if (!key) return -1; + struct timespec deadline; + clock_gettime(CLOCK_REALTIME, &deadline); + double add = timeout_s > 0 ? timeout_s : 0; + deadline.tv_sec += (time_t)add; + deadline.tv_nsec += (long)((add - (double)(time_t)add) * 1e9); + if (deadline.tv_nsec >= 1000000000L) { deadline.tv_sec++; deadline.tv_nsec -= 1000000000L; } + + LOCK_CACHE(); + int i = fl_find(key); + if (i < 0) { UNLOCK_CACHE(); return 0; } /* schon fertig */ + int rc = 0; + while (!g_fl[i].done) { + rc = pthread_cond_timedwait(&g_fl_cond, &g_mu, &deadline); + if (rc != 0) break; /* Zeitablauf */ + } + int done = g_fl[i].done; + g_fl[i].waiters--; + if (g_fl[i].waiters <= 0 && g_fl[i].done) g_fl[i].key = 0; + if (done) g_joined++; + UNLOCK_CACHE(); + return (done && rc == 0) ? 0 : -1; +} + +void j_cache_flight_end(uint64_t key) +{ + if (!key) return; + LOCK_CACHE(); + int i = fl_find(key); + if (i >= 0) { + g_fl[i].done = 1; + pthread_cond_broadcast(&g_fl_cond); + if (g_fl[i].waiters <= 0) g_fl[i].key = 0; + } + UNLOCK_CACHE(); +} + +unsigned long j_cache_flight_joined(void) +{ + LOCK_CACHE(); + unsigned long v = g_joined; + UNLOCK_CACHE(); + return v; +} + void j_cache_clear(void) { LOCK_CACHE(); diff --git a/src/cache.h b/src/cache.h index 244d98f..f841bd0 100644 --- a/src/cache.h +++ b/src/cache.h @@ -9,6 +9,17 @@ void j_cache_config(size_t max_entries, size_t max_bytes, double ttl); void j_cache_stats(size_t *entries, size_t *bytes, unsigned long *hits, unsigned long *misses); void j_cache_clear(void); +/* Single-Flight: gleiche Anfragen, die eintreffen, während eine schon unterwegs ist, + * warten auf diese eine, statt ein zweites Mal beim Anbieter zu fragen. + * + * j_cache_flight_begin: 1 = ich frage, 0 = jemand anders fragt schon (warten). + * j_cache_flight_wait: blockiert bis der Führende fertig ist; Rückgabe -1 bei Zeitablauf. + * j_cache_flight_end: weckt die Wartenden und räumt den Eintrag ab. */ +int j_cache_flight_begin(uint64_t key); +int j_cache_flight_wait(uint64_t key, double timeout_s); +void j_cache_flight_end(uint64_t key); +unsigned long j_cache_flight_joined(void); + uint64_t j_cache_key(const char *method, const char *path, const char *model, const char *body, size_t body_len); diff --git a/src/config.c b/src/config.c index b9fb60e..4e1c995 100644 --- a/src/config.c +++ b/src/config.c @@ -83,6 +83,7 @@ void j_config_defaults(j_config *cfg) cfg->cache_bytes = 32L * 1024 * 1024; cfg->ctx_chars_per_token = 0; cfg->cache_deterministic_only = 1; + snprintf(cfg->prices_path, sizeof cfg->prices_path, "/etc/junction/prices.conf"); cfg->compress = J_COMPRESS_OFF; cfg->compress_keep = 4; cfg->compress_min_bytes = 2048; /* Schaetzung aus, bis sie ausdruecklich gesetzt wird */ @@ -163,6 +164,11 @@ static int global_kw(j_config *cfg, char **w, int n, int lineno, char *err, size if (!strcmp(k, "cache_ttl")) { if (n != 2 || as_double(w[1], &cfg->cache_ttl_s)) goto bad; return 0; } if (!strcmp(k, "cache_entries")) { if (n != 2 || as_long(w[1], &cfg->cache_entries)) goto bad; return 0; } if (!strcmp(k, "cache_bytes")) { if (n != 2 || as_long(w[1], &cfg->cache_bytes)) goto bad; return 0; } + if (!strcmp(k, "prices")) { + if (n != 2) goto bad; + snprintf(cfg->prices_path, sizeof cfg->prices_path, "%s", w[1]); + return 0; + } if (!strcmp(k, "cache_deterministic_only")) { if (n != 2) goto bad; if (!strcmp(w[1], "on")) cfg->cache_deterministic_only = 1; diff --git a/src/config.h b/src/config.h index 0dcd573..3ca0211 100644 --- a/src/config.h +++ b/src/config.h @@ -126,6 +126,10 @@ typedef struct { int paused; int inflight; unsigned long ok_count; + /* Verbrauch, den dieser Endpunkt tatsächlich gemeldet hat. */ + unsigned long tokens_in, tokens_out, tokens_cached; + double cost_usd; + unsigned long cost_unknown; unsigned long fail_count; long last_ms; char last_error[256]; @@ -214,6 +218,8 @@ typedef struct { /* Kürzen von Werkzeugausgaben im Anfrageweg. Standard: aus. * Bewusst global und nicht pro Regel: gekürzt wird, bevor der Regelvergleich den * Kontext schätzt — eine Regel kann also nicht darüber entscheiden. */ + char prices_path[512]; /* Preistabelle: was ein Token kostet */ + int cache_deterministic_only; /* nur Anfragen mit Temperatur 0 zwischenspeichern */ int compress; /* J_COMPRESS_OFF | J_COMPRESS_TOOL */ diff --git a/src/junction.c b/src/junction.c index 53aedbc..5954bbd 100644 --- a/src/junction.c +++ b/src/junction.c @@ -10,6 +10,7 @@ #include "cache.h" #include "opencode.h" +#include "price.h" #include "compress.h" #include "config.h" #include "conn.h" @@ -432,8 +433,43 @@ static void send_simple(j_conn *c, int code, const char *reason, const char *bod (void)j_conn_write(c, body, strlen(body), err, sizeof err); } +/* Verbrauch aus einer Antwort lesen: prompt_tokens, completion_tokens und, wenn der + * Anbieter ihn ausweist, die zwischengespeicherte Eingabe. Fehlt der Block, gibt es + * nichts zu zählen — dann wird auch nichts erfunden. */ +static int usage_from_body(const char *body, size_t len, long *in, long *out, long *cached) +{ + if (!body || !len) return 0; + const char *u = strstr(body, "\"usage\""); + if (!u) return 0; + const char *end = body + len; + + const char *p = strstr(u, "\"prompt_tokens\""); + if (!p || p > end) return 0; + p = strchr(p, ':'); + if (!p) return 0; + *in = strtol(p + 1, NULL, 10); + + p = strstr(u, "\"completion_tokens\""); + if (!p || p > end) return 0; + p = strchr(p, ':'); + if (!p) return 0; + *out = strtol(p + 1, NULL, 10); + + *cached = 0; + p = strstr(u, "\"cached_tokens\""); + if (p && p < end) { + p = strchr(p, ':'); + if (p) *cached = strtol(p + 1, NULL, 10); + } + return 1; +} + /* Wie viel das Kürzen insgesamt gespart hat. Ohne diese Zahl wäre die Funktion eine * Behauptung: man sieht nur, dass es passiert, nicht ob es hilft. */ +static unsigned long g_tokens_in, g_tokens_out, g_tokens_cached; +static double g_cost_usd; +static unsigned long g_cost_unknown; + static unsigned long g_compress_reqs; static unsigned long g_compress_bytes_in; static unsigned long g_compress_bytes_out; @@ -484,9 +520,16 @@ static void status_page(j_conn *c) unsigned long hits = 0, misses = 0; j_cache_stats(&entries, &bytes, &hits, &misses); used += (size_t)snprintf(out + used, cap - used, - "],\"cache\":{\"ttl_s\":%.0f,\"entries\":%zu,\"bytes\":%zu,\"hits\":%lu,\"misses\":%lu}," + "],\"usage\":{\"tokens_in\":%lu,\"tokens_out\":%lu,\"tokens_cached\":%lu," + "\"cost_usd\":%.6f,\"cost_unknown\":%lu,\"prices\":%d}," + "\"cache\":{\"ttl_s\":%.0f,\"entries\":%zu,\"bytes\":%zu,\"hits\":%lu,\"misses\":%lu," + "\"joined\":%lu,\"deterministic_only\":%s}," "\"listener\":{\"tls\":%s},", - CFG.cache_ttl_s, entries, bytes, hits, misses, CFG.listen_tls ? "true" : "false"); + g_tokens_in, g_tokens_out, g_tokens_cached, g_cost_usd, g_cost_unknown, + j_price_count(), + CFG.cache_ttl_s, entries, bytes, hits, misses, + j_cache_flight_joined(), CFG.cache_deterministic_only ? "true" : "false", + CFG.listen_tls ? "true" : "false"); pthread_mutex_lock(&SLOTS.mu); int inflight = SLOTS.inflight, waiting = SLOTS.waiting; pthread_mutex_unlock(&SLOTS.mu); @@ -1424,13 +1467,18 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, int store = (CFG.cache_ttl_s > 0) && (ep->cache_on != 0) && (r.status == 200) && !resp_no_store && out_len > 0 && !json_bool_value(out_body, "stream"); + /* Verbrauch lässt sich nur zählen, wenn die Antwort ganz vorliegt. Bei gesetzter + * Preistabelle wird deshalb auch ohne Cache vollständig gelesen — ein nicht + * gestreamter JSON-Rumpf ist ohnehin endlich. */ + int want_usage = (j_price_count() > 0) && !r.chunked && (r.status == 200); + char msbuf[32]; snprintf(msbuf, sizeof msbuf, "%ld", (long)((now_s() - req_started) * 1000.0)); j_hdrs_set(&r.hdrs, "X-Junction-Endpoint", ep->name); j_hdrs_set(&r.hdrs, "X-Junction-Ms", msbuf); j_hdrs_set(&r.hdrs, "X-Junction-Cache", cache_state); - if (store && !head_sent) { + if ((store || want_usage) && !head_sent) { char *body = NULL; size_t body_len = 0; if (read_full_body(&up, &r.buf, r.body_off, r.chunked, r.content_length, @@ -1440,6 +1488,44 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, free(rewritten); return -1; /* nothing sent yet, failover is safe */ } + /* Verbrauch zählen, bevor die Antwort rausgeht: die Zahlen stehen dann in den + * Kopfzeilen und im /status, nicht nur im Log. */ + { + long u_in = 0, u_out = 0, u_cached = 0; + if (!r.chunked && usage_from_body(body, body_len, &u_in, &u_out, &u_cached)) { + const char *billed = (as_model && as_model[0]) ? as_model : rq_model; + double cost = j_price_cost(billed, u_in, u_cached, u_out, ep->offpeak_active); + STATE_LOCK(); + ep->tokens_in += (unsigned long)u_in; + ep->tokens_out += (unsigned long)u_out; + ep->tokens_cached += (unsigned long)u_cached; + if (cost >= 0) ep->cost_usd += cost; + else ep->cost_unknown++; + STATE_UNLOCK(); + g_tokens_in += (unsigned long)u_in; + g_tokens_out += (unsigned long)u_out; + g_tokens_cached += (unsigned long)u_cached; + if (cost >= 0) g_cost_usd += cost; + else g_cost_unknown++; + + char v[64]; + snprintf(v, sizeof v, "%ld", u_in); + j_hdrs_set(&r.hdrs, "X-Junction-Tokens-In", v); + snprintf(v, sizeof v, "%ld", u_out); + j_hdrs_set(&r.hdrs, "X-Junction-Tokens-Out", v); + if (cost >= 0) { + snprintf(v, sizeof v, "%.6f", cost); + j_hdrs_set(&r.hdrs, "X-Junction-Cost-Usd", v); + jlog("usage", "model=%s in=%ld cached=%ld out=%ld cost_usd=%.6f", + billed, u_in, u_cached, u_out, cost); + } else { + j_hdrs_set(&r.hdrs, "X-Junction-Cost-Usd", "unknown"); + jlog("usage", "model=%s in=%ld cached=%ld out=%ld cost_usd=unknown", + billed, u_in, u_cached, u_out); + } + } + } + /* cache the serialized head *with* its final headers, then send the same bytes */ char *headcopy = malloc(HDR_BLOCK_MAX); size_t headused = 0; @@ -1507,6 +1593,8 @@ static int request_is_cacheable(const j_req *rq, char *why, size_t whylen) * das ist keine Ersparnis, das ist eine falsche Antwort. Einbetter sind ausgenommen: * sie liefern für denselben Text immer denselben Vektor. */ if (CFG.cache_deterministic_only) { + /* Eine Modell-Liste enthält keine Zufälligkeit: sie ist entweder da oder nicht. */ + if (strstr(rq->path, "/models")) return 1; if (strstr(rq->path, "embedding")) return 1; double temp = 0; int found = json_num_value(rq->body, "temperature", &temp); @@ -1553,6 +1641,8 @@ static void serve_from_cache(j_conn *client, const char *head, size_t head_len, static void handle_client(j_conn *client) { j_buf buf; + uint64_t ckey = 0; /* oben, weil 'goto done' die Initialisierung überspringt */ + int flight_leader = 0; j_buf_init(&buf); j_req rq; char err[512] = ""; @@ -1677,8 +1767,9 @@ static void handle_client(j_conn *client) if (streaming) head_sent = 1; /* a rewritten body must be cached under the model it is actually sent as */ - uint64_t ckey = 0; - int may_cache = request_is_cacheable(&rq, err, sizeof err); + /* Mit zwei möglichen Rümpfen wäre ein Treffer nicht eindeutig: die Antwort auf den + * gekürzten Text kann sich von der auf den vollen unterscheiden. Also nicht cachen. */ + int may_cache = comp_body ? 0 : request_is_cacheable(&rq, err, sizeof err); if (may_cache) { ckey = j_cache_key(rq.method, rq.path, model, out_body, out_len); const char *head = NULL, *cbody = NULL; @@ -1688,6 +1779,20 @@ static void handle_client(j_conn *client) serve_from_cache(client, head, head_len, cbody, cbody_len, rq.path, model, age); goto done; } + + /* Läuft dieselbe Anfrage schon? Dann warten und ihr Ergebnis mitbenutzen, + * statt ein zweites Mal zu bezahlen. */ + flight_leader = j_cache_flight_begin(ckey); + if (!flight_leader) { + if (j_cache_flight_wait(ckey, 180.0) == 0 && + j_cache_get(ckey, &head, &head_len, &cbody, &cbody_len, &age) == 0) { + jlog("flight_joined", "path=%s model=%s age_s=%.1f", rq.path, model, age); + serve_from_cache(client, head, head_len, cbody, cbody_len, rq.path, model, age); + goto done; + } + /* Der Führende ist gescheitert — dann selbst fragen. */ + flight_leader = j_cache_flight_begin(ckey); + } } if (slot_acquire(client, head_sent, CFG.queue_timeout_s, @@ -1859,6 +1964,7 @@ static void handle_client(j_conn *client) } done: + if (flight_leader && ckey) j_cache_flight_end(ckey); free(comp_body); free(rq.body); j_buf_free(&buf); @@ -1970,6 +2076,18 @@ int main(int argc, char **argv) } j_cache_config((size_t)CFG.cache_entries, (size_t)CFG.cache_bytes, CFG.cache_ttl_s); + /* Preise laden. Fehlt die Datei, läuft alles weiter — nur steht dann bei jeder + * Anfrage cost_usd=unknown statt einer erfundenen Null. */ + { + char perr[256]; + if (j_price_load(CFG.prices_path, perr, sizeof perr)) + fprintf(stderr, "[%s] prices: %s (cost will be reported as unknown)\n", + CFG.log_prefix, perr); + else + fprintf(stderr, "[%s] prices loaded: %d models from %s\n", + CFG.log_prefix, j_price_count(), CFG.prices_path); + } + signal(SIGPIPE, SIG_IGN); j_set_progress(progress_log); diff --git a/src/price.c b/src/price.c new file mode 100644 index 0000000..e062d7d --- /dev/null +++ b/src/price.c @@ -0,0 +1,134 @@ +/* price.c — was eine Anfrage gekostet hat, aus einer Tabelle mit echten Preisen. + * + * Die Tabelle pflegt ein Mensch, weil Preise sich ändern und niemand sie raten darf. + * Ein Modell ohne Eintrag kostet nicht 0 — es kostet unbekannt, und das steht dann auch + * so im Log. Diesen Unterschied zu verwischen wäre der teuerste Fehler, den so ein + * Bericht machen kann. + * + * Format, eine Zeile pro Modell: + * + * # modell in cached out [schlüssel=wert …] + * deepseek-v4.1-flash 0.30 0.006 1.20 offpeak=0.15,0.60 budget=100 requests=43330/5h + * kimi-k3 3.00 0.30 15.00 budget=15 requests=110/5h + * + * Preise in US-Dollar pro Million Token, budget in US-Dollar pro Monat, requests als + * Anzahl pro Fenster (5h, 1h, 1d — h/d/m werden verstanden). + */ +#define _POSIX_C_SOURCE 200809L + +#include "price.h" + +#include +#include +#include +#include + +#define J_MAX_PRICES 256 + +static j_price g_rows[J_MAX_PRICES]; +static int g_count; + +/* "43330/5h" -> Grenze und Fenster in Sekunden. */ +static void parse_requests(const char *v, long *limit, long *window_s) +{ + char *end = NULL; + long n = strtol(v, &end, 10); + if (end == v || n <= 0) return; + *limit = n; + *window_s = 0; + if (*end == '/') { + char *p = end + 1; + long num = strtol(p, &p, 10); + if (num <= 0) num = 1; + if (*p == 'h') *window_s = num * 3600; + else if (*p == 'd') *window_s = num * 86400; + else if (*p == 'm') *window_s = num * 60; + else *window_s = num * 3600; + } +} + +int j_price_load(const char *path, char *err, size_t errlen) +{ + g_count = 0; + if (!path) return 0; + + FILE *f = fopen(path, "r"); + if (!f) { + snprintf(err, errlen, "cannot open price file %s", path); + return -1; + } + + char line[1024]; + while (fgets(line, sizeof line, f)) { + char *hash = strchr(line, '#'); + if (hash) *hash = '\0'; + + char model[J_PRICE_NAME], a[32], b[32], c[32], rest[512]; + rest[0] = '\0'; + int n = sscanf(line, "%63s %31s %31s %31s %[^\n]", model, a, b, c, rest); + if (n < 4) continue; + if (g_count >= J_MAX_PRICES) break; + + j_price *r = &g_rows[g_count]; + memset(r, 0, sizeof *r); + snprintf(r->model, sizeof r->model, "%s", model); + r->in = atof(a); + r->cached = atof(b); + r->out = atof(c); + + /* Schlüssel=Wert-Paare am Zeilenende, durch Leerzeichen getrennt. */ + char *save = NULL; + for (char *tok = strtok_r(rest, " \t", &save); tok; tok = strtok_r(NULL, " \t", &save)) { + char *eq = strchr(tok, '='); + if (!eq) continue; + *eq = '\0'; + const char *k = tok, *v = eq + 1; + if (!strcmp(k, "offpeak")) { + double oi = 0, oo = 0; + if (sscanf(v, "%lf,%lf", &oi, &oo) == 2) { + r->has_offpeak = 1; + r->off_in = oi; + r->off_out = oo; + } + } else if (!strcmp(k, "budget")) { + r->budget_usd = atof(v); + } else if (!strcmp(k, "requests")) { + parse_requests(v, &r->requests_window, &r->window_s); + } + } + g_count++; + } + fclose(f); + return 0; +} + +int j_price_count(void) { return g_count; } + +int j_price_lookup(const char *model, j_price *out) +{ + const j_price *hit = NULL, *star = NULL; + for (int i = 0; i < g_count; i++) { + if (!strcmp(g_rows[i].model, model)) { hit = &g_rows[i]; break; } + if (!strcmp(g_rows[i].model, "*")) star = &g_rows[i]; + } + if (!hit) hit = star; + if (!hit) return -1; + if (out) *out = *hit; + return 0; +} + +double j_price_cost(const char *model, long in_tokens, long cached_tokens, long out_tokens, + int offpeak) +{ + j_price p; + if (j_price_lookup(model, &p) != 0) return -1.0; + + double pi = p.in, po = p.out; + if (offpeak && p.has_offpeak) { pi = p.off_in; po = p.off_out; } + if (cached_tokens > in_tokens) cached_tokens = in_tokens; + + /* Zwischengespeicherte Eingabe ist billiger als frische — wenn der Anbieter sie + * ausweist. Ohne diesen Wert zählt alles als frisch, was nie zu niedrig schätzt. */ + double fresh = (double)(in_tokens - cached_tokens); + return (fresh * pi + (double)cached_tokens * p.cached + (double)out_tokens * po) / 1e6; +} diff --git a/src/price.h b/src/price.h new file mode 100644 index 0000000..83cfafb --- /dev/null +++ b/src/price.h @@ -0,0 +1,32 @@ +#ifndef JUNCTION_PRICE_H +#define JUNCTION_PRICE_H + +#include + +#define J_PRICE_NAME 64 + +/* Eine Zeile der Preistabelle. Preise in US-Dollar pro Million Token; Budgets in + * US-Dollar pro Monat; Anfragegrenzen pro Zeitfenster. */ +typedef struct { + char model[J_PRICE_NAME]; + double in, cached, out; + int has_offpeak; + double off_in, off_out; + double budget_usd; /* 0 = kein bekanntes Monatsbudget */ + long requests_window; /* 0 = keine bekannte Anfragegrenze */ + long window_s; /* Länge des Fensters in Sekunden */ +} j_price; + +/* Lädt die Tabelle. 0 = geladen, -1 = Datei nicht lesbar. */ +int j_price_load(const char *path, char *err, size_t errlen); +int j_price_count(void); + +/* 0 = gefunden (exakter Name vor "*"), -1 = unbekannt. Ein unbekannter Preis ist + * keine Null — der Unterschied entscheidet, ob man dem Bericht glauben darf. */ +int j_price_lookup(const char *model, j_price *out); + +/* Kosten in US-Dollar. -1.0, wenn das Modell keinen Preis hat. */ +double j_price_cost(const char *model, long in_tokens, long cached_tokens, long out_tokens, + int offpeak); + +#endif diff --git a/tests/flight.sh b/tests/flight.sh new file mode 100644 index 0000000..9eb4ee5 --- /dev/null +++ b/tests/flight.sh @@ -0,0 +1,103 @@ +#!/bin/bash +# Wird von tests/run.sh eingebunden: Single-Flight und Modell-Listen im Cache. + +echo "== 23. Single-Flight: gleiche Anfrage, ein Aufruf ==" + +FPORT=$((PORT+61)) +SPORT=$((PORT+62)) + +# Ein Ziel, das absichtlich langsam antwortet — nur so überlappen sich die Anfragen. +cat > "$TMP/slow.py" <<'PY' +import http.server, json, sys, time +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): pass + def do_POST(self): + n = int(self.headers.get("Content-Length", "0")) + self.rfile.read(n) + time.sleep(3) + out = json.dumps({"id": "slow", "choices": [{"index": 0, + "message": {"role": "assistant", "content": "antwort"}}]}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(out))) + self.end_headers() + self.wfile.write(out) +http.server.HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever() +PY +python3 "$TMP/slow.py" "$SPORT" & PIDS+=($!) +sleep 0.6 + +cat > "$TMP/flight.conf" < "$TMP/flight.log" 2>&1 & +PIDS+=($!) +sleep 0.8 + +BODY='{"model":"m","messages":[{"role":"user","content":"teure frage"}],"max_tokens":5,"temperature":0}' +ask() { + curl -s -m 30 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$BODY" \ + "http://127.0.0.1:$FPORT/v1/chat/completions" | tr -d '\r' \ + | sed -n 's/^[Xx]-[Jj]unction-[Cc]ache: //p' +} + +# Drei Anfragen gleichzeitig. Ohne Single-Flight dauern sie 9 s, mit 3 s. +START=$(date +%s) +ask > "$TMP/f1.txt" & A=$! +ask > "$TMP/f2.txt" & B=$! +ask > "$TMP/f3.txt" & C=$! +wait $A $B $C +ELAPSED=$(( $(date +%s) - START )) + +HITS=$(cat "$TMP/f1.txt" "$TMP/f2.txt" "$TMP/f3.txt" | grep -c '^hit$') +MISS=$(cat "$TMP/f1.txt" "$TMP/f2.txt" "$TMP/f3.txt" | grep -c '^miss$') + +if [ "$ELAPSED" -le 5 ]; then + ok "three concurrent identical requests took ${ELAPSED}s, not 3x3s" +else + bad "three concurrent identical requests took ${ELAPSED}s — no sharing happened" +fi +if [ "$MISS" -eq 1 ] && [ "$HITS" -eq 2 ]; then + ok "exactly one request went upstream, two were served from its result" +else + bad "expected 1 miss and 2 hits, got ${MISS} misses and ${HITS} hits" +fi + +# Der Zähler muss das auch sagen. +STATUS=$(curl -s -m 5 "http://127.0.0.1:$FPORT/status") +case "$STATUS" in + *'"joined":2'*) ok "/status counts the two joined requests" ;; + *) bad "/status does not count joined requests" ;; +esac + +# Modell-Listen sind reproduzierbar und werden ohne Temperatur gecacht. +cat > "$TMP/models.conf" < "$TMP/models.log" 2>&1 & +PIDS+=($!) +sleep 0.8 +# POST, weil der Test-Stub nur POST beantwortet; geprüft wird der Pfad, nicht die Methode. +mfetch() { + curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' \ + -d '{"model":"m","messages":[]}' "http://127.0.0.1:$((FPORT+2))/v1/models" \ + | tr -d '\r' | sed -n 's/^[Xx]-[Jj]unction-[Cc]ache: //p' +} +M1=$(mfetch) +M2=$(mfetch) +if [ "$M1" = "miss" ] && [ "$M2" = "hit" ]; then + ok "a model listing is cached without a temperature" +else + bad "model listing cache: first=${M1:-none} second=${M2:-none}" +fi diff --git a/tests/run.sh b/tests/run.sh index ab347c1..576b5a6 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -20,7 +20,7 @@ contains() { case "$1" in *"$2"*) ok "$3";; *) bad "$3 (missing '$2')";; esac; } # A leftover process on a test port produces confusing failures (a stale junction can # answer requests with somebody else's config), so fail loudly and early. -for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8165 8166 8167 8168 8175 8176 8177 8185 8186 9443 9990 9991 9992 9993 9994 9995 9996; do +for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8165 8166 8167 8168 8175 8176 8177 8185 8186 8187 8188 8189 8190 9443 9990 9991 9992 9993 9994 9995 9996; do if ss -tln 2>/dev/null | grep -q ":$port "; then echo "port $port is busy — a leftover junction/stub is still running:" ss -tlnp 2>/dev/null | grep ":$port " | sed 's/^/ /' @@ -640,6 +640,14 @@ contains "$OUT" "bad arguments" "an impossible offpeak window is rejected" # shellcheck source=tests/cache.sh . "$(dirname "$0")/cache.sh" +# Single-Flight: gleiche Anfrage, ein Aufruf. +# shellcheck source=tests/flight.sh +. "$(dirname "$0")/flight.sh" + +# Verbrauch und Kosten pro Anfrage. +# shellcheck source=tests/usage.sh +. "$(dirname "$0")/usage.sh" + echo if [ "$FAILED" -eq 0 ]; then echo "PASS"; else echo "FAILURES"; fi exit "$FAILED" diff --git a/tests/usage.sh b/tests/usage.sh new file mode 100644 index 0000000..46c2350 --- /dev/null +++ b/tests/usage.sh @@ -0,0 +1,99 @@ +#!/bin/bash +# Wird von tests/run.sh eingebunden: Verbrauch und Kosten pro Anfrage. + +echo "== 24. Verbrauch und Kosten pro Anfrage ==" + +UPORT=$((PORT+71)) +USPORT=$((PORT+72)) + +cat > "$TMP/ustub.py" <<'PY' +import http.server, json, sys +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): pass + def do_POST(self): + n = int(self.headers.get("Content-Length", "0")) + self.rfile.read(n) + out = json.dumps({"id": "u", + "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}}], + "usage": {"prompt_tokens": 1200, "completion_tokens": 300, + "prompt_tokens_details": {"cached_tokens": 1000}}}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(out))) + self.end_headers() + self.wfile.write(out) +http.server.HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever() +PY +python3 "$TMP/ustub.py" "$USPORT" & PIDS+=($!) +sleep 0.6 + +cat > "$TMP/prices.conf" <<'CFG' +# test/preis in cached out +test/preis 0.30 0.006 1.20 +CFG + +cat > "$TMP/usage.conf" < "$TMP/usage.log" 2>&1 & +PIDS+=($!) +sleep 0.8 + +hdr() { + curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$1" \ + "http://127.0.0.1:$UPORT/v1/chat/completions" | tr -d '\r' \ + | sed -n "s/^[Xx]-[Jj]unction-${2}: //p" +} + +PRICED='{"model":"test/preis","messages":[{"role":"user","content":"hi"}],"max_tokens":50}' +# Eine Anfrage, alle Kopfzeilen — sonst zählt der Test drei Aufrufe statt einem. +ALL=$(curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$PRICED" \ + "http://127.0.0.1:$UPORT/v1/chat/completions" | tr -d '\r') +IN=$(printf '%s' "$ALL" | sed -n 's/^[Xx]-[Jj]unction-[Tt]okens-[Ii]n: //p') +OUT=$(printf '%s' "$ALL" | sed -n 's/^[Xx]-[Jj]unction-[Tt]okens-[Oo]ut: //p') +COST=$(printf '%s' "$ALL" | sed -n 's/^[Xx]-[Jj]unction-[Cc]ost-[Uu]sd: //p') + +[ "$IN" = "1200" ] && ok "input tokens are reported in the response headers" \ + || bad "input tokens missing (got '${IN:-none}')" +[ "$OUT" = "300" ] && ok "output tokens are reported in the response headers" \ + || bad "output tokens missing (got '${OUT:-none}')" + +# 1000 von 1200 Eingaben waren zwischengespeichert: 200*0.30 + 1000*0.006 + 300*1.20, +# alles durch eine Million. +WANT="0.000426" +[ "$COST" = "$WANT" ] && ok "cost uses the cached-input price where the provider reports it" \ + || bad "cost was '${COST:-none}', expected $WANT" + +UNKNOWN='{"model":"gibt-es-nicht","messages":[{"role":"user","content":"hi"}],"max_tokens":50}' +UCOST=$(hdr "$UNKNOWN" "Cost-Usd") +[ "$UCOST" = "unknown" ] && ok "a model without a price reports unknown, not zero" \ + || bad "unpriced model reported '${UCOST:-none}'" + +STATUS=$(curl -s -m 5 "http://127.0.0.1:$UPORT/status") +case "$STATUS" in + *'"cost_unknown":1'*) ok "/status counts the unpriced request separately" ;; + *) bad "/status does not count unpriced requests" ;; +esac +case "$STATUS" in + *'"tokens_in":2400'*) ok "/status accumulates tokens across requests" ;; + *) bad "/status token totals are wrong" ;; +esac + +# Ohne Preistabelle darf gar nichts gerechnet werden — nur gezählt. +cat > "$TMP/noprice.conf" < "$TMP/noprice.log" 2>&1 & +PIDS+=($!) +sleep 0.8 +NP=$(curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$PRICED" \ + "http://127.0.0.1:$((UPORT+1))/v1/chat/completions" | tr -d '\r' | sed -n 's/^[Xx]-[Jj]unction-[Cc]ost-Usd: //p') +[ -z "$NP" ] && ok "without a price table no cost header is invented" \ + || bad "a cost was reported without any price table ('$NP')"