#!/usr/bin/env python3 """Agent sessions against an OpenAI-compatible server, to see whether a burst can collapse the prefix-cache hit rate for good (article "Prefix caches that collapse under bursts"). A session is a multi-turn agent loop: a private context of --ctx0 tokens, then --turns turns; each turn appends a tool output of --tool tokens and asks for --out tokens (ignore_eos), then waits --think seconds (the tool call) before the next turn. Every session's text is unique, so sessions share nothing: a turn hits the cache only if its own earlier turns are still resident. Arrivals are open (Poisson): --rate sessions/s, times --burst-mult between --burst-start and --burst-end seconds. --cap N admits at most N sessions at once (the others queue before their first turn): the papers' fix, a bound on resident sessions. Modes: --calibrate N closed loop with N sessions for --duration s; prints sessions/s and turn time (default) open arrivals for --duration s Outputs: .turns.jsonl (one line per turn), .metrics.jsonl (server /metrics every 5 s), .summary.json. """ import argparse, asyncio, json, random, re, time import aiohttp WORDS = ("cache page block token prefix kernel batch tensor queue route shard replica node " "stream warp memory latency budget scheduler decode prefill engine request session tool " "agent trace span metric alert config deploy rollout canary pod volume image layer").split() def text(rng, n_tokens): # ~1 token per word for this vocabulary (checked against the Qwen3 tokenizer: 0.98-1.05) return " ".join(rng.choice(WORDS) for _ in range(n_tokens)) class Run: def __init__(self, a): self.a, self.t0 = a, time.time() self.turns, self.active, self.done, self.started, self.queued = [], 0, 0, 0, 0 self.sem = asyncio.Semaphore(a.cap) if a.cap else None def now(self): return time.time() - self.t0 async def turn(self, s, sid, k, prompt): body = {"model": self.a.model, "prompt": prompt, "max_tokens": self.a.out, "temperature": 0, "ignore_eos": True, "stream": True, "stream_options": {"include_usage": True}} t = self.now(); ttft = None; out = []; usage = None try: async with s.post(self.a.url + "/v1/completions", json=body) as r: if r.status != 200: self.turns.append({"sid": sid, "k": k, "t": t, "error": r.status}); return None async for raw in r.content: line = raw.decode().strip() if not line.startswith("data:") or line.endswith("[DONE]"): continue d = json.loads(line[5:]) if d.get("usage"): usage = d["usage"] for c in d.get("choices", []): if c.get("text"): if ttft is None: ttft = self.now() - t out.append(c["text"]) except Exception as e: # noqa: BLE001 self.turns.append({"sid": sid, "k": k, "t": t, "error": str(e)[:200]}); return None cached = ((usage or {}).get("prompt_tokens_details") or {}).get("cached_tokens") self.turns.append({"sid": sid, "k": k, "t": round(t, 3), "lat": round(self.now() - t, 3), "ttft": round(ttft, 3) if ttft is not None else None, "prompt": (usage or {}).get("prompt_tokens"), "cached": cached}) return "".join(out) async def session(self, s, sid): rng = random.Random(sid * 7919 + 13) self.queued += 1 if self.sem: await self.sem.acquire() self.queued -= 1; self.active += 1; self.started += 1 try: ctx = f"Session {sid}. " + text(rng, self.a.ctx0) for k in range(self.a.turns): ctx += "\nTool output: " + text(rng, self.a.tool) + "\nAssistant:" ans = await self.turn(s, sid, k, ctx) if ans is None: return ctx += ans if k < self.a.turns - 1: await asyncio.sleep(self.a.think) self.done += 1 finally: self.active -= 1 if self.sem: self.sem.release() async def scrape(run, s, f, stop): keys = ("vllm:prefix_cache_queries_total", "vllm:prefix_cache_hits_total", "vllm:num_requests_running", "vllm:num_requests_waiting", "vllm:kv_cache_usage_perc", "vllm:num_preemptions_total", "vllm:prompt_tokens_total", "vllm:generation_tokens_total") while not stop.is_set(): try: async with s.get(run.a.url + "/metrics") as r: body = await r.text() row = {"t": round(run.now(), 1), "active": run.active, "queued": run.queued, "done": run.done} for k in keys: m = re.search(r"^" + re.escape(k) + r"(?:\{[^}]*\})? ([0-9.e+-]+)$", body, re.M) if m: row[k.split(":")[1]] = float(m.group(1)) f.write(json.dumps(row) + "\n"); f.flush() except Exception: # noqa: BLE001 pass await asyncio.sleep(5) async def main(): ap = argparse.ArgumentParser() ap.add_argument("--url", default="http://127.0.0.1:8012") ap.add_argument("--model", default="m") ap.add_argument("--ctx0", type=int, default=2000) ap.add_argument("--turns", type=int, default=10) ap.add_argument("--tool", type=int, default=400) ap.add_argument("--out", type=int, default=64) ap.add_argument("--think", type=float, default=2.0) ap.add_argument("--rate", type=float, default=0.05) ap.add_argument("--burst-mult", type=float, default=3.0) ap.add_argument("--burst-start", type=float, default=300) ap.add_argument("--burst-end", type=float, default=480) ap.add_argument("--duration", type=float, default=1200) ap.add_argument("--cap", type=int, default=0) ap.add_argument("--calibrate", type=int, default=0) ap.add_argument("--seed", type=int, default=1) ap.add_argument("--prefix", required=True) a = ap.parse_args() run = Run(a) stop = asyncio.Event() tasks = [] timeout = aiohttp.ClientTimeout(total=None, sock_read=900) async with aiohttp.ClientSession(timeout=timeout, connector=aiohttp.TCPConnector(limit=0)) as s: mf = open(a.prefix + ".metrics.jsonl", "w") scr = asyncio.create_task(scrape(run, s, mf, stop)) sid = 0 if a.calibrate: async def worker(): nonlocal sid while run.now() < a.duration: sid += 1 await run.session(s, sid) await asyncio.gather(*(worker() for _ in range(a.calibrate))) else: rng = random.Random(a.seed) while run.now() < a.duration: t = run.now() lam = a.rate * (a.burst_mult if a.burst_start <= t < a.burst_end else 1.0) await asyncio.sleep(rng.expovariate(lam)) if run.now() >= a.duration: break sid += 1 tasks.append(asyncio.create_task(run.session(s, sid))) # stop: cancel what is still running; it is counted as unfinished for t in tasks: t.cancel() await asyncio.gather(*tasks, return_exceptions=True) stop.set(); await scr; mf.close() with open(a.prefix + ".turns.jsonl", "w") as f: for r in run.turns: f.write(json.dumps(r) + "\n") ok = [r for r in run.turns if "error" not in r] summ = {"args": vars(a), "sessions_started": run.started, "sessions_done": run.done, "turns": len(ok), "errors": len(run.turns) - len(ok), "wall": round(run.now(), 1)} if a.calibrate and ok: summ["sessions_per_s"] = round(run.done / run.now(), 4) summ["turn_lat_mean"] = round(sum(r["lat"] for r in ok) / len(ok), 2) json.dump(summ, open(a.prefix + ".summary.json", "w"), indent=1) print(json.dumps(summ)) if __name__ == "__main__": asyncio.run(main())