#!/usr/bin/env python3 """A long single-conversation session that grows to about 250k tokens of real source text (test tooling for run-e2e.sh via E2E_RUN_CMD). Each turn adds a chunk of real Rust source from a directory as a new user message and asks a question that needs it; the model's reply stays in the history, so request k+1 extends request k and exercises the prefix cache the way a long agent session does. Every turn is streamed to record TTFT and the decode rate. Output: $E2E_OUT_DIR/long-session.json (never the prompt text). Needs E2E_BASE_URL, E2E_MODEL, E2E_API_KEY. long_session.py [--src DIR] [--turns N] [--target-tokens N] [--max-output N] """ import argparse import json import os import sys import time import urllib.error import urllib.request QUESTIONS = [ "Which function in the code above is the most complex, and why? Answer in at most six sentences.", "List the three places in all the code so far where memory pressure is decided, and what each decides. Be brief.", "Pick one module from the newest code and explain its invariants in at most six sentences.", "Which of the files so far would you change first to make startup faster, and what exactly? Be brief.", "Summarise in five bullet points what all the code so far does together.", "Name two risks you can see in the code so far and where they are. Be brief.", ] def collect(src): files = [] for root, _dirs, names in os.walk(src): for name in sorted(names): if name.endswith(".rs"): path = os.path.join(root, name) try: if os.path.getsize(path) > 1500: files.append(path) except OSError: pass files.sort() return files def take(files, start, chars): parts, used, i = [], 0, start while i < len(files) and used < chars: with open(files[i], encoding="utf-8", errors="replace") as f: text = f.read() parts.append("// ==== " + os.path.relpath(files[i], os.path.dirname(files[0])).replace("\\", "/") + "\n" + text) used += len(text) i += 1 return "\n".join(parts), i def stream(base, key, model, items, max_out): body = {"model": model, "input": items, "max_output_tokens": max_out, "stream": True} req = urllib.request.Request(base + "/v1/responses", json.dumps(body).encode(), {"Authorization": "Bearer " + key, "Content-Type": "application/json"}) t0 = time.time() first = last = None deltas = 0 text = [] usage = {} status = None try: with urllib.request.urlopen(req, timeout=3600) as r: for raw in r: line = raw.decode("utf8", "replace").strip() if not line.startswith("data:"): continue try: d = json.loads(line[5:]) except ValueError: continue ty = d.get("type", "") if ty.endswith("output_text.delta"): now = time.time() first = first or now last = now deltas += 1 text.append(d.get("delta", "")) elif ty.endswith("reasoning_text.delta"): now = time.time() first = first or now last = now deltas += 1 elif ty in ("response.completed", "response.incomplete", "response.failed"): resp = d.get("response", {}) usage = resp.get("usage") or {} status = resp.get("status") except urllib.error.HTTPError as e: return {"error": e.code, "body": e.read()[:300].decode("utf8", "replace"), "wall_s": time.time() - t0}, "" out = usage.get("output_tokens") or deltas info = { "wall_s": round(time.time() - t0, 2), "ttft_s": round(first - t0, 2) if first else None, "decode_tok_s": round((out - 1) / (last - first), 2) if first and last and last > first and out > 1 else None, "input_tokens": usage.get("input_tokens"), "cached_tokens": (usage.get("input_tokens_details") or {}).get("cached_tokens"), "output_tokens": usage.get("output_tokens"), "status": status, } return info, "".join(text) def main(): ap = argparse.ArgumentParser() ap.add_argument("--src", default=os.path.expanduser("~/work/leleka-head/src/crates")) ap.add_argument("--turns", type=int, default=5) ap.add_argument("--target-tokens", type=int, default=215000) ap.add_argument("--max-output", type=int, default=700) a = ap.parse_args() base, model, key = os.environ["E2E_BASE_URL"], os.environ["E2E_MODEL"], os.environ["E2E_API_KEY"] out_dir = os.environ.get("E2E_OUT_DIR", ".") files = collect(a.src) items, results, pos = [], [], 0 chars_per_token = 3.3 per_turn = a.target_tokens // a.turns for turn in range(a.turns): chunk, pos = take(files, pos, int(per_turn * chars_per_token)) items.append({"role": "user", "content": [{"type": "input_text", "text": chunk + "\n\n" + QUESTIONS[turn % len(QUESTIONS)]}]}) info, reply = stream(base, key, model, items, a.max_output) info["turn"] = turn + 1 results.append(info) print(json.dumps(info), flush=True) if "error" in info: break if info.get("input_tokens"): chars_per_token = sum(len(i["content"][0]["text"]) for i in items) / info["input_tokens"] items.append({"role": "assistant", "content": [{"type": "output_text", "text": reply}]}) with open(os.path.join(out_dir, "long-session.json"), "w") as f: json.dump(results, f, indent=1) return 0 if all("error" not in r for r in results) else 1 if __name__ == "__main__": sys.exit(main())