local-web-search/loadtest/loadtest.py
User cb1f887a48 Add loadtest/ harness and query sets
Two ramped-concurrency exercisers for POST /search/contents plus a flat
290-query list (58 topics x 5 templates) for feeding external harnesses.
Endpoint/key come from LWSS_BASE/LWSS_KEY env vars; no secrets committed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 17:53:18 -07:00

80 lines
3.7 KiB
Python

"""Ramped concurrency load test against the live LWSS /search/contents.
Fires N simultaneous content-searches (distinct queries so caching doesn't hide
the render bottleneck) at increasing N, records per-request latency, HTTP status,
and server-side degradation.
Usage:
export LWSS_BASE="https://websearch.neilbantoc.dev" # or your own endpoint
export LWSS_KEY="<your MCP bearer key>"
python loadtest.py
"""
import asyncio, os, time, statistics
import httpx
BASE = os.environ.get("LWSS_BASE", "https://websearch.neilbantoc.dev")
KEY = os.environ["LWSS_KEY"] # required; do not hardcode secrets
HDR = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}
MAX_RESULTS = 5
CLIENT_TIMEOUT = 120 # above the server's 60s stage timeout so we see 502s, not client aborts
LEVELS = [1, 3, 6, 10, 16, 20]
QUERIES = [
"history of the printing press","how do tsunamis form","best practices postgres indexing",
"photosynthesis light reactions","rust vs go concurrency model","james webb telescope discoveries 2026",
"mediterranean diet health effects","how lithium batteries degrade","origins of jazz music",
"kubernetes ingress explained","great barrier reef bleaching","quantum error correction basics",
"roman aqueduct engineering","caffeine metabolism half life","tcp congestion control algorithms",
"volcano types and eruptions","machine learning gradient descent","history of the silk road",
"how vaccines train immune system","black hole event horizon","sourdough fermentation science",
"electric vehicle battery recycling","north sea wind farms","how gps satellites work",
"coral reef restoration methods","the fall of constantinople","monarch butterfly migration",
"cryptography elliptic curves","antarctic ice sheet melting","how noise cancelling works",
"the history of coffee trade","neural network backpropagation","deep sea hydrothermal vents",
"renaissance art techniques","how solar panels convert light","plate tectonics explained",
]
async def one(client, q):
t0 = time.monotonic()
try:
r = await client.post(f"{BASE}/search/contents", headers=HDR,
json={"query": q, "max_results": MAX_RESULTS})
dt = time.monotonic() - t0
if r.status_code == 200:
d = r.json()
got = sum(1 for x in d["results"] if x.get("content"))
return ("ok", dt, r.status_code, got, len(d.get("failed_urls", [])))
return ("http_err", dt, r.status_code, 0, 0)
except Exception as e:
return ("exc", time.monotonic() - t0, type(e).__name__, 0, 0)
async def level(client, n, qstart):
qs = [QUERIES[(qstart + i) % len(QUERIES)] for i in range(n)]
t0 = time.monotonic()
res = await asyncio.gather(*(one(client, q) for q in qs))
wall = time.monotonic() - t0
lat = [r[1] for r in res]
ok = [r for r in res if r[0] == "ok"]
print(f"\n=== concurrency {n} ===")
print(f" wall time: {wall:5.1f}s for {n} requests")
print(f" succeeded: {len(ok)}/{n}")
print(f" latency p50: {statistics.median(lat):5.1f}s "
f"min {min(lat):.1f} max {max(lat):.1f}")
if len(lat) >= 4:
print(f" latency p95: {sorted(lat)[int(len(lat)*0.95)-1]:5.1f}s")
avg_content = statistics.mean([r[3] for r in ok]) if ok else 0
print(f" avg pages w/ content per req: {avg_content:.1f}/{MAX_RESULTS}")
fails = [r for r in res if r[0] != "ok"]
if fails:
for r in fails:
print(f" FAIL: {r[0]} status={r[2]}")
return qstart + n
async def main():
qs = 0
async with httpx.AsyncClient(timeout=CLIENT_TIMEOUT) as client:
for n in LEVELS:
qs = await level(client, n, qs)
await asyncio.sleep(3) # brief cooldown between levels
asyncio.run(main())