junction: GET /spend — was der Monat gekostet hat, aus dem Spend-Log

Das Spend-Log schreibt seit dem letzten Commit mit, aber niemand konnte es lesen, ohne
selbst JSON-Zeilen zu summieren. /spend beantwortet die Frage, für die es die Datei gibt:

    GET /spend                 → laufender Monat
    GET /spend?month=2026-10   → ein beliebiger Monat, den die Datei noch deckt

Antwort: Gesamtsumme, Anzahl der Anfragen und die Aufteilung je virtuellem Schlüssel und
je Modell — Zahlen aus der Datei, keine Schätzung. Ohne eingetragenes spend_log sagt die
Antwort das (404), statt Nullen zu liefern, die wie ein Monat ohne Verbrauch aussehen.
Ein Monat, in dem die Datei noch gar nicht existiert, ist dagegen ein leerer Monat und
kein Fehler; nur ein echtes Problem (Rechte, Pfad) wird als Fehler gemeldet.

Der Monatsanfang wird arithmetisch aus dem Kalenderdatum gerechnet (days_from_civil),
nicht über timegm() — kein Zeitzonen- oder Sommerzeit-Effekt, und portabel ohne
GNU-Erweiterung.

Dabei ist ein echter Fehler aufgefallen, den nur diese Auskunft sichtbar gemacht hat:
spend_append schrieb now_s() ins Log, und das ist die monotone Uhr für Fristen, nicht die
Wanduhr. Die Zeile lautete "ts":66841 — Sekunden seit Programmstart. Folge: beim nächsten
Start fand das Budget keine Zeile im laufenden Monat und war wieder voll, obwohl der
Monatsverbrauch in der Datei stand. Jetzt steht dort time(NULL). Ein Budget, das jeden
Neustart vergisst, ist keins — und ohne /spend hätte das niemand bemerkt.

Tests (tests/spend-vkey.sh, Abschnitt 28): Summe des Monats, Aufteilung je Schlüssel und
Modell, ein Monat davor (muss leer sein), ein kaputter Monatsparameter (400) und ein
Router ohne Log (nennt den Grund). Der Ledger-Test hatte vorher schon gezeigt, dass die
Kosten pro Anfrage stimmen; jetzt auch, dass sie über den Monat zusammengezählt werden.

make test: PASS, 193 Prüfungen. Live: /spend antwortet auf 127.0.0.1:8090 mit dem
laufenden Monat (noch 0 USD, weil seit dem Einschalten des Logs keine Anfrage mit
Verbrauch durch junction ging).
This commit is contained in:
Hermes committed 2026-11-08 07:52:34 +00:00
1 parent 1e7c26b34c
commit 4cea332fd6
3 files changed
+173 -3

No files matched your search

+15 -2
View File
@@ -270,6 +270,16 @@ spend_log /var/lib/junction/spend.jsonl
"tokens_in":1200,"tokens_out":300,"tokens_cached":1000,"cost_usd":0.000720}
```
`GET /spend` answers for the ledger what `/status` answers for the process: the month's
total and its split per key and per model, `?month=YYYY-MM` for any month the file still
covers. Without a `spend_log` it says so (`404 no spend_log configured`) instead of
returning zeros that look like a month without spending.
Timestamps in the ledger are wall-clock (`time(NULL)`), not the monotonic clock the
timeouts use. That distinction cost a bug: with monotonic seconds the file said
`"ts":66841`, and after the next restart the month's spend was invisible — a budget that
forgets every restart is no budget. `/spend` is what made it visible.
At startup the keys' spent amounts are recomputed from that file for the current month.
Without it a budget would be full again after every restart, which is the one thing a
budget must not be. `/status` also keeps the in-memory numbers, so a request costs one
@@ -428,6 +438,7 @@ others still arrive. Nothing is invented to fill the gap.
|---|---|---|
| GET | `/status` | endpoints, counters, cache stats, rules |
| GET | `/metrics` | the same counters as Prometheus text (unauthenticated, like `/status`) |
| GET | `/spend[?month=YYYY-MM]` | cost of that month from the spend log, per key and per model |
| POST | `/admin/pause/<name>` | stop routing there |
| POST | `/admin/resume/<name>` | clear pause + cooldown + offline |
| POST | `/admin/flush/cache` | drop every cached response |
@@ -478,14 +489,16 @@ a resource URI un-prefixed on `resources/read`, an unknown prefix refused, and a
server not taking the list down. A guard script is tested from both sides: one that
refuses a word it does not want (with its reason in the body and in `/metrics`), one
that exits silently (the exit code becomes the reason), and a request that passes and is
logged as `guard_pass`. The key limits have their own
logged as `guard_pass`. `/spend` is checked against a seeded ledger: the month's total,
the split per key and model, a month with nothing in it, a malformed month, and a router
without a ledger saying exactly that. The key limits have their own
file: a `rpm 1` key is served once and then refused with `429` and a `Retry-After`, a key
whose budget the ledger already used up is refused before it routes anything, and a
priced request through a key shows up in the log file, in `/status` and in `/metrics`.
The offline wait has its own section too: with the only endpoint missing the first
request fails as before, and once the endpoint is back the next request waits out the
offline hold (measured ~2 s) and is served instead of refused.
Pass = `PASS` (186 checks), including two that would have caught the two mistakes this
Pass = `PASS` (193 checks), including two that would have caught the two mistakes this
design invites: a serial stub making a concurrent router look serialised, and a
"waiting" comment leaking into a caller that never asked for a stream.
+141 -1
View File
@@ -566,7 +566,11 @@ static void spend_append(const char *vkey, const char *model, const char *ep,
int n = snprintf(line, sizeof line,
"{\"ts\":%.0f,\"vkey\":\"%s\",\"model\":\"%s\",\"endpoint\":\"%s\","
"\"tokens_in\":%ld,\"tokens_out\":%ld,\"tokens_cached\":%ld,\"cost_usd\":%.6f}\n",
now_s(), ev, em, ep ? ep : "", in, out, cached, cost);
/* Wanduhr, nicht now_s(): das ist monoton und taugt für Fristen, aber nicht
* für "welcher Monat war das". Mit der monotonen Zeit stand im Log "ts":66841,
* und beim nächsten Start war der Monatsverbrauch unsichtbar — ein Budget, das
* jeden Neustart vergisst, ist keins. */
(double)time(NULL), ev, em, ep ? ep : "", in, out, cached, cost);
if (n <= 0 || (size_t)n >= sizeof line) return;
pthread_mutex_lock(&g_spend_mu);
int fd = open(CFG.spend_log, O_WRONLY | O_CREAT | O_APPEND, 0600);
@@ -743,6 +747,141 @@ static char *build_status(size_t *len_out)
return out;
}
/* Tage seit 1970-01-01 für ein Kalenderdatum, ohne timegm(): die Umrechnung ist
* arithmetisch, damit sie nicht von der Zeitzone des Prozesses abhängt. */
static long days_from_civil(long y, unsigned m, unsigned d)
{
y -= (m <= 2);
long era = (y >= 0 ? y : y - 399) / 400;
unsigned yoe = (unsigned)(y - era * 400);
unsigned doy = (153u * (m + (m > 2 ? -3u : 9u)) + 2u) / 5u + d - 1u;
unsigned doe = yoe * 365u + yoe / 4u - yoe / 100u + doy;
return era * 146097L + (long)doe - 719468L;
}
#define SPEND_MAX_KEYS 32
#define SPEND_MAX_MODELS 64
typedef struct {
char name[J_GLOB_MAX];
double cost;
unsigned long n;
} spend_row;
/* GET /spend[?month=YYYY-MM] — was dieser Monat gekostet hat, je Schlüssel und je
* Modell, gelesen aus dem Spend-Log. Die Zahlen sind Buchführung, keine Schätzung:
* jede Zeile im Log ist eine Anfrage, die Verbrauch gemeldet hat. Ist kein Log
* eingetragen, sagt die Antwort das, statt Nullen zu erfinden. */
static void spend_page(j_conn *c, const char *query)
{
long year = 0, mon = 0;
time_t now = time(NULL);
struct tm tmv;
gmtime_r(&now, &tmv);
year = tmv.tm_year + 1900;
mon = tmv.tm_mon + 1;
if (query) {
const char *m = strstr(query, "month=");
if (m) {
int y = 0, mo = 0;
if (sscanf(m + 6, "%4d-%2d", &y, &mo) == 2 && y > 1970 && mo >= 1 && mo <= 12) {
year = y;
mon = mo;
} else {
send_simple(c, 400, "Bad Request", "{\"error\":\"month must be YYYY-MM\"}");
return;
}
}
}
if (!CFG.spend_log[0]) {
send_simple(c, 404, "Not Found", "{\"error\":\"no spend_log configured\"}");
return;
}
double from = (double)days_from_civil(year, (unsigned)mon, 1u) * 86400.0;
long ny = year, nm = mon + 1;
if (nm > 12) { nm = 1; ny++; }
double to = (double)days_from_civil(ny, (unsigned)nm, 1u) * 86400.0;
spend_row keys[SPEND_MAX_KEYS], models[SPEND_MAX_MODELS];
int nkeys = 0, nmodels = 0;
double total = 0.0;
unsigned long lines = 0;
int overflow = 0;
FILE *f = fopen(CFG.spend_log, "r");
/* Existiert die Datei noch nicht, hat niemand etwas verbraucht — das ist ein leerer
* Monat und kein Fehler. Nur ein anderes Problem (Rechte, kaputter Pfad) wird
* gemeldet, statt es als "0 USD" zu verkleiden. */
int missing = (f == NULL && errno == ENOENT);
if (f) {
char line[1024];
while (fgets(line, sizeof line, f)) {
const char *ts = strstr(line, "\"ts\":");
const char *cost = strstr(line, "\"cost_usd\":");
char vk[J_GLOB_MAX] = "", md[J_GLOB_MAX] = "";
if (!ts || !cost) continue;
double t = strtod(ts + 5, NULL);
if (t < from || t >= to) continue;
json_str_value(line, "vkey", vk, sizeof vk);
json_str_value(line, "model", md, sizeof md);
double cost_v = strtod(cost + 11, NULL);
total += cost_v;
lines++;
int found = -1;
for (int i = 0; i < nkeys; i++)
if (!strcmp(keys[i].name, vk)) { found = i; break; }
if (found < 0 && nkeys < SPEND_MAX_KEYS) {
found = nkeys++;
snprintf(keys[found].name, sizeof keys[found].name, "%s", vk);
}
if (found >= 0) { keys[found].cost += cost_v; keys[found].n++; }
else overflow = 1;
found = -1;
for (int i = 0; i < nmodels; i++)
if (!strcmp(models[i].name, md)) { found = i; break; }
if (found < 0 && nmodels < SPEND_MAX_MODELS) {
found = nmodels++;
snprintf(models[found].name, sizeof models[found].name, "%s", md);
}
if (found >= 0) { models[found].cost += cost_v; models[found].n++; }
else overflow = 1;
}
fclose(f);
} else if (!missing) {
send_simple(c, 404, "Not Found", "{\"error\":\"spend_log not readable\"}");
return;
}
size_t cap = 512 + (size_t)(nkeys + nmodels) * 160;
char *out = malloc(cap);
if (!out) { send_simple(c, 500, "Internal Server Error", "{\"error\":\"oom\"}"); return; }
size_t u = (size_t)snprintf(out, cap,
"{\"month\":\"%04ld-%02ld\",\"from\":%.0f,\"to\":%.0f,\"total_usd\":%.6f,"
"\"requests\":%lu,\"truncated\":%s,\"vkeys\":[",
year, mon, from, to, total, lines, overflow ? "true" : "false");
for (int i = 0; i < nkeys; i++) {
char en[J_GLOB_MAX];
json_escape(keys[i].name, en, sizeof en);
u += (size_t)snprintf(out + u, cap - u,
"%s{\"name\":\"%s\",\"cost_usd\":%.6f,\"requests\":%lu}",
i ? "," : "", en, keys[i].cost, keys[i].n);
}
u += (size_t)snprintf(out + u, cap - u, "],\"models\":[");
for (int i = 0; i < nmodels; i++) {
char em[J_GLOB_MAX];
json_escape(models[i].name, em, sizeof em);
u += (size_t)snprintf(out + u, cap - u,
"%s{\"model\":\"%s\",\"cost_usd\":%.6f,\"requests\":%lu}",
i ? "," : "", em, models[i].cost, models[i].n);
}
u += (size_t)snprintf(out + u, cap - u, "]}");
send_simple(c, 200, "OK", out);
free(out);
}
static void status_page(j_conn *c)
{
size_t len = 0;
@@ -2442,6 +2581,7 @@ static void handle_client(j_conn *client)
if (!strcmp(rq.path, "/status")) { status_page(client); goto done; }
if (!strcmp(rq.path, "/metrics")) { metrics_page(client); goto done; }
if (!strncmp(rq.path, "/spend", 6)) { spend_page(client, rq.path); goto done; }
if (!strncmp(rq.path, "/admin/", 7)) { admin(client, rq.path); goto done; }
/* junction ist auch selbst ein MCP-Server: /mcp bündelt die Werkzeuge aller
* eingetragenen Server. Vor der Modellvermittlung, weil hier kein Modell im
+17
View File
@@ -141,3 +141,20 @@ else
bad "/metrics exports the spend per key"
fi
contains "$LM" 'junction_vkey_requests_total{vkey="hermes",outcome="ok"} 1' "/metrics counts the key's requests"
# --- 4. Die Monatsauskunft --------------------------------------------------------------
# Dieselbe Datei, ausgewertet: was hat dieser Monat gekostet, je Schlüssel und Modell.
SP=$(curl -s -m 5 "http://127.0.0.1:$P_LED/spend")
contains "$SP" '"total_usd":0.000720' "/spend sums the month's cost"
contains "$SP" '"name":"hermes","cost_usd":0.000720' "/spend names the key that spent it"
contains "$SP" '"model":"test/preis"' "/spend names the model"
contains "$SP" '"requests":1' "/spend counts the requests"
# Ein Monat davor darf nichts enthalten — sonst zählt das Fenster nicht.
PREV=$(date -d "$(date +%Y-%m-01) -1 month" +%Y-%m 2>/dev/null || date -v-1m +%Y-%m)
SP0=$(curl -s -m 5 "http://127.0.0.1:$P_LED/spend?month=$PREV")
contains "$SP0" '"total_usd":0.000000' "/spend only counts the requested month"
SPBAD=$(curl -s -m 5 "http://127.0.0.1:$P_LED/spend?month=kapputt")
contains "$SPBAD" "month must be YYYY-MM" "a malformed month is refused"
# Ohne eingetragenes Log gibt es keine Zahlen — und keine erfundenen Nullen.
SPNONE=$(curl -s -m 5 "http://127.0.0.1:$P_RPM/spend")
contains "$SPNONE" "no spend_log configured" "/spend without a log says so instead of inventing zero"