Files
junction/tests/mcp_concurrency.py
Hermes 107de9e39e tests: stop three ways the suite failed for the wrong reason
gcc -fanalyzer warns on snprintf("%s") between two elements of the same array
it cannot prove disjoint; memmove of the fixed-size element is what the call
did, without the warning.

mcp.py slept a fixed 1.2 s for junction to listen while junction is still
talking to its MCP servers; under load the first POST was refused and the
whole suite failed. It now waits for the port, and an empty call list is a
reported failure instead of an IndexError that leaves a router behind.

mcp_concurrency.py's fake servers kept the default listen backlog of 5. 32
simultaneous calls overflowed it, two came back "MCP server unavailable" and
the fast server looked slow (1.22 s, 38/40 intact). With backlog 128: 40/40
intact, fast answers in 0.05 s.

check_ports.py resolves variables in file order (RDP is a stub port and later a
router port) and sees env-prefixed stub starts; run.sh prints who holds a port
when wait_port gives up.

Full suite: 537 OK, 0 FAIL, PASS. Installed and restarted; /admin, /spend and
/metrics answer 403 from the LAN and 200 on loopback, streams stay clean.
2026-11-18 23:47:14 +00:00

281 lines
11 KiB
Python

#!/usr/bin/env python3
"""Gleichzeitigkeit: viele Clients am selben junction, ohne dass einer den
anderen aussperrt.
Der Test prüft drei Dinge, die im Betrieb wehtun:
1. Ein kalter Cache darf nicht dazu führen, dass N Clients N-mal alle
Server abfragen — genau einer baut, die anderen lesen mit.
2. Ein langsamer Server darf die Aufrufe an einen schnellen nicht
blockieren. Wer auf tasksd wartet, während skilld antwortet, merkt
nichts von fremden Zeitlimits.
3. Antworten unter Last müssen unversehrt sein: gleiche Länge, gleiches
JSON, keine zerrissenen oder leeren Körper.
Die Stub-Server zählen mit, wie oft sie gefragt wurden — damit lässt sich
"einer baut" von "alle bauen" unterscheiden, statt es zu vermuten.
"""
import json
import os
import socket
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
JUNCTION = os.environ.get("JUNCTION_BIN", "./junction")
PORT = 18196
SLOW_DELAY = 3.0 # wie lange der langsame Server braucht
LIST_CALLS = {"fast": 0, "slow": 0}
CALL_CALLS = {"fast": 0, "slow": 0}
ZAEHL_MU = threading.Lock()
def zaehle(kind, which):
with ZAEHL_MU:
if kind == "list":
LIST_CALLS[which] += 1
else:
CALL_CALLS[which] += 1
TOOLS = {
"fast": [{"name": "schnell", "description": "antwortet sofort",
"inputSchema": {"type": "object", "properties": {}}}],
"slow": [{"name": "langsam", "description": "braucht drei Sekunden",
"inputSchema": {"type": "object", "properties": {}}}],
}
def make_handler(which):
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, format, *args): # noqa: A002 (Basisklasse)
pass
def _send(self, obj, code=200):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
req = json.loads(self.rfile.read(n) or b"{}")
m = req.get("method")
if m == "initialize":
return self._send({"jsonrpc": "2.0", "id": req.get("id"),
"result": {"protocolVersion": "2025-06-18",
"capabilities": {"tools": {}},
"serverInfo": {"name": which}}})
if m == "tools/list":
zaehle("list", which)
if which == "slow":
time.sleep(0.05) # ein bisschen Realität
return self._send({"jsonrpc": "2.0", "id": req.get("id"),
"result": {"tools": TOOLS[which]}})
if m in ("prompts/list", "resources/list"):
key = "prompts" if m.startswith("prompts") else "resources"
return self._send({"jsonrpc": "2.0", "id": req.get("id"),
"result": {key: []}})
if m == "tools/call":
zaehle("call", which)
if which == "slow":
time.sleep(SLOW_DELAY)
return self._send({"jsonrpc": "2.0", "id": req.get("id"),
"result": {"content": [{"type": "text",
"text": f"{which}:ok"}],
"isError": False}})
return self._send({"jsonrpc": "2.0", "id": req.get("id"),
"error": {"code": -32601, "message": "no"}})
return H
def freier_port():
s = socket.socket()
s.bind(("127.0.0.1", 0))
p = s.getsockname()[1]
s.close()
return p
def post(url, payload, timeout=40):
data = json.dumps(payload).encode()
req = urllib.request.Request(url, data=data, method="POST",
headers={"Content-Type": "application/json"})
t0 = time.time()
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return time.time() - t0, r.status, r.read().decode()
except urllib.error.HTTPError as e:
return time.time() - t0, e.code, e.read().decode()
except Exception as e: # noqa: BLE001
return time.time() - t0, 0, str(e)
def main():
fast_port, slow_port = freier_port(), freier_port()
for which, port in (("fast", fast_port), ("slow", slow_port)):
# The default backlog is 5. Thirty-two simultaneous connections then
# overflow the listen queue and two calls fail with "server
# unavailable" -- a property of this fake server, not of junction.
class Srv(ThreadingHTTPServer):
request_queue_size = 128
daemon_threads = True
srv = Srv(("127.0.0.1", port), make_handler(which))
threading.Thread(target=srv.serve_forever, daemon=True).start()
tmp = tempfile.mkdtemp()
conf = os.path.join(tmp, "junction.conf")
with open(conf, "w") as f:
f.write(f"""
listen 127.0.0.1:{PORT}
log_prefix jtest
max_inflight 32
queue_timeout 60
probe_interval 0
mcp_auth off
mcp_cache_ttl 60
mcp fast url http://127.0.0.1:{fast_port}/mcp timeout 30
mcp slow url http://127.0.0.1:{slow_port}/mcp timeout 30
endpoint dummy {{
base http://127.0.0.1:9/v1
timeout 1
api_key_env DUMMY_KEY
}}
""")
env = dict(os.environ, DUMMY_KEY="x")
proc = subprocess.Popen([JUNCTION, "--config", conf], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
url = f"http://127.0.0.1:{PORT}/mcp"
fehler = []
# warten, bis junction horcht
for _ in range(100):
try:
socket.create_connection(("127.0.0.1", PORT), 0.2).close()
break
except OSError:
time.sleep(0.05)
else:
print("FAIL: junction horcht nicht")
return 1
try:
# --- 1. kalter Cache, viele Clients gleichzeitig -------------------
LIST_CALLS["fast"] = LIST_CALLS["slow"] = 0
antworten = []
mu = threading.Lock()
def liste(i):
d, st, b = post(url, {"jsonrpc": "2.0", "id": i, "method": "tools/list"})
with mu:
antworten.append((d, st, b))
faden = [threading.Thread(target=liste, args=(i,)) for i in range(40)]
t0 = time.time()
for f in faden:
f.start()
for f in faden:
f.join()
dauer = time.time() - t0
ok = [a for a in antworten if a[1] == 200 and '"result"' in a[2]]
# Nur das result vergleichen: die id unterscheidet sich naturgemäß.
def nur_result(koerper):
try:
return json.dumps(json.loads(koerper).get("result"), sort_keys=True)
except Exception:
return koerper
gleich = len({nur_result(a[2]) for a in ok}) == 1
print(f" 40 gleichzeitige tools/list, kalter Cache: {dauer:.2f}s, "
f"{len(ok)}/40 ok, Antworten identisch: {gleich}")
print(f" Server-Abfragen fuer die Liste: fast={LIST_CALLS['fast']} "
f"slow={LIST_CALLS['slow']} (erwartet: 1 und 1)")
if len(ok) != 40:
fehler.append(f"{40 - len(ok)} von 40 Listen-Aufrufen ohne Antwort")
if not gleich:
fehler.append("Antworten unterscheiden sich unter Last")
if LIST_CALLS["fast"] > 1 or LIST_CALLS["slow"] > 1:
fehler.append(f"Cache half nicht: {LIST_CALLS} statt je 1")
# --- 2. langsamer Server darf den schnellen nicht blockieren ------
zeiten = {"schnell": [], "langsam": []}
mu = threading.Lock()
def rufe(name, i):
d, st, b = post(url, {"jsonrpc": "2.0", "id": 1000 + i,
"method": "tools/call",
"params": {"name": name, "arguments": {}}})
with mu:
zeiten["langsam" if name.startswith("slow") else "schnell"].append((d, st, b))
faden = []
for i in range(8): # acht Clients auf den langsamen
faden.append(threading.Thread(target=rufe, args=(f"slow__langsam", i)))
for i in range(32): # zweiunddreissig auf den schnellen
faden.append(threading.Thread(target=rufe, args=(f"fast__schnell", i)))
t0 = time.time()
for f in faden:
f.start()
for f in faden:
f.join()
gesamt = time.time() - t0
schn = [z[0] for z in zeiten["schnell"] if z[1] == 200]
lan = [z[0] for z in zeiten["langsam"] if z[1] == 200]
schn_max = max(schn) if schn else 99
lan_max = max(lan) if lan else 99
print(f" 8 langsame + 32 schnelle Aufrufe zusammen: {gesamt:.2f}s")
print(f" schnell: {len(schn)}/32 ok, langsamster {schn_max:.2f}s")
print(f" langsam: {len(lan)}/8 ok, langsamster {lan_max:.2f}s")
if len(schn) != 32 or len(lan) != 8:
fehler.append(f"nicht alle Aufrufe kamen durch: {len(schn)}/32, {len(lan)}/8")
if schn_max > 1.5:
fehler.append(f"schneller Server wurde ausgebremst: {schn_max:.2f}s")
if lan_max > SLOW_DELAY + 3:
fehler.append(f"langsamer Server brauchte {lan_max:.2f}s statt ~{SLOW_DELAY}s")
# --- 3. Antworten sind unversehrt ---------------------------------
kaputt = [z for z in zeiten["schnell"] + zeiten["langsam"]
if z[1] == 200 and "fast:ok" not in z[2] and "slow:ok" not in z[2]]
print(f" unversehrte Antworten: {40 - len(kaputt)}/40")
if kaputt:
for z in kaputt[:3]:
print(f" kaputt: status={z[1]} body={z[2][:160]!r}")
fehler.append(f"{len(kaputt)} zerrissene Antworten")
finally:
proc.terminate()
try:
proc.wait(5)
except subprocess.TimeoutExpired:
proc.kill()
if fehler:
print("FAIL:")
for f in fehler:
print(" -", f)
err = proc.stderr.read().decode() if proc.stderr else ""
if err.strip():
print("--- junction stderr ---")
print(err[-1200:])
return 1
print("PASS: Gleichzeitigkeit — 40 Listen-Aufrufe mit einem einzigen Aufbau, "
"langsamer Server blockiert schnellen nicht, alle Antworten unversehrt")
return 0
if __name__ == "__main__":
sys.exit(main())