local-web-search/loadtest/loadtest2.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

79 lines
3.7 KiB
Python

"""Clean ramped load test — large UNIQUE query set so nothing hits cache.
Builds 300 unique queries (60 topics x 5 templates) and ramps concurrency,
reporting latency and per-page render yield for the full /search/contents path.
Usage:
export LWSS_BASE="https://websearch.neilbantoc.dev" # or your own endpoint
export LWSS_KEY="<your MCP bearer key>"
python loadtest2.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
LEVELS = [1, 4, 8, 12, 16, 20]
TOPICS = [
"the printing press","tsunamis","postgres indexing","photosynthesis","volcanoes","jazz music",
"the mediterranean diet","lithium batteries","the silk road","kubernetes","coral reefs","quantum computing",
"roman aqueducts","caffeine","tcp networking","gradient descent","the roman empire","monarch butterflies",
"elliptic curve cryptography","antarctic ice","noise cancelling","the coffee trade","neural networks",
"hydrothermal vents","renaissance art","solar panels","plate tectonics","the french revolution","glaciers",
"sourdough bread","wind turbines","gps satellites","the great wall of china","honeybees","nuclear fusion",
"the human immune system","black holes","the amazon rainforest","electric cars","the industrial revolution",
"vaccines","tectonic earthquakes","the byzantine empire","desalination","the ozone layer","fiber optics",
"the cold war","permafrost","hydrogen fuel","the mongol empire","antibiotics","ocean currents",
"the apollo program","genetics","the stock market","volcano monitoring","migratory birds","semiconductors",
]
TEMPLATES = ["how does {} work","the history of {}","explain {} in detail","{} facts and science","understanding {}"]
QUERIES = [t.format(x) for x in TOPICS for t in TEMPLATES] # 60*5 = 300 unique
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"))
n = len(d["results"])
return ("ok", dt, got, n)
return ("http_%d" % r.status_code, dt, 0, 0)
except Exception as e:
return (type(e).__name__, time.monotonic() - t0, 0, 0)
async def level(client, n, qstart):
qs = QUERIES[qstart:qstart+n]
t0 = time.monotonic()
res = await asyncio.gather(*(one(client, q) for q in qs))
wall = time.monotonic() - t0
ok = [r for r in res if r[0] == "ok"]
lat = [r[1] for r in res]
full = sum(1 for r in ok if r[2] >= r[3] and r[3] > 0) # all results had content
partial = sum(1 for r in ok if 0 < r[2] < r[3])
empty = sum(1 for r in ok if r[2] == 0)
errs = [r for r in res if r[0] != "ok"]
total_pages = sum(r[3] for r in ok)
got_pages = sum(r[2] for r in ok)
print(f"\n=== concurrency {n} ===")
print(f" wall {wall:5.1f}s | p50 {statistics.median(lat):5.1f}s | min {min(lat):.1f} max {max(lat):.1f}")
print(f" requests: {len(ok)}/{n} ok (full={full} partial={partial} empty={empty}) errors={len(errs)}")
print(f" page yield: {got_pages}/{total_pages} rendered "
f"({100*got_pages/total_pages:.0f}%)" if total_pages else " page yield: n/a")
for r in errs:
print(" ERROR:", r[0])
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(4)
asyncio.run(main())