"""Tests of the 256k-session replay driver (STRA-308, rule E7). Run: python -m unittest discover -s scripts/e2e -p "test_replay_session.py" -v Stdlib only, Python >= 3.9. The engines are in-test http.server fakes of /v1/responses (two reply generators, a request log); no GPU, no real engine.""" import hashlib import http.server import json import os import re import subprocess import sys import tempfile import threading import unittest HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import replay_session as R # noqa: E402 SCRIPT = os.path.join(HERE, "replay_session.py") TURNS = 5 SECRET_KEY = "sk-test-secret-key-0123456789" def n_for_turn(k): return 7 + 3 * k # the H0 reply length of turn k (1-based) in the recording class FakeEngine: """POST /v1/responses -> SSE stream. reply(turn, n_requested) -> (text, output_tokens). Records every request body in .log (raw JSON text).""" def __init__(self, reply): self.reply = reply self.log = [] self.auth = [] engine = self class H(http.server.BaseHTTPRequestHandler): def log_message(self, *args): pass def do_POST(self): raw = self.rfile.read(int(self.headers.get("Content-Length", "0"))).decode("utf8") engine.log.append(raw) engine.auth.append(self.headers.get("Authorization")) body = json.loads(raw) items = body["input"] turn = sum(1 for i in items if i["role"] == "user") text, out_tok = engine.reply(turn, body.get("max_output_tokens")) chars = sum(len(i["content"][0]["text"]) for i in items) usage = {"input_tokens": chars // 3, "output_tokens": out_tok, "input_tokens_details": {"cached_tokens": 0 if turn == 1 else chars // 4}} self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.end_headers() half = max(1, len(text) // 2) for part in (text[:half], text[half:]): self.wfile.write(("data: " + json.dumps({"type": "response.output_text.delta", "delta": part}) + "\n\n").encode()) self.wfile.write(("data: " + json.dumps({"type": "response.completed", "response": {"status": "completed", "usage": usage}}) + "\n\n").encode()) self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H) self.url = "http://127.0.0.1:%d" % self.server.server_address[1] self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) self.thread.start() def close(self): self.server.shutdown() self.server.server_close() def reply_recording(turn, n_req): return "recorded answer %d " % turn + "x" * 40, n_for_turn(turn) def reply_a(turn, n_req): return "engine A says %d " % turn + "a" * 30, n_req # length matches N_k def reply_b(turn, n_req): return "ENGINE-B-ANSWER %d " % turn + "b" * 50, n_req # different text, same length def make_src(root): d = os.path.join(root, "src") os.makedirs(d) for i in range(8): with open(os.path.join(d, "mod%d.rs" % i), "w") as f: f.write(("// module %d\nfn f%d() { let x = %d; }\n" % (i, i, i * 7)) * 80) return d def run_cli(*args): p = subprocess.run([sys.executable, SCRIPT] + list(args), capture_output=True, text=True, timeout=120) return p.returncode, p.stdout, p.stderr class Base(unittest.TestCase): @classmethod def setUpClass(cls): cls.tmp = tempfile.TemporaryDirectory() cls.src = make_src(cls.tmp.name) cls.h0 = os.path.join(cls.tmp.name, "h0.json") cls.rec = FakeEngine(reply_recording) rc, out, err = run_cli("record-h0", "--base-url", cls.rec.url, "--out", cls.h0, "--src", cls.src, "--turns", str(TURNS), "--target-tokens", "900", "--context", "262144", "--max-output", "300", "--model", "fake") assert rc == 0, (out, err) with open(cls.h0) as f: cls.h0_data = json.load(f) @classmethod def tearDownClass(cls): cls.rec.close() cls.tmp.cleanup() def replay(self, engine, name, *extra): out = os.path.join(self.tmp.name, name) rc, so, se = run_cli("replay", "--h0", self.h0, "--base-url", engine.url, "--out", out, "--src", self.src, "--model", "fake", *extra) data = None if os.path.exists(out): with open(out) as f: data = json.load(f) return rc, data, so, se class TestAggregates(unittest.TestCase): """Fixture with known numbers, hand computed. Turn (ttft, latency, output, N_k): (10, 12, 20, 20) (20, 28, 40, 40) (30, 36, 60, 60). decode times 2, 8, 6 = 16 s; per-turn rates 10, 5, 10 tok/s (mean 8.33, NOT the answer); output total 120.""" def turns(self, n3=60): return [{"ttft_s": 10.0, "latency_s": 12.0, "output_tokens": 20, "n_k": 20}, {"ttft_s": 20.0, "latency_s": 28.0, "output_tokens": 40, "n_k": 40}, {"ttft_s": 30.0, "latency_s": 36.0, "output_tokens": 60, "n_k": n3}] def test_ttft_sum_is_sum_of_per_turn_ttft(self): self.assertAlmostEqual(R.aggregates(self.turns(), 100.0)["ttft_sum"], 60.0) def test_decode_tps_is_total_tokens_over_total_decode_time(self): a = R.aggregates(self.turns(), 100.0) self.assertAlmostEqual(a["decode_time_s"], 16.0) self.assertAlmostEqual(a["decode_tps"], 120 / 16.0) # 7.5, not the 8.33 of the mean of rates self.assertNotAlmostEqual(a["decode_tps"], (10 + 5 + 10) / 3.0) def test_wall_norm_equals_wall_when_all_lengths_match(self): a = R.aggregates(self.turns(), 100.0) self.assertEqual(a["wall"], 100.0) self.assertAlmostEqual(a["wall_norm"], 100.0) def test_wall_norm_rescales_decode_time_when_lengths_differ(self): # N_total = 20 + 40 + 90 = 150, output total 120: 100 - 16 + 150 * 16 / 120 = 104 a = R.aggregates(self.turns(n3=90), 100.0) self.assertAlmostEqual(a["wall_norm"], 104.0) self.assertEqual(a["wall"], 100.0) def test_turn_without_output_counts_whole_latency_as_ttft_and_no_decode(self): t = self.turns() + [{"ttft_s": None, "latency_s": 5.0, "output_tokens": 0, "n_k": 0}] a = R.aggregates(t, 110.0) self.assertAlmostEqual(a["ttft_sum"], 65.0) self.assertAlmostEqual(a["decode_time_s"], 16.0) def test_no_output_at_all_gives_null_rate_and_wall_norm_equals_wall(self): a = R.aggregates([{"ttft_s": None, "latency_s": 3.0, "output_tokens": 0, "n_k": 4}], 3.0) self.assertIsNone(a["decode_tps"]) self.assertEqual(a["wall_norm"], 3.0) class TestRecordH0(Base): def test_h0_file_format(self): h = self.h0_data self.assertEqual(h["context_tokens"], 262144) self.assertEqual(h["target_tokens"], 900) self.assertEqual(len(h["turns"]), TURNS) for k, t in enumerate(h["turns"], 1): for key in ("reply_sha256", "reply_token_ids", "prompt_tokens", "cached_tokens", "output_tokens"): self.assertIn(key, t) self.assertEqual(t["output_tokens"], n_for_turn(k)) self.assertEqual(t["reply_sha256"], hashlib.sha256(t["reply_text"].encode()).hexdigest()) def test_recording_requests_are_explicit_greedy(self): self.assertEqual(len(self.rec.log), TURNS) for raw in self.rec.log: self.assertIn('"temperature": 0', raw) self.assertEqual(json.loads(raw)["max_output_tokens"], 300) class TestReplay(Base): def test_prompts_identical_across_two_engines_with_different_replies(self): ea, eb = FakeEngine(reply_a), FakeEngine(reply_b) try: rca, a, _, _ = self.replay(ea, "a.json") rcb, b, _, _ = self.replay(eb, "b.json") finally: ea.close() eb.close() self.assertEqual((rca, rcb), (0, 0)) pa = [t["prompt_sha256"] for t in a["turns"]] pb = [t["prompt_sha256"] for t in b["turns"]] self.assertEqual(len(pa), TURNS) self.assertEqual(pa, pb) # the empty diff of the acceptance command self.assertEqual(pa, [t["prompt_sha256"] for t in self.h0_data["turns"]]) # and equal to the recorded prompts self.assertNotEqual([t["reply_sha256"] for t in a["turns"]], [t["reply_sha256"] for t in b["turns"]]) # the replies really differ self.assertEqual(a["reply_diverges_from_h0_turns"], list(range(1, TURNS + 1))) def test_requests_carry_greedy_and_forced_length_and_never_the_engines_own_reply(self): eb = FakeEngine(reply_b) try: rc, data, _, _ = self.replay(eb, "b2.json") log = list(eb.log) finally: eb.close() self.assertEqual(rc, 0) greedy = [r for r in log if re.search(r'"temperature": 0\b|"greedy"', r)] self.assertGreaterEqual(len(greedy), 5) for k, raw in enumerate(log, 1): body = json.loads(raw) self.assertEqual(body["max_output_tokens"], n_for_turn(k)) # N_k of the H0 turn self.assertEqual(body["temperature"], 0) self.assertNotIn("ENGINE-B-ANSWER", raw) # the arm's own reply is never fed back if k > 1: self.assertIn("recorded answer %d " % (k - 1), raw) # the H0 reply of turn k-1 is def test_matching_lengths_give_no_flag_and_wall_norm_equals_wall(self): ea = FakeEngine(reply_a) try: rc, data, _, _ = self.replay(ea, "a3.json") finally: ea.close() self.assertEqual(rc, 0) self.assertEqual([t["length_unmatched"] for t in data["turns"]], [False] * TURNS) self.assertAlmostEqual(data["wall_norm"], data["wall"], places=9) for key in ("ttft_sum", "decode_tps", "wall", "wall_norm"): self.assertIn(key, data) self.assertAlmostEqual(data["ttft_sum"], sum(t["ttft_s"] for t in data["turns"]), places=9) def test_shorter_and_longer_reply_is_flagged_not_failed(self): def odd(turn, n_req): if turn == 2: return "short", n_req - 3 if turn == 4: return "long " * 20, n_req + 5 return "same %d" % turn, n_req e = FakeEngine(odd) try: rc, data, _, _ = self.replay(e, "odd.json") finally: e.close() self.assertEqual(rc, 0) self.assertEqual([t["length_unmatched"] for t in data["turns"]], [False, True, False, True, False]) self.assertEqual(data["length_unmatched_turns"], [2, 4]) self.assertEqual(data["status"], "ok") self.assertEqual(data["output_tokens_total"], data["n_total"] + 2) # -3 + 5 def test_forged_prompt_sha_exits_3_naming_the_turn_and_sends_nothing(self): e = FakeEngine(reply_a) try: good = [t["prompt_sha256"] for t in self.h0_data["turns"]] forged = list(good) forged[2] = "0" * 64 rc, data, so, se = self.replay(e, "forged.json", "--expect-prompt-sha", ",".join(forged)) sent = len(e.log) finally: e.close() self.assertEqual(rc, 3) self.assertIn("turn 3", se) self.assertNotIn("turn 1:", se) self.assertEqual(sent, 0) self.assertEqual(data["status"], "prompt_hash_mismatch") def test_correct_expected_prompt_sha_passes(self): e = FakeEngine(reply_a) try: good = ",".join(t["prompt_sha256"] for t in self.h0_data["turns"]) rc, data, _, _ = self.replay(e, "good.json", "--expect-prompt-sha", good) finally: e.close() self.assertEqual(rc, 0) def test_different_source_than_recorded_exits_3(self): other = os.path.join(self.tmp.name, "other_src") os.makedirs(other) for i in range(8): with open(os.path.join(other, "m%d.rs" % i), "w") as f: f.write("// different %d\n" % i * 300) e = FakeEngine(reply_a) try: out = os.path.join(self.tmp.name, "other.json") rc, _, se = run_cli("replay", "--h0", self.h0, "--base-url", e.url, "--out", out, "--src", other) sent = len(e.log) finally: e.close() self.assertEqual(rc, 3) self.assertIn("turn 1", se) self.assertEqual(sent, 0) def test_api_key_is_sent_but_never_written(self): e = FakeEngine(reply_a) keyfile = os.path.join(self.tmp.name, "key.txt") with open(keyfile, "w") as f: f.write(SECRET_KEY + "\n") try: rc, data, _, _ = self.replay(e, "keyed.json", "--key-file", keyfile) auth = list(e.auth) finally: e.close() self.assertEqual(rc, 0) self.assertEqual(set(auth), {"Bearer " + SECRET_KEY}) with open(os.path.join(self.tmp.name, "keyed.json")) as f: self.assertNotIn(SECRET_KEY, f.read()) def test_unreachable_engine_exits_1_with_a_record(self): rc, data, _, se = self.replay(type("Dead", (), {"url": "http://127.0.0.1:9"})(), "dead.json") self.assertEqual(rc, 1) self.assertEqual(data["status"], "failed") def test_mismatching_turns_flag_is_a_usage_error(self): e = FakeEngine(reply_a) try: rc, _, _, _ = self.replay(e, "bad.json", "--turns", "4") finally: e.close() self.assertEqual(rc, 2) class TestSource(unittest.TestCase): def test_no_wall_clock_in_the_driver(self): with open(SCRIPT, encoding="utf-8") as f: src = f.read() self.assertIsNone(re.search(r"time\.time", src)) # acceptance 5: grep -n "time\.time" is empty self.assertIn("time.monotonic", src) def test_python_39_syntax_only(self): with open(SCRIPT, encoding="utf-8") as f: src = f.read() compile(src, SCRIPT, "exec", flags=0, dont_inherit=True) self.assertIsNone(re.search(r"^\s*match\s+\w+:\s*$", src, re.M)) # no structural pattern matching (3.10) if __name__ == "__main__": unittest.main()