From 3737571a824e69e8f4872e099b17c0dfb86900ba Mon Sep 17 00:00:00 2001 From: Hermes Date: Wed, 18 Nov 2026 14:13:22 +0000 Subject: [PATCH] prices: Varianten und Abo-Zeilen bepreisen, Cache-Hits kosten 0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ein "#variant"-Suffix ist ein Selektor, kein eigener Modellname. Bisher fand deepseek-v4.1-flash#max deshalb keine Preiszeile und blieb "unknown". j_price_lookup_kind ignoriert den Suffix und nimmt den Basispreis; eine exakte Zeile für den vollen Namen gewinnt weiterhin. Für Endpoints mit kind opencode-go gewinnt eine "-go"-Zeile (Abo: 0 Tokenpreis, Budget/Requests) vor dem Listenpreis. forward_step und die Review-Kosten benutzen den Endpoint-Kind jetzt mit. Ein Cache-Hit baut den Kopf neu auf: X-Junction-Cost-Usd ist 0.000000, Tokens-In/Out sind 0, obwohl der gespeicherte Rumpf noch die Usage des ursprünglichen Calls trägt. Der Ledger war schon korrekt; jetzt stimmen auch die Kopfzeilen dieser Anfrage. Live-Ursache: die Config zeigte auf /etc/junction/prices.conf, die Datei liegt unter /home/lotherk/stack/data/junction/prices.conf. Der Pfad wird beim Deployment korrigiert. Tests in usage.sh: #variant -> Basispreis 0.000426; opencode-go -> -go-Zeile 0.000000; erster Call 0.000426, Cache-Hit 0.000000/0 Tokens; der bisherige noprice-Test band versehentlich auf den Stub-Port und prüfte dadurch nichts — eigener Port und wait_port. Tests: 524 OK, 0 FAIL. --- README.md | 22 ++++++++++++++++ config.example | 6 +++++ src/junction.c | 52 ++++++++++++++++++++++---------------- src/price.c | 55 +++++++++++++++++++++++++++++++++------- src/price.h | 10 +++++++- tests/run.sh | 2 +- tests/usage.sh | 68 ++++++++++++++++++++++++++++++++++++++++++++++---- 7 files changed, 178 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 1ba12bc..1f09847 100644 --- a/README.md +++ b/README.md @@ -364,6 +364,8 @@ request falls back to an unreviewed forward and only the header/log names it. | `X-Junction-Judge-Next-Target` | endpoint or pool that will judge next | | `X-Junction-Judge-Next-Model` | its `as` model, or `pool` when the pool members carry their own | | `X-Junction-Judge-Next-Cache` | `off`, `5m` or `1h` for the next judge | +| `X-Junction-Tokens-In` / `-Out` | the provider's token usage of this call (non-streaming) | +| `X-Junction-Cost-Usd` | exact cost from the price table; `unknown` when a price row is missing, absent without a price table; a cache hit reports `0.000000` and zero tokens | | `X-Junction-Review` | the configured N | | `X-Junction-Review-Rounds` | review rounds that actually completed | | `X-Junction-Review-Model` | the model the worker/review calls were sent as | @@ -547,6 +549,26 @@ jq -r '.cache' spend.jsonl | sort | uniq -c `/spend` reads the same file and sums `cost_usd`, so the dashboard, the monthly budgets and the log can never disagree. +### Price table and per-call cost + +`prices ` loads the table once at startup. A row is +`model input cached output [offpeak=IN,OUT] [budget=USD] [requests=N/5h]`, all +prices per million tokens. The billed name is the target's `as` model; a +`#variant` suffix is a selector, not part of the name, so `deepseek-v4.1-flash#max` +uses the base `deepseek-v4.1-flash` row. An exact row for the full variant still +wins. For an endpoint with `kind opencode-go`, a `-go` row wins over the base +row: it describes the subscription (zero token price, budget/requests) rather than +the pay-as-you-go list price. + +A non-streaming response carries `X-Junction-Tokens-In`, `X-Junction-Tokens-Out` +and, when the price is known, `X-Junction-Cost-Usd`. An unpriced model keeps +`unknown`; without any price table the headers are not invented. A cache hit is a +call that cost nothing: it reports cost `0.000000` and zero tokens even though the +cached body still contains the provider's original usage. The spend log and +`/spend` are authoritative for every call, including streams; a stream cannot get a +late cost header because its head is already on the wire, but a reviewed stream +carries the summed cost in its final `junction` object. + ## Virtual keys, limits, spend A virtual key is a token `junction` minted itself: the client sends it, the real diff --git a/config.example b/config.example index c5cc676..cc8e5c7 100644 --- a/config.example +++ b/config.example @@ -248,5 +248,11 @@ req path "/v1/models" check none pass peer1, peer2, opencode-go # step. A failing judge falls back to the worker without its cache marker; a # first-call provider 4xx reaches the client with its own status and body. +# Optional price table: model input cached output [offpeak=IN,OUT] [budget=USD] +# A "#variant" uses the base model's row; kind opencode-go prefers "-go" +# (subscription: 0 token price) over the list price. Non-streaming responses then +# carry X-Junction-Tokens-In/-Out and X-Junction-Cost-Usd. +# prices /home/lotherk/stack/data/junction/prices.conf + # Anything unseen is refused rather than silently sent to the opencode-go. req for "*" block diff --git a/src/junction.c b/src/junction.c index 04b3e13..4c8e5d3 100644 --- a/src/junction.c +++ b/src/junction.c @@ -3148,7 +3148,8 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, l_out = u_out; l_cached = 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); + double cost = j_price_cost_kind(billed, ep->kind, 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; @@ -3398,7 +3399,7 @@ typedef struct { } review_usage; static void review_usage_add(review_usage *u, const char *body, const char *model, - int offpeak) + const j_endpoint *ep) { if (!body) return; long in = 0, out = 0, cached = 0; @@ -3407,7 +3408,8 @@ static void review_usage_add(review_usage *u, const char *body, const char *mode u->out += out; u->cached += cached; u->seen = 1; - double cost = j_price_cost(model, in, cached, out, offpeak); + double cost = j_price_cost_kind(model, ep->kind, in, cached, out, + ep->offpeak_active); if (cost < 0) u->cost_known = 0; else u->cost += cost; } @@ -3494,7 +3496,7 @@ static int review_serve(j_conn *client, j_endpoint *ep, const j_req *rq, j_buf_free(&cap); return rc; } - review_usage_add(&rev, cap.data, billed, ep->offpeak_active); + review_usage_add(&rev, cap.data, billed, ep); char *answer = NULL; int tools = 0; @@ -3547,7 +3549,7 @@ static int review_serve(j_conn *client, j_endpoint *ep, const j_req *rq, jlog("review", "round=%d endpoint=%s ok=0 error=%s", round, ep->name, err); break; } - review_usage_add(&rev, cap.data, billed, ep->offpeak_active); + review_usage_add(&rev, cap.data, billed, ep); char *next = NULL; int next_tools = 0; const char *next_why = NULL; @@ -3706,23 +3708,31 @@ static void serve_from_cache(j_conn *client, const char *head, size_t head_len, const char *model, double age) { char err[192]; - char *out = malloc(head_len + 64); - if (!out) return; - size_t used = 0; - memcpy(out, head, head_len); - used = head_len; - /* rewrite the cache marker: stored heads say "miss", a hit must say "hit" */ - char *marker = strstr(out, "X-Junction-Cache:"); - if (marker) { - char *eol = strstr(marker, "\r\n"); - if (eol) { - static const char hit[] = "X-Junction-Cache: hit\r\n"; - size_t tail = used - (size_t)(eol + 2 - out); - memmove(marker + sizeof hit - 1, eol + 2, tail); - memcpy(marker, hit, sizeof hit - 1); - used = (size_t)(marker - out) + (sizeof hit - 1) + tail; - } + /* A cache hit costs nothing, even though the stored body still carries the + * provider's usage of the call that filled it. Rebuild the head from its + * headers so the client sees the truth for THIS call: cache=hit, cost 0, + * zero tokens. */ + const char *sep = strstr(head, "\r\n"); + if (!sep || (size_t)(sep + 2 - head) > head_len) { + if (j_conn_write(client, head, head_len, err, sizeof err) >= 0 && body_len) + (void)j_conn_write(client, body, body_len, err, sizeof err); + jlog("cache_hit", "path=%s model=%s age_s=%.0f bytes=%zu", path, model, age, body_len); + return; } + j_hdrs h; + j_hdrs_init(&h); + j_hdrs_parse(&h, sep + 2, head_len - (size_t)(sep + 2 - head)); + j_hdrs_set(&h, "X-Junction-Cache", "hit"); + j_hdrs_set(&h, "X-Junction-Cost-Usd", "0.000000"); + j_hdrs_set(&h, "X-Junction-Tokens-In", "0"); + j_hdrs_set(&h, "X-Junction-Tokens-Out", "0"); + + size_t cap = head_len + 512; + char *out = malloc(cap); + if (!out) return; + int n = snprintf(out, cap, "%.*s\r\n", (int)(sep - head), head); + size_t used = n > 0 ? (size_t)n : 0; + used += j_hdrs_serialize(&h, out + used, cap - used, 1, 1); if (j_conn_write(client, out, used, err, sizeof err) >= 0 && body_len) (void)j_conn_write(client, body, body_len, err, sizeof err); free(out); diff --git a/src/price.c b/src/price.c index e062d7d..50fcf7b 100644 --- a/src/price.c +++ b/src/price.c @@ -104,24 +104,55 @@ int j_price_load(const char *path, char *err, size_t errlen) int j_price_count(void) { return g_count; } -int j_price_lookup(const char *model, j_price *out) +static const j_price *price_exact(const char *model) { - 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]; + for (int i = 0; i < g_count; i++) + if (!strcmp(g_rows[i].model, model)) return &g_rows[i]; + return NULL; +} + +static const j_price *price_star(void) +{ + for (int i = 0; i < g_count; i++) + if (!strcmp(g_rows[i].model, "*")) return &g_rows[i]; + return NULL; +} + +int j_price_lookup_kind(const char *model, const char *kind, j_price *out) +{ + if (!model || !*model) return -1; + + char base[J_PRICE_NAME]; + size_t b = 0; + while (model[b] && model[b] != '#' && b + 1 < sizeof base) { + base[b] = model[b]; + b++; } - if (!hit) hit = star; + base[b] = '\0'; + + const j_price *hit = price_exact(model); + if (!hit && kind && !strcmp(kind, "opencode-go") && base[0]) { + char go[J_PRICE_NAME + 4]; + int n = snprintf(go, sizeof go, "%s-go", base); + if (n > 0 && (size_t)n < sizeof go) hit = price_exact(go); + } + if (!hit && base[0]) hit = price_exact(base); + if (!hit) hit = price_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) +int j_price_lookup(const char *model, j_price *out) +{ + return j_price_lookup_kind(model, NULL, out); +} + +double j_price_cost_kind(const char *model, const char *kind, long in_tokens, + long cached_tokens, long out_tokens, int offpeak) { j_price p; - if (j_price_lookup(model, &p) != 0) return -1.0; + if (j_price_lookup_kind(model, kind, &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; } @@ -132,3 +163,9 @@ double j_price_cost(const char *model, long in_tokens, long cached_tokens, long double fresh = (double)(in_tokens - cached_tokens); return (fresh * pi + (double)cached_tokens * p.cached + (double)out_tokens * po) / 1e6; } + +double j_price_cost(const char *model, long in_tokens, long cached_tokens, long out_tokens, + int offpeak) +{ + return j_price_cost_kind(model, NULL, in_tokens, cached_tokens, out_tokens, offpeak); +} diff --git a/src/price.h b/src/price.h index 83cfafb..ba54d35 100644 --- a/src/price.h +++ b/src/price.h @@ -22,11 +22,19 @@ 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. */ + * keine Null — der Unterschied entscheidet, ob man dem Bericht glauben darf. + * Ein "#variante"-Suffix wird ignoriert: der Basisname ist bepreist. */ int j_price_lookup(const char *model, j_price *out); +/* Wie oben, aber mit Endpoint-Art. Für kind "opencode-go" gewinnt eine + * "-go"-Zeile: sie beschreibt das Abo (0 Tokenpreis, Budget/Requests) + * statt des Listenpreises. Eine exakte Zeile für den vollen Namen gewinnt immer. */ +int j_price_lookup_kind(const char *model, const char *kind, 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); +double j_price_cost_kind(const char *model, const char *kind, long in_tokens, + long cached_tokens, long out_tokens, int offpeak); #endif diff --git a/tests/run.sh b/tests/run.sh index 35e2585..45344f0 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -71,7 +71,7 @@ log_has() { # answer requests with somebody else's config), so fail loudly and early. # 8157 gehört auf dieser Maschine dem Hermes-Gateway — der Port wird von keinem # Test benutzt, also darf er die Suite nicht aufhalten. -for port in 8361 8362 8363 8364 8357 8358 8359 8360 8355 8356 8347 8348 8349 8350 8351 8352 8353 8354 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8395 8396 8397 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8160 8161 8162 8163 8164 8165 8166 8365 8366 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 8208 9443 9990 9991 9992 9993 9994 9995 9996; do +for port in 8361 8362 8363 8364 8357 8358 8359 8360 8355 8356 8347 8348 8349 8350 8351 8352 8353 8354 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8395 8396 8397 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8160 8161 8162 8163 8164 8165 8166 8365 8366 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 8204 8205 8206 8207 8208 8209 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/^/ /' diff --git a/tests/usage.sh b/tests/usage.sh index 46c2350..1b3af41 100644 --- a/tests/usage.sh +++ b/tests/usage.sh @@ -30,6 +30,8 @@ sleep 0.6 cat > "$TMP/prices.conf" <<'CFG' # test/preis in cached out test/preis 0.30 0.006 1.20 +# Subscription row: 0 token price, only a budget/request window. +test/preis-go 0 0 0 budget=10 requests=100/5h CFG cat > "$TMP/usage.conf" < [url] + local url=${3:-"http://127.0.0.1:$UPORT/v1/chat/completions"} 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' \ + "$url" | tr -d '\r' \ | sed -n "s/^[Xx]-[Jj]unction-${2}: //p" } @@ -84,16 +87,71 @@ case "$STATUS" in esac # Ohne Preistabelle darf gar nichts gerechnet werden — nur gezählt. +NOPRICE=$((PORT+69)) cat > "$TMP/noprice.conf" < "$TMP/noprice.log" 2>&1 & PIDS+=($!) -sleep 0.8 +wait_port "$NOPRICE" 30 || bad "the no-price instance did not come up" 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') + "http://127.0.0.1:$NOPRICE/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')" + +# Ein "#variant" ist ein Selektor, kein eigener Modellname: der Basispreis gilt. +VARIANT='{"model":"test/preis#max","messages":[{"role":"user","content":"hi"}],"max_tokens":50}' +VCOST=$(hdr "$VARIANT" "Cost-Usd") +[ "$VCOST" = "0.000426" ] && ok "a #variant uses the base model's price" \ + || bad "variant cost was '${VCOST:-none}', expected 0.000426" + +# Ein opencode-go-Endpoint nutzt die -go-Zeile (Abo: 0 Tokenpreis), nicht den +# Listenpreis der Basiszeile. +GOPORT=$((PORT+70)) +cat > "$TMP/go.conf" < "$TMP/go.log" 2>&1 & +PIDS+=($!) +wait_port "$GOPORT" 30 || bad "the opencode-go cost instance did not come up" +GOCOST=$(hdr "$VARIANT" "Cost-Usd" "http://127.0.0.1:$GOPORT/v1/chat/completions") +[ "$GOCOST" = "0.000000" ] && ok "an opencode-go model uses the -go subscription row" \ + || bad "opencode-go cost was '${GOCOST:-none}', expected 0.000000" + +# Ein Cache-Hit kostet nichts; der gespeicherte Rumpf trägt aber noch die Usage +# des ursprünglichen Calls. Kopfzeilen und Ledger müssen den Hit mit 0 zeigen. +CACHEPORT=$((PORT+74)) +cat > "$TMP/cost-cache.conf" < "$TMP/cost-cache.log" 2>&1 & +PIDS+=($!) +wait_port "$CACHEPORT" 30 || bad "the cost-cache instance did not come up" +CACHED='{"model":"test/preis","messages":[{"role":"user","content":"cache cost"}],"max_tokens":50,"temperature":0}' +C1=$(curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CACHED" \ + "http://127.0.0.1:$CACHEPORT/v1/chat/completions" | tr -d '\r') +C2=$(curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CACHED" \ + "http://127.0.0.1:$CACHEPORT/v1/chat/completions" | tr -d '\r') +C1COST=$(printf '%s' "$C1" | sed -n 's/^[Xx]-[Jj]unction-[Cc]ost-[Uu]sd: //p') +C2COST=$(printf '%s' "$C2" | sed -n 's/^[Xx]-[Jj]unction-[Cc]ost-[Uu]sd: //p') +C2IN=$(printf '%s' "$C2" | sed -n 's/^[Xx]-[Jj]unction-[Tt]okens-[Ii]n: //p') +C2OUT=$(printf '%s' "$C2" | sed -n 's/^[Xx]-[Jj]unction-[Tt]okens-[Oo]ut: //p') +[ "$C1COST" = "0.000426" ] && ok "the first priced call reports its exact cost" \ + || bad "first cached call cost was '${C1COST:-none}'" +[ "$C2COST" = "0.000000" ] && ok "a cache hit reports cost 0, not the original cost" \ + || bad "cache hit cost was '${C2COST:-none}'" +[ "$C2IN" = "0" ] && [ "$C2OUT" = "0" ] && ok "a cache hit reports zero tokens" \ + || bad "cache hit tokens were '${C2IN:-none}'/'${C2OUT:-none}'"