Eine Zeile je bedienter Anfrage — Verbrauch und Fehlersuche in derselben Datei

Das Spend-Log war eine Buchführung über Kosten; jetzt ist es das Anfrage-Log. Neu in
jeder Zeile: status, latency_ms, upstream_ms, queue_ms, rule_line, cache (off/miss/hit/
peer/joined), retries. Die Zeilenmenge bleibt dieselbe — eine pro bedienter Anfrage —,
aber sie steht vorher auch für Anfragen ohne Nutzungszahlen und für Cache-Treffer, die
vorher gar keine Zeile hatten. Ein Strom bekommt eine Zeile mit Nullen statt einer
Schätzung; gescheiterte Versuche bleiben in journald und in /metrics.

Damit braucht es keinen Exporter: jq oder duckdb lesen die Datei, /spend summiert
dieselben Zeilen, und die Monatsbudgets hängen weiter an cost_usd.

Dabei ein echter Fehler gefunden, den erst die Suite zeigte: junction brach mitten im
Single-Flight-Abschnitt mit SIGABRT ab. Ursache war mein erster Entwurf — der Status
wurde aus dem gespeicherten Kopf gelesen, nachdem die Antwort schon draußen war. Der
Zeiger aus j_cache_get gilt aber nur bis zum nächsten put, und ein zweiter Faden, der
denselben Eintrag füllt, gibt ihn frei: use-after-free. Der Code wird jetzt gelesen,
solange der Zeiger noch gilt, an allen drei Stellen (lokaler Treffer, Peer-Treffer,
mitbenutzter Flug). Belegt mit AddressSanitizer: die ganze Suite läuft grün durch,
null Berichte.

Tests: Abschnitt 35 (10 Prüfungen) — zwei Anfragen, zwei Zeilen; Status, Cache-Quelle,
Regelzeile (aus der Konfiguration gelesen, nicht geraten), Tokens, Kosten; eine
Cache-Antwort mit Nullen; /spend gleich der Summe der Zeilen.
make test: PASS, 220 Prüfungen, 154 s.
This commit is contained in:
Hermes committed 2026-11-08 09:42:12 +00:00
1 parent c8b4e51a16
commit 114d1acad0
6 files changed
+277 -12

No files matched your search

+50 -1
View File
@@ -237,6 +237,48 @@ That listener answers `GET /metrics` and nothing else — `/v1` and `/admin` sta
`listen`, so a monitoring container can read the numbers without also being able to
pause endpoints or rewrite the configuration.
## The request log — one line per served request
`spend_log` is not only a ledger. Every request junction answers leaves one JSON line,
and that line is the only place where a single request is complete: Prometheus cannot
hold the dimension (model × endpoint × rule × cache source) and journald spreads the same
request over five event lines.
```json
{"ts":1794123456,"vkey":"hermes","model":"deepseek-v4.1-flash","endpoint":"cloud",
"status":200,"latency_ms":1840,"upstream_ms":1839,"queue_ms":0,"rule_line":120,
"cache":"miss","retries":0,"tokens_in":1200,"tokens_out":300,"tokens_cached":0,
"cost_usd":0.000720}
```
| field | meaning |
|---|---|
| `status` | what the client got — the endpoint's status, not ours |
| `latency_ms` | the whole request as the client waited for it |
| `upstream_ms` | that time minus the queue wait; derived, not measured separately |
| `queue_ms` | how long the request waited for an `max_inflight` slot |
| `rule_line` | the line of the rule that matched; `0` when no rule ran (cache hit) |
| `cache` | `off` (not cacheable), `miss` (paid), `hit` (own cache), `peer` (another instance), `joined` (waited for an identical request in flight) |
| `retries` | additional attempts of this same request, not the process total |
| `tokens_*`, `cost_usd` | the provider's numbers; a cache hit has zeros, not estimates |
A streamed answer cannot be billed after the fact, but it still gets a line — with
zeros rather than a guess. Failed requests are counted in `/metrics` and logged per
attempt in journald; the request log is for what was served, not for every try.
No exporter, no collector, no agent — the file is the interface:
```bash
# p95 latency per model over the last day
jq -r 'select(.ts > (now-86400)) | [.model, .latency_ms] | @tsv' spend.jsonl |
sort -k1,1 | awk '{a[$1]=a[$1]" "$2} END {for (m in a) print m, a[m]}'
# what the cache actually saved
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.
## Virtual keys, limits, spend
A virtual key is a token `junction` minted itself: the client sends it, the real
@@ -575,7 +617,14 @@ The rolling update is tested for real: a second instance binds the same port whi
first serves, `SIGTERM` on the first logs `draining` and `drained` and it exits, the
second serves during and after the handover, and without `so_reuseport` the port stays
exclusive.
Pass = `PASS` (210 checks), including two that would have caught the two mistakes this
The request log has its own section: two served requests write exactly two lines, the
paid one carries the provider's tokens, the status, a positive latency and the matching
rule line, the cached one says `cache":"hit"` with zero tokens and no rule, and `/spend`
sums exactly what the ledger wrote. A third check would have caught a real
use-after-free: the status code must be read out of the cached head *before* the body is
sent, because another thread may replace that entry while this one is still writing —
the whole suite also runs green under AddressSanitizer.
Pass = `PASS` (220 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.
+2
View File
@@ -29,6 +29,8 @@ retry_backoff 0.5
# One JSON line per request that reported usage: time, key, model, endpoint, tokens,
# cost. The per-key monthly budgets are recomputed from it at startup — without it a
# budget would be full again after every restart. Empty = no log.
# One JSON line per served request: cost for the budgets, plus status, latency,
# queue wait, rule line, cache source and retries for looking things up later.
# spend_log /var/lib/junction/spend.jsonl
# A guard sees every request before it is routed and decides: exit 0 = pass, anything
+10 -2
View File
@@ -174,8 +174,16 @@ vkey "webui" token_env VKEY_WEBUI allow "deepseek-*" rpm 60 budget 10
vkey "navigator" token_env VKEY_NAVIGATOR allow "*" endpoints "ollama1,ollama2" rpm 30 budget 5
vkey "hermes" token_env VKEY_HERMES allow "*"
# Bookkeeping: one JSON line per request that reported usage. Without this file
# there is no monthly figure and no budget that survives a restart.
# One JSON line per served request — the ledger and the request log in the same file.
# Without it there is no monthly figure, no budget that survives a restart, and no way
# to answer "why was that request slow" without grepping five journald lines.
#
# ts, vkey, model, endpoint, status, latency_ms, upstream_ms, queue_ms, rule_line,
# cache (off|miss|hit|peer|joined), retries, tokens_in/out/cached, cost_usd
#
# A cache hit writes zeros for tokens and cost, not estimates; a streamed answer writes a
# line as well (zeros are honest, a guess is not). Failed attempts are not in here —
# they are in journald and in /metrics.
spend_log /var/lib/junction/spend.jsonl
+95 -8
View File
@@ -59,6 +59,13 @@ static pthread_rwlock_t g_rules_rw = PTHREAD_RWLOCK_INITIALIZER;
/* Which connection, if any, wants a heartbeat from THIS thread right now. A thread
* handles one request, so this is per-request state, not global. */
/* Angaben, die den Anfragepfad nie verlassen, aber in die Logzeile gehören:
* Wartezeit in der Schlange, Zahl der Wiederholungen, Trefferregel. Thread-lokal, weil
* jeder Request in einem eigenen Faden läuft — kein Sperren, keine Reihenfolge. */
static __thread long t_queue_ms;
static __thread int t_req_retries;
static __thread int t_rule_line;
static __thread j_conn *t_heartbeat;
static __thread double t_heartbeat_started;
@@ -578,21 +585,43 @@ static double month_start_ts(void)
tmv.tm_min * 60 + tmv.tm_sec));
}
static void spend_append(const char *vkey, const char *model, const char *ep,
long in, long out, long cached, double cost)
/* Der Anteil, der beim Anbieter lag: die ganze Anfrage abzüglich der Wartezeit in der
* Schlange. Nicht gemessen, sondern hergeleitet — deshalb steht das im Kommentar und
* nicht nur im Log. */
static double upstream_part(double latency_ms)
{
return latency_ms > (double)t_queue_ms ? latency_ms - (double)t_queue_ms : 0.0;
}
/* Eine Zeile je bedienter Anfrage: Verbrauch für die Budgets, alles andere für die
* Fehlersuche. Dieselbe Datei für beides — zwei Protokolle über denselben Vorgang wären
* zwei Wahrheiten, und die eine wäre immer die ältere.
*
* `cache` sagt, woher die Antwort kam (off/miss/hit/joined/peer), `latency_ms` ist die
* ganze Anfrage aus Sicht des Clients, `upstream_ms` der Anteil beim Anbieter,
* `queue_ms` die Wartezeit auf einen Platz. Eine Zeile pro Anfrage ist dieselbe Menge
* wie vorher — die Felder sind neu, nicht die Zeilen. */
static void reqlog_append(const char *vkey, const char *model, const char *ep, int status,
double latency_ms, double upstream_ms, long queue_ms,
int rule_line, const char *cache, int retries,
long in, long out, long cached, double cost)
{
if (!CFG.spend_log[0]) return;
char line[1024], em[J_GLOB_MAX], ev[J_NAME_MAX];
char line[1280], em[J_GLOB_MAX], ev[J_NAME_MAX], ee[J_NAME_MAX];
json_escape(model ? model : "", em, sizeof em);
json_escape(vkey ? vkey : "", ev, sizeof ev);
json_escape(ep ? ep : "", ee, sizeof ee);
int n = snprintf(line, sizeof line,
"{\"ts\":%.0f,\"vkey\":\"%s\",\"model\":\"%s\",\"endpoint\":\"%s\","
"\"status\":%d,\"latency_ms\":%.0f,\"upstream_ms\":%.0f,\"queue_ms\":%ld,"
"\"rule_line\":%d,\"cache\":\"%s\",\"retries\":%d,"
"\"tokens_in\":%ld,\"tokens_out\":%ld,\"tokens_cached\":%ld,\"cost_usd\":%.6f}\n",
/* 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);
(double)time(NULL), ev, em, ee, status, latency_ms, upstream_ms, queue_ms,
rule_line, cache && cache[0] ? cache : "off", retries, 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);
@@ -2415,6 +2444,12 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
j_hdrs_set(&r.hdrs, "X-Junction-Ms", msbuf);
j_hdrs_set(&r.hdrs, "X-Junction-Cache", cache_state);
/* Verbrauch und Kosten über den Block hinaus, damit die Logzeile auch dann
* geschrieben wird, wenn die Antwort keine Nutzungszahlen trägt: eine Anfrage, die
* beantwortet wurde, gehört ins Log — mit Nullen, nicht gar nicht. */
long l_in = 0, l_out = 0, l_cached = 0;
double l_cost = -1.0;
if ((store || want_usage) && !head_sent) {
char *body = NULL;
size_t body_len = 0;
@@ -2430,6 +2465,9 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
{
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)) {
l_in = u_in;
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);
STATE_LOCK();
@@ -2456,8 +2494,7 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
}
STATE_UNLOCK();
}
spend_append(vkey_name, billed, ep->name, u_in, u_out, u_cached,
cost >= 0 ? cost : 0.0);
l_cost = cost;
char v[64];
snprintf(v, sizeof v, "%ld", u_in);
@@ -2493,6 +2530,11 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
j_mesh_store(fill_key, headcopy, headused, body, body_len, CFG.cache_ttl_s);
free(headcopy);
}
double now_ms = (now_s() - req_started) * 1000.0;
reqlog_append(vkey_name, (as_model && as_model[0]) ? as_model : rq_model,
ep->name, r.status, now_ms, upstream_part(now_ms), t_queue_ms,
t_rule_line, cache_state, t_req_retries, l_in, l_out, l_cached,
l_cost >= 0 ? l_cost : 0.0);
int rc = send_head(client, r.status, r.reason, &r.hdrs, (long)body_len, err, errlen);
if (rc == 0 && body_len && j_conn_write(client, body, body_len, err, errlen) < 0)
rc = -1;
@@ -2518,6 +2560,15 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
? relay_dechunk(client, &up, r.buf.data + pre_off, pre_len, ep->idle_timeout_s, deadline)
: relay_stream(client, &up, r.buf.data + pre_off, pre_len, r.content_length,
ep->idle_timeout_s, deadline);
{
/* Ein Strom lässt sich nicht nachträglich abrechnen; die Zeile sagt trotzdem,
* dass die Anfrage bedient wurde — mit Nullen statt mit Schätzungen. */
double now_ms = (now_s() - req_started) * 1000.0;
reqlog_append(vkey_name, (as_model && as_model[0]) ? as_model : rq_model,
ep->name, r.status, now_ms, upstream_part(now_ms), t_queue_ms,
t_rule_line, cache_state, t_req_retries, l_in, l_out, l_cached,
l_cost >= 0 ? l_cost : 0.0);
}
t_heartbeat = NULL;
resp_free(&r);
j_conn_close(&up);
@@ -2568,6 +2619,7 @@ static int forward_with_retry(j_conn *client, j_endpoint *ep, const j_req *rq,
nanosleep(&ts, NULL);
}
g_retries++;
t_req_retries++;
}
rc = forward_step(client, ep, rq, body, len, as_model, rq_model, cache_state,
started, head_sent, vkey_name, err, errlen);
@@ -2612,6 +2664,19 @@ static int request_is_cacheable(const j_req *rq, char *why, size_t whylen)
return 1;
}
/* Der gespeicherte Kopf beginnt mit "HTTP/1.1 <code> …". Für die Logzeile braucht es
* den Code, und Raten wäre eine Behauptung. */
static int status_from_head(const char *head, size_t head_len)
{
if (!head || head_len < 13) return 200;
const char *sp = memchr(head, ' ', head_len);
if (!sp) return 200;
int code = 0;
for (const char *p = sp + 1; p < head + head_len && *p >= '0' && *p <= '9'; p++)
code = code * 10 + (*p - '0');
return code > 0 ? code : 200;
}
static void serve_from_cache(j_conn *client, const char *head, size_t head_len,
const char *body, size_t body_len, const char *path,
const char *model, double age)
@@ -2819,6 +2884,9 @@ static void handle_client(j_conn *client)
const char *out_body = rq.body;
size_t out_len = out_body ? strlen(out_body) : 0;
double started = now_s();
t_queue_ms = 0;
t_req_retries = 0;
t_rule_line = 0;
/* Does the caller want a stream? Then it gets a stream immediately — with nothing
* but comments in it until there is a real answer. Everything else waits silently
@@ -2845,7 +2913,14 @@ static void handle_client(j_conn *client)
size_t head_len = 0, cbody_len = 0;
double age = 0;
if (j_cache_get(ckey, &head, &head_len, &cbody, &cbody_len, &age) == 0) {
/* Der Code muss gelesen werden, solange der Zeiger gilt: ein anderer Faden
* kann den Eintrag während des Sendens ersetzen, und dann zeigt `head` auf
* freigegebenen Speicher. */
int cstatus = status_from_head(head, head_len);
serve_from_cache(client, head, head_len, cbody, cbody_len, rq.path, model, age);
reqlog_append(vk ? vk->name : "", model, "", cstatus,
(now_s() - started) * 1000.0, 0, t_queue_ms, t_rule_line,
"hit", t_req_retries, 0, 0, 0, 0.0);
goto done;
}
/* Lokal nichts — aber vielleicht hat ein anderer Knoten dieselbe Frage schon
@@ -2856,8 +2931,12 @@ static void handle_client(j_conn *client)
size_t mhl = 0, mbl = 0;
double mage = 0;
if (j_mesh_lookup(ckey, &mhead, &mhl, &mbody, &mbl, &mage) == 0) {
int pstatus = status_from_head(mhead, mhl);
jlog("cache_hit", "path=%s model=%s age_s=%.0f via=peer", rq.path, model, mage);
serve_from_cache(client, mhead, mhl, mbody, mbl, rq.path, model, mage);
reqlog_append(vk ? vk->name : "", model, "", pstatus,
(now_s() - started) * 1000.0, 0, t_queue_ms, t_rule_line,
"peer", t_req_retries, 0, 0, 0, 0.0);
free(mhead);
free(mbody);
goto done;
@@ -2870,8 +2949,12 @@ static void handle_client(j_conn *client)
if (!flight_leader) {
if (j_cache_flight_wait(ckey, 180.0) == 0 &&
j_cache_get(ckey, &head, &head_len, &cbody, &cbody_len, &age) == 0) {
int jstatus = status_from_head(head, head_len);
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);
reqlog_append(vk ? vk->name : "", model, "", jstatus,
(now_s() - started) * 1000.0, 0, t_queue_ms, t_rule_line,
"joined", t_req_retries, 0, 0, 0, 0.0);
goto done;
}
/* Der Führende ist gescheitert — dann selbst fragen. */
@@ -2915,8 +2998,11 @@ static void handle_client(j_conn *client)
}
}
if (slot_acquire(client, head_sent, CFG.queue_timeout_s,
streaming ? "stream" : "request") != 0) {
double queue_started = now_s();
int slot_rc = slot_acquire(client, head_sent, CFG.queue_timeout_s,
streaming ? "stream" : "request");
t_queue_ms = (long)((now_s() - queue_started) * 1000.0);
if (slot_rc != 0) {
if (!head_sent) {
char body[512];
snprintf(body, sizeof body,
@@ -3044,6 +3130,7 @@ static void handle_client(j_conn *client)
g_compress_bytes_in += cstat.bytes_in;
g_compress_bytes_out += cstat.bytes_out;
}
t_rule_line = rule->line;
int rc = forward_with_retry(client, ep, &rq, send_body, send_len, rule->target_as[t], model,
may_cache ? "miss" : "off", started, head_sent,
vk ? vk->name : "", err, sizeof err);
+115
View File
@@ -0,0 +1,115 @@
#!/bin/bash
# Wird von tests/run.sh eingebunden: eine Zeile je bedienter Anfrage.
#
# Das Request-Log ist die einzige Stelle, an der eine einzelne Anfrage vollständig
# steht: Status, Dauer, Wartezeit, Regel, Cache-Quelle, Wiederholungen, Tokens, Kosten.
# Prometheus kann das nicht (zu viele Dimensionen), journald nur über mehrere Zeilen.
echo
echo "== 35. Anfrage-Log: eine Zeile, alle Felder =="
LPORT=$((PORT+210))
LSTUB=$((PORT+211))
LLED="$TMP/reqlog.jsonl"
cat > "$TMP/lstub.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": "l",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}}],
"usage": {"prompt_tokens": 900, "completion_tokens": 120,
"prompt_tokens_details": {"cached_tokens": 400}}}).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/lstub.py" "$LSTUB" & PIDS+=($!)
sleep 0.6
cat > "$TMP/lprices.conf" <<'CFG'
# test/log in cached out
test/log 0.30 0.006 1.20
CFG
cat > "$TMP/reqlog.conf" <<CFG
listen 127.0.0.1:$LPORT
prices $TMP/lprices.conf
cache_ttl 300
cache_entries 20
cache_bytes 2000000
spend_log $LLED
endpoint a { base http://127.0.0.1:$LSTUB/v1; timeout 20 }
req for "*" pass a
CFG
./junction --config "$TMP/reqlog.conf" > "$TMP/reqlog.log" 2>&1 &
PIDS+=($!)
wait_port "$LPORT" 10 || bad "the request-log instance did not come up"
LBODY='{"model":"test/log","messages":[{"role":"user","content":"eine frage"}],"max_tokens":5,"temperature":0}'
lask() {
curl -s -m 10 -o /dev/null -X POST -H 'Content-Type: application/json' -d "$LBODY" \
"http://127.0.0.1:$LPORT/v1/chat/completions"
}
lask # miss: bezahlt beim Anbieter
lask # hit: aus dem eigenen Cache
logfield() { # logfield <zeilennummer> <feld>
python3 - "$LLED" "$1" "$2" <<'PY'
import json, sys
lines = [l for l in open(sys.argv[1]) if l.strip()]
idx = int(sys.argv[2])
print(json.loads(lines[idx]).get(sys.argv[3], ""))
PY
}
nlines=$(python3 -c "print(sum(1 for l in open('$LLED') if l.strip()))")
[ "$nlines" = "2" ] && ok "two served requests, two lines — no line per event, one per request" \
|| bad "expected 2 log lines, found $nlines"
[ "$(logfield 0 status)" = "200" ] && ok "the line carries the status" \
|| bad "status missing: $(logfield 0 status)"
[ "$(logfield 0 cache)" = "miss" ] && ok "the paid request says cache=miss" \
|| bad "first line is not a miss: $(logfield 0 cache)"
[ "$(logfield 1 cache)" = "hit" ] && ok "the cached request says cache=hit" \
|| bad "second line is not a hit: $(logfield 1 cache)"
[ "$(logfield 1 tokens_in)" = "0" ] && ok "a cache hit costs no tokens" \
|| bad "cache hit reported $(logfield 1 tokens_in) input tokens"
[ "$(logfield 0 tokens_in)" = "900" ] && ok "the paid request carries the provider's token numbers" \
|| bad "tokens missing: $(logfield 0 tokens_in)"
# Die Regelzeile wird nicht geraten: sie muss die Zeile der passenden Regel sein.
rule_at=$(grep -n '^req for "\*"' "$TMP/reqlog.conf" | cut -d: -f1)
[ "$(logfield 0 rule_line)" = "$rule_at" ] \
&& ok "the line names the rule that matched (line $rule_at)" \
|| bad "rule_line was $(logfield 0 rule_line), the rule sits on line $rule_at"
[ "$(logfield 1 rule_line)" = "0" ] && ok "a cache hit names no rule — none was used" \
|| bad "cache hit claims rule_line $(logfield 1 rule_line)"
# latency_ms muss eine Zahl sein und zur Antwort passen; queue_ms ist bei freien Plätzen 0.
python3 - "$LLED" <<'PY'
import json, sys
lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
d = lines[0]
ok = (isinstance(d.get("latency_ms"), (int, float)) and d["latency_ms"] >= 0
and d.get("upstream_ms", -1) >= 0 and d.get("queue_ms") == 0
and d.get("retries") == 0 and d.get("cost_usd", 0) > 0)
sys.exit(0 if ok else 1)
PY
[ $? -eq 0 ] && ok "latency_ms, upstream_ms, queue_ms, retries and cost all present and plausible" \
|| bad "a timing or cost field is missing or implausible"
# Die Kosten aus dem Log sind dieselben, die /spend summiert.
total=$(curl -s -m 5 "http://127.0.0.1:$LPORT/spend" | python3 -c "import sys,json;print('%.6f'%json.load(sys.stdin)['total_usd'])")
logged=$(python3 - "$LLED" <<'PY'
import json, sys
print("%.6f" % sum(json.loads(l).get("cost_usd", 0) for l in open(sys.argv[1]) if l.strip()))
PY
)
[ "$total" = "$logged" ] && ok "/spend sums the same numbers the ledger writes ($total)" \
|| bad "/spend says $total, the ledger says $logged"
+5 -1
View File
@@ -46,7 +46,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 8335 8336 8337 8338 8339 8340 8341 8342 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8165 8166 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 9443 9990 9991 9992 9993 9994 9995 9996; do
for port in 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8165 8166 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 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/^/ /'
@@ -703,6 +703,10 @@ contains "$OUT" "bad arguments" "an impossible offpeak window is rejected"
# shellcheck source=tests/cluster.sh
. "$(dirname "$0")/cluster.sh"
# Eine Zeile je bedienter Anfrage (Status, Dauer, Regel, Cache-Quelle).
# shellcheck source=tests/reqlog.sh
. "$(dirname "$0")/reqlog.sh"
# junction als MCP-Server: Werkzeuge der angebundenen Server bündeln und
# Aufrufe an den richtigen Server weiterreichen. Eigenes Programm, weil zwei
# erfundene MCP-Server gebraucht werden.