Files
leleka/scripts/e2e/long_session.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 c84fcdcdd5 e2e: long_session.py refuses an empty corpus, records the corpus digest and fails when the last turn is shorter than 200k tokens
The owner's cleanup removed the source directory of the 245k session; the run then streamed 73-306 token prompts and looked healthy. Exit 2: no usable file.
Exit 3: final-turn input_tokens < --min-final-tokens (default 200000, 0 disables). corpus.sha256 (file list with per-file digests, char count) is written next to long-session.json.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 01:39:10 +01:00

167 lines
8.0 KiB
Python

#!/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 hashlib
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()[: chars - used] # the last file is cut to the budget, so a turn never overshoots by a whole file
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,
}
reply = "".join(text)
info["reply_sha256"] = hashlib.sha256(reply.encode()).hexdigest()[:16] # lets two configurations be compared without storing the text
return info, reply
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)
ap.add_argument("--min-final-tokens", type=int, default=200000, help="exit 3 when the last turn's prompt is shorter (0: no check)")
ap.add_argument("--context", type=int, default=262144, help="the engine's context; the last turn is cut to fit under it")
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)
# Guard (STRA-245): a source directory that vanished or holds no usable file made a "245k" session of a few hundred tokens and the run looked fine.
if not files:
print("long_session: --src %s yields no .rs file larger than 1500 bytes; refusing to run an empty session" % a.src, file=sys.stderr)
return 2
corpus = hashlib.sha256()
total_chars = 0
for path in files:
with open(path, "rb") as f:
data = f.read()
corpus.update(os.path.relpath(path, a.src).replace("\\", "/").encode() + b"\x00" + hashlib.sha256(data).digest())
total_chars += len(data)
digest = corpus.hexdigest()
print("long_session: corpus %s: %d files, %d chars, sha256 %s" % (a.src, len(files), total_chars, digest), file=sys.stderr, flush=True)
with open(os.path.join(out_dir, "corpus.sha256"), "w") as f:
f.write("src=%s files=%d chars=%d sha256=%s\n" % (a.src, len(files), total_chars, digest))
items, results, pos = [], [], 0
chars_per_token = 3.3
per_turn = a.target_tokens // a.turns
used_tokens = 0
for turn in range(a.turns):
# the last turn takes what is left under the context (prompt + output budget + 8 tokens of margin), 4% under for the estimate's error
room = int((a.context - a.max_output - 8 - used_tokens - 400) * 0.96)
want = per_turn if turn < a.turns - 1 else min(max(a.target_tokens - used_tokens, per_turn), room)
chunk, pos = take(files, pos, int(min(want, room) * 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"):
used_tokens = info["input_tokens"] + (info.get("output_tokens") or 0)
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)
if any("error" in r for r in results):
return 1
final = (results[-1].get("input_tokens") or 0) if results else 0
if final < a.min_final_tokens:
print("long_session: the final turn had %d input tokens, fewer than --min-final-tokens %d: this is not the long session it is meant to be (short corpus?)" % (final, a.min_final_tokens), file=sys.stderr)
return 3
return 0
if __name__ == "__main__":
sys.exit(main())