"""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, ending=None, usage_edit=None): """ending(turn) -> "completed" (default) | "cut" (stream ends with no terminal event) | "failed" | "incomplete_max" | "incomplete_other" | "incomplete_noreason". usage_edit(turn, usage) may change the usage object (e.g. drop input_tokens).""" self.reply = reply self.ending = ending or (lambda turn: "completed") self.usage_edit = usage_edit 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()) if engine.usage_edit: engine.usage_edit(turn, usage) end = engine.ending(turn) if end == "cut": return # the connection closes after the deltas: no terminal event resp = {"status": "completed", "usage": usage} ty = "response.completed" if end == "failed": ty, resp = "response.failed", {"status": "failed", "usage": usage, "error": {"code": "server_error", "message": "engine fell over"}} elif end.startswith("incomplete"): ty, resp = "response.incomplete", {"status": "incomplete", "usage": usage} if end == "incomplete_max": resp["incomplete_details"] = {"reason": "max_output_tokens"} elif end == "incomplete_other": resp["incomplete_details"] = {"reason": "content_filter"} self.wfile.write(("data: " + json.dumps({"type": ty, "response": resp}) + "\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_reply_is_flagged_not_failed(self): def odd(turn, n_req): if turn == 2: return "short", n_req - 3 if turn == 4: return "short again", n_req - 1 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.assertTrue(data["arm_valid"]) self.assertEqual(data["bound_exceeded_turns"], []) self.assertEqual(data["output_tokens_total"], data["n_total"] - 4) # -3 - 1 def test_output_above_the_forced_bound_marks_the_arm_invalid(self): # E7(b): output_tokens > N_k is not LENGTH-UNMATCHED, the configuration is invalid def over(turn, n_req): return ("long " * 20, n_req + 5) if turn == 4 else ("same %d" % turn, n_req) e = FakeEngine(over) try: rc, data, _, se = self.replay(e, "over.json") finally: e.close() self.assertEqual(rc, 4) self.assertIn("OUTPUT_BOUND_EXCEEDED turn 4", se) self.assertEqual(data["status"], "arm_invalid") self.assertIs(data["arm_valid"], False) self.assertEqual(data["bound_exceeded_turns"], [4]) self.assertEqual([t["bound_exceeded"] for t in data["turns"]], [False, False, False, True, False]) self.assertEqual(len(data["invalid_reasons"]), 1) self.assertIn("output_tokens %d > N_k %d" % (n_for_turn(4) + 5, n_for_turn(4)), data["invalid_reasons"][0]) self.assertEqual(len(data["turns"]), TURNS) # the run is complete and recorded; only the arm is invalid def test_server_reported_token_counts_are_recorded_per_turn(self): # E7(a)/E2(3) minimal evidence e = FakeEngine(reply_a) try: rc, data, _, _ = self.replay(e, "tok.json") finally: e.close() self.assertEqual(rc, 0) for t, h in zip(data["turns"], self.h0_data["turns"]): self.assertEqual(t["prompt_tokens"], h["prompt_tokens"]) self.assertEqual(t["h0_prompt_tokens"], h["prompt_tokens"]) self.assertIs(t["prompt_tokens_match_h0"], True) self.assertIsInstance(t["cached_tokens"], int) self.assertEqual(t["output_tokens"], t["n_k"]) self.assertEqual(t["output_tokens_source"], "usage") self.assertEqual(data["prompt_tokens_differ_from_h0_turns"], []) def test_prompt_tokens_that_differ_from_h0_are_listed(self): # the engine tokenises the same text differently: the evaluator must see it def skew(turn, usage): if turn in (2, 5): usage["input_tokens"] += 7 e = FakeEngine(reply_a, usage_edit=skew) try: rc, data, _, _ = self.replay(e, "skew.json") finally: e.close() self.assertEqual(rc, 0) # equality across arms is judged by the evaluator; the driver records the facts self.assertEqual(data["prompt_tokens_differ_from_h0_turns"], [2, 5]) self.assertEqual([t["prompt_tokens_match_h0"] for t in data["turns"]], [True, False, True, True, False]) self.assertEqual([t["prompt_sha256"] for t in data["turns"]], [t["prompt_sha256"] for t in self.h0_data["turns"]]) # same text, other token count def test_stream_cut_off_is_a_failed_turn_with_nonzero_exit(self): # D308-1 e = FakeEngine(reply_a, ending=lambda turn: "cut" if turn == 3 else "completed") try: rc, data, _, se = self.replay(e, "cut.json") sent = len(e.log) finally: e.close() self.assertEqual(rc, 1) self.assertIn("turn 3", se) self.assertIn("without response.completed", se) self.assertEqual(data["status"], "failed") self.assertIn("turn 3", data["error"]) self.assertIn("output-integrity", data["error"]) self.assertIs(data["arm_valid"], False) self.assertEqual(sent, 3) # nothing is sent after the failed turn self.assertEqual([t["turn"] for t in data["turns"]], [1, 2, 3]) self.assertIsNotNone(data["turns"][2]["integrity_failure"]) self.assertIsNone(data["turns"][0]["integrity_failure"]) self.assertEqual(data["output_tokens_total"], n_for_turn(1) + n_for_turn(2)) # the failed turn never enters the aggregates def test_response_failed_is_a_failed_turn_with_the_server_message(self): # D308-1 e = FakeEngine(reply_a, ending=lambda turn: "failed" if turn == 1 else "completed") try: rc, data, _, se = self.replay(e, "failed.json") finally: e.close() self.assertEqual(rc, 1) self.assertEqual(data["status"], "failed") self.assertIn("response.failed", data["error"]) self.assertIn("engine fell over", data["error"]) self.assertEqual(data["turns"][0]["terminal_event"], "response.failed") self.assertEqual(len(data["turns"]), 1) def test_incomplete_by_the_output_bound_is_accepted_other_incomplete_is_not(self): # D308-1 boundary e = FakeEngine(reply_a, ending=lambda turn: "incomplete_max") try: rc, data, _, _ = self.replay(e, "inc_max.json") finally: e.close() self.assertEqual((rc, data["status"]), (0, "ok")) self.assertEqual({t["terminal_event"] for t in data["turns"]}, {"response.incomplete"}) e = FakeEngine(reply_a, ending=lambda turn: "incomplete_noreason") # no reason, output_tokens == N_k: stopped by the bound try: rc, data, _, _ = self.replay(e, "inc_none.json") finally: e.close() self.assertEqual((rc, data["status"]), (0, "ok")) e = FakeEngine(reply_a, ending=lambda turn: "incomplete_other" if turn == 2 else "completed") try: rc, data, _, se = self.replay(e, "inc_other.json") finally: e.close() self.assertEqual((rc, data["status"]), (1, "failed")) self.assertIn("content_filter", se) def test_missing_usage_input_tokens_is_a_failed_turn(self): # E2(3) cannot be checked without the server-reported prompt_tokens e = FakeEngine(reply_a, usage_edit=lambda turn, usage: usage.pop("input_tokens") if turn == 2 else None) try: rc, data, _, se = self.replay(e, "nousage.json") finally: e.close() self.assertEqual(rc, 1) self.assertIn("usage.input_tokens", se) self.assertEqual(data["status"], "failed") def test_record_h0_refuses_a_failed_stream(self): e = FakeEngine(reply_recording, ending=lambda turn: "cut" if turn == 2 else "completed") try: out = os.path.join(self.tmp.name, "h0_cut.json") rc, _, se = run_cli("record-h0", "--base-url", e.url, "--out", out, "--src", self.src, "--turns", str(TURNS), "--target-tokens", "900", "--context", "262144", "--max-output", "300", "--model", "fake") finally: e.close() self.assertEqual(rc, 1) self.assertIn("turn 2", se) self.assertFalse(os.path.exists(out)) # no H0 from a damaged recording 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()