Files
junction/tests/run.sh
T
junction 10103e77ca mcp: Antwort muss die id der Anfrage tragen (Umschlag, nicht Argument)
Der Fehler, der im Betrieb als 'task_get haengt' ankam: steht in der Anfrage
'id' hinter 'params', und heisst das Werkzeug-Argument selbst 'id' (task_get,
task_done, page_read ...), fand die rekursive Suche das Argument zuerst.
junction antwortete mit {"id":"t0025"} statt der Anfrage-id. Der Client
wartete auf seine eigene id, bekam sie nie und hing — im Client-Log nur
'Received a response for an unknown message ID'.

Neu: json_top() liest den Umschlag nur auf der obersten Ebene. Werkzeug-
Argumente koennen heissen wie sie wollen.

Belegt: opencode-Lauf mit erzwungenem tasksd__task_get vorher haengend,
jetzt Titel in 3,4 s. Neuer Test tests/mcp_envelope.py (5 Faelle, in
make test) prueft, dass die Antwort immer die Anfrage-id traegt.
2026-11-12 10:59:21 +00:00

785 lines
29 KiB
Bash
Executable File

#!/bin/bash
# junction test suite — stub endpoints only, no network, no models. ~150 s.
set -uo pipefail
cd "$(dirname "$0")/.."
# Hermetisch: dieser Lauf darf nicht davon abhängen, welche Schlüssel zufällig in der
# Umgebung stehen. Sonst legt junction Endpunkte an, die kein Test erwartet.
unset OPENCODE_GO_API_KEY OLLAMA_KEY ANTHROPIC_API_KEY CLAUDE_API_KEY 2>/dev/null || true
for n in 1 2 3 4 5 6 7 8; do
unset "OPENCODE_GO_API_KEY$n" "OLLAMA_KEY$n" "ANTHROPIC_API_KEY$n" "CLAUDE_API_KEY$n" 2>/dev/null || true
done
TMP=$(mktemp -d)
PORT=8135
P_FAIL=9990; P_GATED=9991; P_DEAD=9992; P_SLOW=9993; P_PONDER=9994
PIDS=()
FAILED=0
cleanup() {
for pid in "${PIDS[@]:-}"; do kill "$pid" 2>/dev/null; done
rm -rf "$TMP"
}
trap cleanup EXIT
ok() { printf ' OK %s\n' "$1"; }
bad() { printf ' FAIL %s\n' "$1"; FAILED=1; }
contains() { case "$1" in *"$2"*) ok "$3";; *) bad "$3 (missing '$2')";; esac; }
# Auf den Listener warten statt zu schlafen. Unter Last (parallel kompiliert, ein
# Scrape dazwischen) war "junction nach 0,7 s erreichbar" nicht immer wahr, und dann
# scheiterten Prüfungen, die mit dem Code nichts zu tun hatten.
wait_port() {
local port=$1 limit=$(( ${2:-10} * 20 )) i=0
while [ "$i" -lt "$limit" ]; do
if (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then exec 3>&-; return 0; fi
sleep 0.05; i=$((i+1))
done
return 1
}
# serviert wird vor dem Log-Eintrag: die Antwort ist beim Client, "served_by" folgt
# einen Wimpernschlag später. Ein direkter grep verliert dieses Rennen je nach
# Lastlage — deshalb kurz nachsehen statt sofort urteilen.
log_has() {
local file=$1 pat=$2 label=$3 i=0
while [ "$i" -lt 40 ]; do
grep -q "$pat" "$file" 2>/dev/null && { ok "$label"; return 0; }
sleep 0.05; i=$((i+1))
done
bad "$label (no '$pat' in $file after 2 s)"
}
# 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.
# 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 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/^/ /'
exit 1
fi
done
make -s >/dev/null || { echo "build failed"; exit 1; }
TLSCC="-DJ_HAVE_TLS -lssl -lcrypto"
[ -f /usr/include/openssl/ssl.h ] || TLSCC=""
# Die Bibliotheken gehören hinter die Quellen: davor aufgelistet löst der Linker
# SSL_pending nicht auf, und auf einem frischen Checkout (ohne fertiges tests/stub)
# scheitert die Suite an einer Zeile, die nie jemand ausprobiert hat.
# Nicht nur "fehlt es?" — auch "ist es älter als seine Quellen?". Ein von Hand ohne
# -DJ_HAVE_TLS gebauter Stub blieb sonst liegen und die TLS-Abschnitte scheiterten an
# einer Zeile, die niemand angefasst hat.
if [ ! -x tests/stub ] || [ tests/stub.c -nt tests/stub ] || [ src/conn.c -nt tests/stub ]; then
cc -std=c99 -O2 -Isrc -o tests/stub tests/stub.c src/conn.c $TLSCC || exit 1
fi
tests/stub $P_FAIL "FAILING" --fail & PIDS+=($!)
tests/stub $P_GATED "GATED" & PIDS+=($!)
tests/stub $P_SLOW "SLOW" --delay 6 & PIDS+=($!)
tests/stub $P_PONDER "PONDER" --delay 13 & PIDS+=($!)
sleep 0.5
# a hook that refuses until a marker file exists (created after 3 s)
cat > "$TMP/gate.sh" <<GATE
#!/bin/sh
[ -f "$TMP/open" ] && exit 0
echo "gate_closed"
exit 7
GATE
chmod +x "$TMP/gate.sh"
( sleep 3; : > "$TMP/open" ) &
PIDS+=($!)
cat > "$TMP/junction.conf" <<CFG
listen 127.0.0.1:$PORT
offline_hold_s 15
endpoint dead {
base http://127.0.0.1:$P_DEAD/v1
context 200000
priority 5
timeout 10
idle_timeout 5
}
endpoint failing {
base http://127.0.0.1:$P_FAIL/v1
context 64000
priority 10
timeout 10
idle_timeout 5
cooldown 60
}
endpoint gated {
base http://127.0.0.1:$P_GATED/v1
context 64000
priority 20
timeout 10
idle_timeout 5
hook $TMP/gate.sh
hook_retry 15
hook_backoff 1
}
endpoint slow {
base http://127.0.0.1:$P_SLOW/v1
context 128000
priority 30
timeout 30
idle_timeout 2
}
req for "*" pass dead, failing, gated, slow
CFG
./junction --config "$TMP/junction.conf" > "$TMP/router.log" 2>&1 &
PIDS+=($!)
sleep 0.7
REQ='{"model":"x","messages":[{"role":"user","content":"hi"}],"max_tokens":64}'
echo "== 1. dead -> offline, failing -> cooldown, gated waits for its hook =="
R1=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' -d "$REQ" \
"http://127.0.0.1:$PORT/v1/chat/completions")
contains "$R1" "served by GATED" "served by the gated endpoint once the hook opened"
grep -q "offline endpoint=dead" "$TMP/router.log" && ok "unreachable endpoint marked offline" \
|| bad "unreachable endpoint marked offline"
grep -q "failed endpoint=failing" "$TMP/router.log" && ok "503 endpoint cooled down" \
|| bad "503 endpoint cooled down"
grep -q "waiting endpoint=gated" "$TMP/router.log" && ok "hook refusal retried, not fatal" \
|| bad "hook refusal retried, not fatal"
echo "== 2. /status =="
ST=$(curl -s -m 5 "http://127.0.0.1:$PORT/status")
contains "$ST" '"name":"dead"' "status lists endpoints"
OFF=$(printf '%s' "$ST" | sed -n 's/.*"name":"dead"[^}]*"offline_s":\([0-9]*\).*/\1/p')
if [ -n "$OFF" ] && [ "$OFF" -gt 0 ]; then ok "dead endpoint holds an offline window (${OFF}s)"; else bad "offline_s=$OFF"; fi
echo "== 3. slow endpoint, forced: 'still_working' must be logged =="
curl -s -m 5 -X POST "http://127.0.0.1:$PORT/admin/pause/gated" >/dev/null
: > "$TMP/router.log"
R3=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' -d "$REQ" \
"http://127.0.0.1:$PORT/v1/chat/completions")
contains "$R3" "served by SLOW" "slow endpoint served"
grep -q "still_working side=upstream" "$TMP/router.log" && ok "silence logged as still_working" \
|| bad "silence logged as still_working"
curl -s -m 5 -X POST "http://127.0.0.1:$PORT/admin/resume/gated" >/dev/null
echo "== 4. rules: block, catch-all, context threshold =="
cat > "$TMP/rules.conf" <<CFG
listen 127.0.0.1:$((PORT+1))
endpoint small {
base http://127.0.0.1:$P_GATED/v1
context 64000
timeout 10
idle_timeout 5
}
endpoint big {
base http://127.0.0.1:$P_SLOW/v1
context 200000
timeout 30
idle_timeout 2
}
req need >100000 pass big
req for "blocked-*" block
req for "*" pass small
CFG
./junction --config "$TMP/rules.conf" > "$TMP/rules.log" 2>&1 &
PIDS+=($!)
sleep 0.7
R4a=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \
-d '{"model":"blocked-model","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \
"http://127.0.0.1:$((PORT+1))/v1/chat/completions")
contains "$R4a" "blocked_by_rule" "block rule refuses"
R4b=$(curl -s -m 30 -X POST -H 'Content-Type: application/json' \
-d '{"model":"anything","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \
"http://127.0.0.1:$((PORT+1))/v1/chat/completions")
contains "$R4b" "served by GATED" "catch-all rule serves through the small endpoint"
# "need" only ever uses a number the client wrote — no character counting, no default
R4c=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' \
-d '{"model":"anything","messages":[{"role":"user","content":"hi"}],"max_tokens":120000}' \
"http://127.0.0.1:$((PORT+1))/v1/chat/completions")
contains "$R4c" "served by SLOW" "declared max_tokens above the threshold picks the big endpoint"
R4d=$(curl -s -m 30 -X POST -H 'Content-Type: application/json' \
-d '{"model":"anything","messages":[{"role":"user","content":"a long prompt with no token budget declared at all"}]}' \
"http://127.0.0.1:$((PORT+1))/v1/chat/completions")
contains "$R4d" "served by GATED" "a request without max_tokens is not sized by guesswork"
echo "== 5. model rewrite ('pass <endpoint> as <model>') =="
cat > "$TMP/rewrite.conf" <<CFG
listen 127.0.0.1:$((PORT+2))
endpoint echo {
base http://127.0.0.1:$P_GATED/v1
context 64000
timeout 10
idle_timeout 5
}
req for "*" pass echo as "STUB-MODEL-NAME"
CFG
./junction --config "$TMP/rewrite.conf" > "$TMP/rewrite.log" 2>&1 &
PIDS+=($!)
sleep 0.7
R5=$(curl -s -m 20 -D- -X POST -H 'Content-Type: application/json' \
-d '{"model":"original-name","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \
"http://127.0.0.1:$((PORT+2))/v1/chat/completions")
contains "$R5" "served by GATED" "rewrite rule still serves"
contains "$R5" "X-Stub-Model: STUB-MODEL-NAME" "the endpoint receives the rewritten model"
case "$R5" in
*"original-name"*) bad "the client's model name leaked past the rewrite" ;;
*) ok "the client's model name was replaced, not appended" ;;
esac
log_has "$TMP/rewrite.log" "served_by endpoint=echo" "rewrite logged a served_by line"
echo "== 6. no rule matches -> 503, fast =="
cat > "$TMP/norule.conf" <<CFG
listen 127.0.0.1:$((PORT+3))
endpoint small {
base http://127.0.0.1:$P_GATED/v1
context 64000
}
req need >100000 pass small
CFG
./junction --config "$TMP/norule.conf" > "$TMP/norule.log" 2>&1 &
PIDS+=($!)
sleep 0.7
T0=$(date +%s%N)
R6=$(curl -s -m 10 -X POST -H 'Content-Type: application/json' -d "$REQ" \
"http://127.0.0.1:$((PORT+3))/v1/chat/completions")
MS=$(( ($(date +%s%N) - T0) / 1000000 ))
contains "$R6" "no_matching_rule" "unmatched request refused"
if [ "$MS" -lt 2000 ]; then ok "refusal in ${MS} ms"; else bad "refusal took ${MS} ms"; fi
echo "== 7. config errors are loud =="
printf 'listen 127.0.0.1:8090\nendpoint x {\n base http://a/v1\n timout 5\n}\n' > "$TMP/bad.conf"
OUT=$(./junction --config "$TMP/bad.conf" 2>&1)
contains "$OUT" "unknown endpoint keyword 'timout'" "typo in an endpoint key is an error"
printf 'listen 127.0.0.1:8090\nendpoint x {\n base http://a/v1\n}\nreq for "*" pass nope\n' > "$TMP/bad2.conf"
OUT2=$(./junction --config "$TMP/bad2.conf" 2>&1)
contains "$OUT2" "unknown endpoint 'nope'" "a rule may not pass to an unknown endpoint"
echo "== 8-10. features: chunked bodies, caching, header passthrough =="
FEAT=$((PORT+4))
cat > "$TMP/features.conf" <<CFG
listen 127.0.0.1:$FEAT
cache_ttl 60
cache_entries 32
cache_bytes 1048576
endpoint gated {
base http://127.0.0.1:$P_GATED/v1
context 64000
timeout 10
idle_timeout 5
header "X-Static: yes"
}
req for "*" check none pass gated
CFG
./junction --config "$TMP/features.conf" > "$TMP/features.log" 2>&1 &
PIDS+=($!)
sleep 0.7
BODY='{"model":"x","messages":[{"role":"user","content":"chunked body arrives intact"}],"max_tokens":8}'
C1=${BODY:0:16}
C2=${BODY:16}
RESP=$( { printf 'POST /v1/chat/completions HTTP/1.1\r\nHost: t\r\nContent-Type: application/json\r\n'
printf 'Transfer-Encoding: chunked\r\n\r\n'
printf '%x\r\n%s\r\n%x\r\n%s\r\n0\r\n\r\n' ${#C1} "$C1" ${#C2} "$C2"
} | nc -w 5 127.0.0.1 "$FEAT" )
contains "$RESP" "served by GATED" "chunked request is decoded and forwarded"
contains "$RESP" "X-Stub-Body-Len: ${#BODY}" "decoded body reached the endpoint byte-exact"
# same request twice: the second must come out of the cache (own body — the chunked
# request above already filled the cache for its own body)
# Temperatur 0, weil der Cache sonst bewusst nicht greift (siehe Abschnitt 22).
CBODY='{"model":"cachemodel","messages":[{"role":"user","content":"cache me once"}],"max_tokens":8,"temperature":0}'
R1=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \
"http://127.0.0.1:$FEAT/v1/chat/completions")
contains "$R1" "X-Junction-Cache: miss" "first request is a cache miss"
R2=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \
"http://127.0.0.1:$FEAT/v1/chat/completions")
contains "$R2" "X-Junction-Cache: hit" "identical second request is a cache hit"
R3=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \
"http://127.0.0.1:$FEAT/v1/chat/completions")
contains "$R3" "X-Junction-Cache: hit" "third request still a hit"
curl -s -m 5 -X POST "http://127.0.0.1:$FEAT/admin/flush/cache" >/dev/null
R4=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \
"http://127.0.0.1:$FEAT/v1/chat/completions")
contains "$R4" "X-Junction-Cache: miss" "flush clears the cache"
R5=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' \
-H 'Cache-Control: no-cache' -d "$CBODY" "http://127.0.0.1:$FEAT/v1/chat/completions")
contains "$R5" "X-Junction-Cache: off" "client no-cache bypasses the cache"
R6=$(curl -s -m 10 -D- -X POST -H 'Content-Type: application/json' -H 'X-Custom: abc123' \
-d '{"model":"y","messages":[{"role":"user","content":"header check"}],"max_tokens":8}' \
"http://127.0.0.1:$FEAT/v1/chat/completions")
contains "$R6" "X-Stub-Custom: abc123" "client header reaches the endpoint"
contains "$R6" "X-Stub-Static: yes" "endpoint 'header' line is injected"
contains "$R6" "X-Junction-Endpoint: gated" "response names the serving endpoint"
contains "$R6" "X-Stub-Xff: " "X-Forwarded-For reaches the endpoint"
echo "== 11. TLS listener =="
if command -v openssl >/dev/null 2>&1 && [ -f /usr/include/openssl/ssl.h ]; then
openssl req -x509 -newkey rsa:2048 -nodes -keyout "$TMP/key.pem" -out "$TMP/cert.pem" \
-days 1 -subj "/CN=localhost" >/dev/null 2>&1
TLSP=$((PORT+5))
cat > "$TMP/tls.conf" <<CFG
listen 127.0.0.1:$TLSP tls $TMP/cert.pem $TMP/key.pem
endpoint gated {
base http://127.0.0.1:$P_GATED/v1
context 64000
timeout 10
}
req for "*" check none pass gated
CFG
./junction --config "$TMP/tls.conf" > "$TMP/tls.log" 2>&1 &
PIDS+=($!)
sleep 0.8
TS=$(curl -sk -m 10 "https://127.0.0.1:$TLSP/status")
contains "$TS" '"listener":{"tls":true}' "TLS listener answers https"
TR=$(curl -sk -m 10 -X POST -H 'Content-Type: application/json' \
-d '{"model":"z","messages":[{"role":"user","content":"tls"}],"max_tokens":8}' \
"https://127.0.0.1:$TLSP/v1/chat/completions")
contains "$TR" "served by GATED" "request over TLS reaches the endpoint"
echo "== 12. TLS upstream (https endpoint) =="
./tests/stub 9443 SECURE --tls "$TMP/cert.pem" "$TMP/key.pem" > "$TMP/stubtls.log" 2>&1 &
PIDS+=($!)
sleep 0.8
cat > "$TMP/tlsup.conf" <<CFG
listen 127.0.0.1:$((PORT+6))
endpoint secure {
base https://127.0.0.1:9443/v1
tls_verify off
context 64000
timeout 10
idle_timeout 5
}
req for "*" check none pass secure
CFG
./junction --config "$TMP/tlsup.conf" > "$TMP/tlsup.log" 2>&1 &
PIDS+=($!)
sleep 0.8
US=$(curl -s -m 15 -X POST -H 'Content-Type: application/json' \
-d '{"model":"s","messages":[{"role":"user","content":"over tls"}],"max_tokens":8}' \
"http://127.0.0.1:$((PORT+6))/v1/chat/completions")
contains "$US" "served by SECURE" "request served by an https endpoint"
for _try in 1 2 3 4 5 6 7 8 9 10; do
grep -q "tls=1" "$TMP/tlsup.log" && break
sleep 0.1
done
grep -q "tls=1" "$TMP/tlsup.log" && ok "log marks the TLS connection" || bad "log marks the TLS connection"
# verification must actually be enforced: the same self-signed peer, tls_verify on
cat > "$TMP/tlsverify.conf" <<CFG
listen 127.0.0.1:$((PORT+7))
endpoint secure {
base https://127.0.0.1:9443/v1
context 64000
timeout 10
idle_timeout 5
}
req for "*" check none pass secure
CFG
./junction --config "$TMP/tlsverify.conf" > "$TMP/tlsverify.log" 2>&1 &
PIDS+=($!)
sleep 0.8
VS=$(curl -s -m 15 -o /dev/null -w '%{http_code}' -X POST \
-H 'Content-Type: application/json' -d '{"model":"s","max_tokens":8}' \
"http://127.0.0.1:$((PORT+7))/v1/chat/completions")
if [ "$VS" = "503" ]; then ok "self-signed cert refused when verification is on"; else bad "unverified TLS accepted (got $VS)"; fi
grep -q "tls_verify_failed" "$TMP/tlsverify.log" && ok "failure names the certificate problem" || bad "failure names the certificate problem"
else
echo " SKIP (no OpenSSL headers)"
fi
echo "== 13. concurrency: two slow requests run at the same time =="
CONC=$((PORT+8))
cat > "$TMP/conc.conf" <<CFG
listen 127.0.0.1:$CONC
max_inflight 4
endpoint slow {
base http://127.0.0.1:$P_SLOW/v1
context 65536
timeout 30
idle_timeout 10
}
req for "*" check none pass slow
CFG
./junction --config "$TMP/conc.conf" > "$TMP/conc.log" 2>&1 &
PIDS+=($!)
sleep 0.7
T0=$(date +%s%N)
curl -s -m 40 -X POST -H 'Content-Type: application/json' \
-d '{"model":"a","messages":[{"role":"user","content":"one"}],"max_tokens":8}' \
"http://127.0.0.1:$CONC/v1/chat/completions" > "$TMP/c1.out" &
C1=$!
curl -s -m 40 -X POST -H 'Content-Type: application/json' \
-d '{"model":"b","messages":[{"role":"user","content":"two"}],"max_tokens":8}' \
"http://127.0.0.1:$CONC/v1/chat/completions" > "$TMP/c2.out" &
C2=$!
wait "$C1" "$C2"
MS=$(( ($(date +%s%N) - T0) / 1000000 ))
contains "$(cat "$TMP/c1.out")" "served by SLOW" "first of the pair was served"
contains "$(cat "$TMP/c2.out")" "served by SLOW" "second of the pair was served"
if [ "$MS" -lt 11000 ]; then ok "both took ${MS} ms together (one 6 s delay, not two)"; else bad "serialised: ${MS} ms"; fi
echo "== 14. a waiting streamer is told why it waits =="
QUEUE=$((PORT+9))
cat > "$TMP/queue.conf" <<CFG
listen 127.0.0.1:$QUEUE
max_inflight 1
queue_timeout 40
endpoint slow {
base http://127.0.0.1:$P_SLOW/v1
context 65536
timeout 30
idle_timeout 10
}
req for "*" check none pass slow
CFG
./junction --config "$TMP/queue.conf" > "$TMP/queue.log" 2>&1 &
PIDS+=($!)
sleep 0.7
curl -s -m 40 -X POST -H 'Content-Type: application/json' \
-d '{"model":"first","messages":[{"role":"user","content":"blocker"}],"max_tokens":8}' \
"http://127.0.0.1:$QUEUE/v1/chat/completions" > "$TMP/q1.out" &
Q1=$!
sleep 0.6
Q2=$(curl -sN -m 40 -X POST -H 'Accept: text/event-stream' \
-H 'Content-Type: application/json' \
-d '{"model":"second","stream":true,"messages":[{"role":"user","content":"waiter"}]}' \
"http://127.0.0.1:$QUEUE/v1/chat/completions")
wait "$Q1"
contains "$Q2" ": junction: waiting for a free slot" "the waiting stream carries a status comment"
contains "$Q2" ": junction: still waiting" "and keeps saying so while it waits"
contains "$Q2" "served by SLOW" "the real answer arrives in the same stream"
case "$(cat "$TMP/q1.out")" in
*junction:*) bad "a non-streaming caller saw injected text" ;;
*) ok "the silent caller got no injected text" ;;
esac
grep -q "queued" "$TMP/queue.log" && ok "the queue is logged" || bad "the queue is logged"
echo "== 15. a stream stays alive while the model is thinking =="
HB=$((PORT+10))
cat > "$TMP/hb.conf" <<CFG
listen 127.0.0.1:$HB
max_inflight 4
endpoint pondering {
base http://127.0.0.1:$P_PONDER/v1
context 65536
timeout 60
idle_timeout 30
}
req for "*" check none pass pondering
CFG
./junction --config "$TMP/hb.conf" > "$TMP/hb.log" 2>&1 &
PIDS+=($!)
sleep 0.7
HB_OUT=$(curl -sN -m 40 -X POST -H 'Accept: text/event-stream' -H 'Content-Type: application/json' \
-d '{"model":"thinker","stream":true,"messages":[{"role":"user","content":"think hard"}]}' \
"http://127.0.0.1:$HB/v1/chat/completions")
contains "$HB_OUT" ": junction: model is still working" "a silent upstream produces heartbeats"
contains "$HB_OUT" "served by PONDER" "and the answer still arrives after the silence"
grep -q "still_working side=upstream" "$TMP/hb.log" && ok "the silence is logged as progress" \
|| bad "the silence is logged as progress"
# der stille Client bekommt weiterhin nichts injiziert
HB_PLAIN=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' \
-d '{"model":"quiet","messages":[{"role":"user","content":"no stream"}]}' \
"http://127.0.0.1:$HB/v1/chat/completions")
case "$HB_PLAIN" in
*junction:*) bad "a non-streaming caller received a heartbeat" ;;
*) ok "no heartbeat without a stream" ;;
esac
echo "== 16. budgets: soft throttle, hard skip, least-usage, virtual keys =="
P_BUD1=9995; P_BUD2=9996
tests/stub $P_BUD1 "RICH" & PIDS+=($!)
tests/stub $P_BUD2 "POOR" & PIDS+=($!)
sleep 0.4
# usage_cmd: ein Skript, das eine Zeile key=value ausgibt — genau wie in Produktion
cat > "$TMP/u90.sh" <<'EOS'
#!/bin/sh
echo "percent=90 used_usd=54 budget_usd=60 reset_s=0"
EOS
cat > "$TMP/u5.sh" <<'EOS'
#!/bin/sh
echo "percent=5 used_usd=3 budget_usd=60 reset_s=0"
EOS
chmod +x "$TMP/u90.sh" "$TMP/u5.sh"
BUD=$((PORT+11))
cat > "$TMP/budget.conf" <<CFG
listen 127.0.0.1:$BUD
balance least-usage
endpoint rich {
base http://127.0.0.1:$P_BUD1/v1
context 64000
timeout 20
usage_cmd $TMP/u90.sh
usage_poll 1
budget soft 80
budget hard 95
on_soft delay 1
}
endpoint poor {
base http://127.0.0.1:$P_BUD2/v1
context 64000
timeout 20
usage_cmd $TMP/u5.sh
usage_poll 1
cost 1.0
}
req for "*" check none pass rich, poor
CFG
VK_TEST="vk-secret-123" ./junction --config "$TMP/budget.conf" > "$TMP/budget.log" 2>&1 &
PIDS+=($!)
sleep 2.5 # der Usage-Faden muss mindestens einmal gelaufen sein
B_RESP=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \
-d '{"model":"ds4","messages":[{"role":"user","content":"balance"}]}' \
"http://127.0.0.1:$BUD/v1/chat/completions")
contains "$B_RESP" "served by POOR" "least-usage picks the endpoint with more headroom"
grep -q "usage endpoint=rich" "$TMP/budget.log" && ok "the usage command ran and was logged" \
|| bad "the usage command ran and was logged"
# hartes Limit: rich auf 96 % -> muss uebersprungen werden
cat > "$TMP/u96.sh" <<'EOS'
#!/bin/sh
echo "percent=96 used_usd=58 budget_usd=60 reset_s=0"
EOS
chmod +x "$TMP/u96.sh"
cat > "$TMP/hard.conf" <<CFG
listen 127.0.0.1:$((PORT+12))
endpoint rich {
base http://127.0.0.1:$P_BUD1/v1
context 64000
timeout 20
usage_cmd $TMP/u96.sh
usage_poll 1
budget hard 95
}
endpoint poor {
base http://127.0.0.1:$P_BUD2/v1
context 64000
timeout 20
}
req for "*" check none pass rich, poor
CFG
./junction --config "$TMP/hard.conf" > "$TMP/hard.log" 2>&1 &
PIDS+=($!)
sleep 2.5
H_RESP=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \
-d '{"model":"ds4","messages":[{"role":"user","content":"skip"}]}' \
"http://127.0.0.1:$((PORT+12))/v1/chat/completions")
contains "$H_RESP" "served by POOR" "an endpoint over its hard budget is skipped"
# weiche Drosselung: 85 % bei soft 80 -> mindestens 1 s Verzoegerung
cat > "$TMP/u85.sh" <<'EOS'
#!/bin/sh
echo "percent=85 used_usd=51 budget_usd=60 reset_s=0"
EOS
chmod +x "$TMP/u85.sh"
cat > "$TMP/soft.conf" <<CFG
listen 127.0.0.1:$((PORT+13))
endpoint rich {
base http://127.0.0.1:$P_BUD1/v1
context 64000
timeout 20
usage_cmd $TMP/u85.sh
usage_poll 1
budget soft 80
on_soft delay 2
}
req for "*" check none pass rich
CFG
./junction --config "$TMP/soft.conf" > "$TMP/soft.log" 2>&1 &
PIDS+=($!)
wait_port $((PORT+13)) 10
# Nicht schlafen und hoffen: warten, bis der Abruf den Prozentwert wirklich hat.
# usage_poll steht auf 1 s; unter Last war "nach 2,5 s ist es da" nicht immer wahr,
# und die Prüfung maß dann 8 ms statt der Drosselung.
for _i in $(seq 1 100); do
curl -s -m 2 "http://127.0.0.1:$((PORT+13))/status" | grep -q '"usage_percent":85' && break
sleep 0.1
done
T0=$(date +%s%N)
curl -s -m 20 -X POST -H 'Content-Type: application/json' \
-d '{"model":"ds4","messages":[{"role":"user","content":"slow down"}]}' \
"http://127.0.0.1:$((PORT+13))/v1/chat/completions" >/dev/null
T1=$(date +%s%N)
ELAPSED_MS=$(( (T1 - T0) / 1000000 ))
if [ "$ELAPSED_MS" -ge 1500 ]; then ok "soft budget delays the request (${ELAPSED_MS} ms)"; else bad "soft budget delays the request (${ELAPSED_MS} ms)"; fi
# virtuelle Schluessel: Modell ausserhalb des allow-Globs -> 403
cat > "$TMP/vkey.conf" <<CFG
listen 127.0.0.1:$((PORT+14))
vkey "webui" token_env VK_TEST allow "ds*"
endpoint rich {
base http://127.0.0.1:$P_BUD1/v1
context 64000
timeout 20
}
req for "*" check none pass rich
CFG
VK_TEST="vk-secret-123" ./junction --config "$TMP/vkey.conf" > "$TMP/vkey.log" 2>&1 &
PIDS+=($!)
sleep 0.8
VK_OK=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer vk-secret-123' \
-d '{"model":"ds4","messages":[{"role":"user","content":"allowed"}]}' \
"http://127.0.0.1:$((PORT+14))/v1/chat/completions")
contains "$VK_OK" "served by RICH" "a vkey inside its allow-glob is served"
VK_NO=$(curl -s -m 20 -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' \
-H 'Authorization: Bearer vk-secret-123' \
-d '{"model":"gpt-6","messages":[{"role":"user","content":"denied"}]}' \
"http://127.0.0.1:$((PORT+14))/v1/chat/completions")
[ "$VK_NO" = "403" ] && ok "a vkey outside its allow-glob is refused (403)" \
|| bad "a vkey outside its allow-glob is refused (got $VK_NO)"
# Konfigurationsfehler muessen laut sein
printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n budget soft abc\n}\n' > "$TMP/badbudget.conf"
OUT=$(./junction --config "$TMP/badbudget.conf" 2>&1)
contains "$OUT" "bad arguments" "a non-numeric budget is rejected"
printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n offpeak 25:00-26:00\n}\n' > "$TMP/badoffpeak.conf"
OUT=$(./junction --config "$TMP/badoffpeak.conf" 2>&1)
contains "$OUT" "bad arguments" "an impossible offpeak window is rejected"
# ctx-Filter und Vision-Routing liegen in einer eigenen Datei, damit run.sh lesbar bleibt.
# shellcheck source=tests/ctx-vision.sh
. "$(dirname "$0")/ctx-vision.sh"
# Die opencode-Brücke, gegen einen Nachbau des Sitzungs-API.
# shellcheck source=tests/opencode.sh
. "$(dirname "$0")/opencode.sh"
# Gewichtung, Balance pro Regel und Zeitlimits.
# shellcheck source=tests/balancing.sh
. "$(dirname "$0")/balancing.sh"
# Benannte Ketten und einzeilige Blöcke.
# shellcheck source=tests/pools.sh
. "$(dirname "$0")/pools.sh"
# Wiederholung vor dem Failover, Schlüssel-Pool und /metrics.
# shellcheck source=tests/retry-metrics.sh
. "$(dirname "$0")/retry-metrics.sh"
# Limits je virtuellem Schlüssel und das Spend-Log.
# shellcheck source=tests/spend-vkey.sh
. "$(dirname "$0")/spend-vkey.sh"
# Warten auf die Rückkehr der Kette, statt sofort zu scheitern.
# shellcheck source=tests/offline-wait.sh
. "$(dirname "$0")/offline-wait.sh"
# Wächter vor dem Weiterleiten.
# shellcheck source=tests/guard.sh
. "$(dirname "$0")/guard.sh"
# Kürzen von Werkzeugausgaben.
# shellcheck source=tests/compress.sh
. "$(dirname "$0")/compress.sh"
# Antwort-Cache und seine Grenze.
# 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"
# Mehrere Instanzen, gemeinsamer Cache, SO_REUSEPORT, Drain.
# 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"
# Retry-After des Anbieters statt eigener Wartezeit.
# shellcheck source=tests/retry-after.sh
. "$(dirname "$0")/retry-after.sh"
# Ein Modell zur Zeit, mehrere Modelle parallel, Präfix weg.
# shellcheck source=tests/local-pool.sh
. "$(dirname "$0")/local-pool.sh"
# Erreichbarkeit im Hintergrund prüfen: offline nehmen, dann wieder nachsehen.
# shellcheck source=tests/probe.sh
. "$(dirname "$0")/probe.sh"
# Ein Schlüssel in der Umgebung ist ein Endpunkt.
# shellcheck source=tests/env-providers.sh
. "$(dirname "$0")/env-providers.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.
echo
echo "== MCP =="
if python3 "$(dirname "$0")/mcp.py" > "$TMP/mcp.log" 2>&1; then
ok "$(tail -1 "$TMP/mcp.log")"
else
fail "MCP-Prüfungen fehlgeschlagen:"
sed 's/^/ /' "$TMP/mcp.log" | tail -12
fi
# Umschlag: die Antwort muss die id der Anfrage tragen. Der Fehler dahinter
# liess jeden Werkzeugaufruf mit einem Argument "id" (task_get, task_done ...)
# im Client ewig haengen, weil die Antwort die id des Arguments trug.
echo "== MCP-Umschlag =="
if python3 "$(dirname "$0")/mcp_envelope.py" > "$TMP/mcp_env.log" 2>&1; then
grep -E '^ |^PASS' "$TMP/mcp_env.log" | sed 's/^/ /'
else
fail "Umschlag-Pruefungen fehlgeschlagen:"
grep -vE '^\[jenv\]' "$TMP/mcp_env.log" | sed 's/^/ /' | tail -12
fi
# Gleichzeitigkeit: viele Clients am selben MCP-Eingang, ein langsamer Server
# darf die anderen nicht ausbremsen. Zaehlt die Abfragen an die Server mit.
echo "== MCP unter Last =="
if python3 "$(dirname "$0")/mcp_concurrency.py" > "$TMP/mcp_conc.log" 2>&1; then
grep -E '^ |^PASS' "$TMP/mcp_conc.log" | sed 's/^/ /'
else
fail "Gleichzeitigkeit fehlgeschlagen:"
grep -vE '^\[jtest\]' "$TMP/mcp_conc.log" | sed 's/^/ /' | tail -14
fi
# Steuerkanal: Regeln im Betrieb setzen und löschen, Endpunkte pausieren,
# Konfiguration schreiben — jeweils mit Prüfung, dass der Router danach anders handelt.
echo
echo "== Steuerkanal =="
if JUNCTION_BIN="$PWD/junction" python3 "$(dirname "$0")/control.py" > "$TMP/control.log" 2>&1; then
ok "$(tail -1 "$TMP/control.log")"
else
fail "Steuerkanal-Prüfungen fehlgeschlagen:"
sed 's/^/ /' "$TMP/control.log" | tail -12
fi
echo
if [ "$FAILED" -eq 0 ]; then echo "PASS"; else echo "FAILURES"; fi
exit "$FAILED"