Der vkey wurde nur beim Eintreffen der Anfrage gegen sein Monatsbudget geprüft. review_serve machte danach bis zu review_count weitere Provider-Calls, ein hartes Budget konnte so um Faktor 5 überschritten werden. vkey_budget_open liest den Verbrauch unter STATE_LOCK und wird vor jeder Review-Runde geprüft. Ist das Budget erschöpft, endet die Schleife, die letzte gute Antwort (bzw. die Originalantwort) geht an den Client und X-Junction-Review-Skipped nennt "budget". Test in spend-vkey.sh: eigener vkey mit budget 0.0005 und review 2, ein Call kostet 0.00072. Erwartet und geprüft: Originalantwort wird ausgeliefert, Rounds: 0, genau eine Zeile im Spend-Log, Log nennt skipped=budget. Tests: 440 OK, 0 FAIL.
199 lines
9.4 KiB
Bash
199 lines
9.4 KiB
Bash
# Limits je virtuellem Schlüssel und das Spend-Log — sourced von tests/run.sh.
|
|
# Erwartet PORT, TMP, PIDS, contains, log_has, ok, bad aus run.sh.
|
|
|
|
echo "== 28. Limits je Schlüssel und Spend-Log =="
|
|
|
|
# --- 1. Anfragen pro Minute --------------------------------------------------------------
|
|
# Ein Schlüssel mit rpm 1 darf einmal, danach 429 mit Retry-After. Ohne die Pause im
|
|
# Header wiederholt ein Client im gleichen Takt und die Sperre verlängert sich selbst.
|
|
P_RPM=$((PORT+52))
|
|
cat > "$TMP/rpm.conf" <<CFG
|
|
listen 127.0.0.1:$P_RPM
|
|
vkey "limited" token_env VKEY_RPM allow "*" rpm 1
|
|
endpoint gated {
|
|
base http://127.0.0.1:$P_GATED/v1
|
|
context 64000
|
|
timeout 10
|
|
idle_timeout 5
|
|
}
|
|
req for "*" check none pass gated
|
|
CFG
|
|
VKEY_RPM=secret-rpm-secret ./junction --config "$TMP/rpm.conf" > "$TMP/rpm.log" 2>&1 &
|
|
PIDS+=($!)
|
|
wait_port $P_RPM 10
|
|
R1=$(curl -s -m 10 -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' \
|
|
-H 'Authorization: Bearer secret-rpm-secret' \
|
|
-d '{"model":"m","messages":[{"role":"user","content":"hi"}]}' \
|
|
"http://127.0.0.1:$P_RPM/v1/chat/completions")
|
|
[ "$R1" = "200" ] && ok "the first request inside the rpm limit is served" \
|
|
|| bad "the first request inside the rpm limit is served (got $R1)"
|
|
R2=$(curl -s -m 10 -D "$TMP/rpm.h" -X POST -H 'Content-Type: application/json' \
|
|
-H 'Authorization: Bearer secret-rpm-secret' \
|
|
-d '{"model":"m","messages":[{"role":"user","content":"hi"}]}' \
|
|
"http://127.0.0.1:$P_RPM/v1/chat/completions")
|
|
contains "$R2" "vkey_rate_limited" "the second request is refused with the reason"
|
|
tr -d '\r' < "$TMP/rpm.h" | grep -qi '^Retry-After: [1-9]' \
|
|
&& ok "the refusal carries a Retry-After in seconds" \
|
|
|| bad "the refusal carries a Retry-After in seconds"
|
|
log_has "$TMP/rpm.log" "vkey_limited vkey=limited reason=vkey_rate_limited" \
|
|
"the refusal is logged with the key name"
|
|
S2=$(curl -s -m 5 "http://127.0.0.1:$P_RPM/status")
|
|
contains "$S2" '"name":"limited"' "/status lists the key"
|
|
contains "$S2" '"denied":1' "/status counts the refusal"
|
|
|
|
# --- 2. Monatsbudget, gerechnet aus dem Spend-Log ----------------------------------------
|
|
# Ein Budget, das beim Neustart wieder voll ist, ist keins: die Zahl kommt aus der Datei,
|
|
# nicht aus dem Speicher. Hier steht schon Verbrauch in der Datei, also muss der erste
|
|
# Request abgelehnt werden.
|
|
P_BUD=$((PORT+53))
|
|
NOW=$(date +%s)
|
|
cat > "$TMP/spend-seed.jsonl" <<JSONL
|
|
{"ts":$NOW,"vkey":"limited","model":"m","endpoint":"gated","tokens_in":1,"tokens_out":1,"tokens_cached":0,"cost_usd":5.000000}
|
|
JSONL
|
|
cat > "$TMP/bud.conf" <<CFG
|
|
listen 127.0.0.1:$P_BUD
|
|
spend_log $TMP/spend-seed.jsonl
|
|
vkey "limited" token_env VKEY_BUD allow "*" budget 1.0
|
|
endpoint gated {
|
|
base http://127.0.0.1:$P_GATED/v1
|
|
context 64000
|
|
timeout 10
|
|
idle_timeout 5
|
|
}
|
|
req for "*" check none pass gated
|
|
CFG
|
|
VKEY_BUD=secret-bud-secret ./junction --config "$TMP/bud.conf" > "$TMP/bud.log" 2>&1 &
|
|
PIDS+=($!)
|
|
wait_port $P_BUD 10
|
|
B1=$(curl -s -m 10 -X POST -H 'Content-Type: application/json' \
|
|
-H 'Authorization: Bearer secret-bud-secret' \
|
|
-d '{"model":"m","messages":[{"role":"user","content":"hi"}]}' \
|
|
"http://127.0.0.1:$P_BUD/v1/chat/completions")
|
|
contains "$B1" "vkey_budget_exhausted" "a key over its monthly budget is refused"
|
|
SB=$(curl -s -m 5 "http://127.0.0.1:$P_BUD/status")
|
|
contains "$SB" '"spent_usd":5.000000' "the month's spend was read from the ledger at startup"
|
|
|
|
# --- 3. Das Spend-Log schreibt, was eine Anfrage gekostet hat ---------------------------
|
|
# Ein Stub, der Verbrauch meldet, plus Preistabelle: danach steht die Zeile in der Datei,
|
|
# die Zahl in /status und die Summe in /metrics.
|
|
P_USE=$((PORT+54))
|
|
P_LED=$((PORT+55))
|
|
cat > "$TMP/ledstub.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": 0}}}).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/ledstub.py" "$P_USE" & PIDS+=($!)
|
|
cat > "$TMP/ledger-prices.conf" <<'CFG'
|
|
# test/preis in cached out
|
|
test/preis 0.30 0.006 1.20
|
|
CFG
|
|
cat > "$TMP/ledger.conf" <<CFG
|
|
listen 127.0.0.1:$P_LED
|
|
prices $TMP/ledger-prices.conf
|
|
spend_log $TMP/spend.jsonl
|
|
vkey "hermes" token_env VKEY_H allow "*"
|
|
endpoint used {
|
|
base http://127.0.0.1:$P_USE/v1
|
|
context 64000
|
|
timeout 20
|
|
idle_timeout 5
|
|
}
|
|
req for "*" check none pass used
|
|
CFG
|
|
wait_port $P_USE 5
|
|
VKEY_H=secret-h ./junction --config "$TMP/ledger.conf" > "$TMP/ledger.log" 2>&1 &
|
|
PIDS+=($!)
|
|
wait_port $P_LED 10
|
|
L1=$(curl -s -m 10 -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' \
|
|
-H 'Authorization: Bearer secret-h' \
|
|
-d '{"model":"test/preis","messages":[{"role":"user","content":"hi"}],"max_tokens":50}' \
|
|
"http://127.0.0.1:$P_LED/v1/chat/completions")
|
|
[ "$L1" = "200" ] && ok "the priced request through a vkey is served" \
|
|
|| bad "the priced request through a vkey is served (got $L1)"
|
|
LED=$(cat "$TMP/spend.jsonl" 2>/dev/null)
|
|
contains "$LED" '"vkey":"hermes"' "the spend log names the key that caused the cost"
|
|
contains "$LED" '"endpoint":"used"' "the spend log names the endpoint"
|
|
if printf '%s' "$LED" | grep -qE '"cost_usd":0\.0007[0-9]*'; then
|
|
ok "the spend log carries the computed cost"
|
|
else
|
|
bad "the spend log carries the computed cost ($(printf '%s' "$LED" | head -c 160))"
|
|
fi
|
|
SL=$(curl -s -m 5 "http://127.0.0.1:$P_LED/status")
|
|
contains "$SL" '"spent_usd":0.0007' "/status adds the request to the key's spend"
|
|
LM=$(curl -s -m 5 "http://127.0.0.1:$P_LED/metrics")
|
|
if printf '%s' "$LM" | grep -qE '^junction_vkey_spend_usd_total\{vkey="hermes"\} 0\.0007'; then
|
|
ok "/metrics exports the spend per key"
|
|
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"
|
|
|
|
# --- 3b. Review-Runden halten das Monatsbudget ein ------------------------------------
|
|
# Der vkey prüft sein Budget beim Eintreffen der Anfrage. Danach kostet jede
|
|
# Review-Runde einen weiteren Provider-Call; ein hartes Budget darf nicht um
|
|
# bis zu review_count Calls überschritten werden.
|
|
P_RV=$((PORT+73))
|
|
cat > "$TMP/review-budget.conf" <<CFG
|
|
listen 127.0.0.1:$P_RV
|
|
prices $TMP/ledger-prices.conf
|
|
spend_log $TMP/review-budget.jsonl
|
|
vkey "rv" token_env VKEY_RV allow "*" budget 0.0005
|
|
endpoint used {
|
|
base http://127.0.0.1:$P_USE/v1
|
|
context 64000
|
|
timeout 20
|
|
idle_timeout 5
|
|
}
|
|
req for "*" review 2 check none pass used
|
|
CFG
|
|
VKEY_RV=secret-rv ./junction --config "$TMP/review-budget.conf" > "$TMP/review-budget.log" 2>&1 &
|
|
PIDS+=($!)
|
|
wait_port $P_RV 10
|
|
RV=$(curl -s -m 20 -D "$TMP/review-budget.h" -X POST -H 'Content-Type: application/json' \
|
|
-H 'Authorization: Bearer secret-rv' \
|
|
-d '{"model":"test/preis","messages":[{"role":"user","content":"hi"}],"max_tokens":50}' \
|
|
"http://127.0.0.1:$P_RV/v1/chat/completions")
|
|
contains "$RV" '"ok"' "the original answer is delivered when the review budget is spent"
|
|
tr -d '\r' < "$TMP/review-budget.h" | grep -qi '^X-Junction-Review-Skipped: budget' \
|
|
&& ok "the skipped review names the budget in its header" \
|
|
|| bad "the skipped review names the budget in its header"
|
|
tr -d '\r' < "$TMP/review-budget.h" | grep -qi '^X-Junction-Review-Rounds: 0' \
|
|
&& ok "no review round ran after the budget was spent" \
|
|
|| bad "no review round ran after the budget was spent"
|
|
[ "$(wc -l < "$TMP/review-budget.jsonl")" = "1" ] \
|
|
&& ok "the budget stopped the run after the one paid request" \
|
|
|| bad "the budget stopped the run after the one paid request ($(wc -l < "$TMP/review-budget.jsonl") calls)"
|
|
log_has "$TMP/review-budget.log" "review round=1 endpoint=used skipped=budget" \
|
|
"the skipped review round is logged with its reason"
|
|
|
|
# --- 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"
|