Files
leleka/scripts/e2e/test_prefix_tail_equivalence.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 7788651476 STRA-328: paired reply-tail equivalence check (plan, tool, tests) and consistent prefix-cache doc
No default changes. scripts/e2e/prefix_tail_equivalence.py scores the `reply` prefix-cache tail live: record an agent session against the reply
arm (history built from its own output, so it resumes from its own reply checkpoint), replay the exact request bodies on a cold server
(--prefix-cache-mib 0), and judge greedy identity of every output item, tool-call integrity of each arm (declared name, call_id, JSON arguments
against the tool schema, streamed deltas == done == item, response.completed), restore evidence (cached_tokens) and, with --control, cold-vs-cold
determinism. Verdicts PASS / FAIL_* / INCONCLUSIVE_*. Two sequential phases because one 5090 cannot hold two serve instances.
Tested on in-process fake servers (15 tests); it has NOT been run against the engine. The plan (scripts/e2e/prefix_tail_equivalence_plan.md)
also records the open numeric-gate decision (q_tail_gate needs teacher-forced captures).

docs/prefix-cache.md: the stale "EXPERIMENTAL: off by default" lines now agree with the measured paragraph, and both say that the
rtx5090-32g profile sets the tail while the live equivalence gate is open.

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

206 lines
10 KiB
Python

"""Tests of prefix_tail_equivalence.py (STRA-328): the verdict logic on in-process fake servers. No engine, no GPU, no network beyond 127.0.0.1.
Run: python -m unittest test_prefix_tail_equivalence -v (from scripts/e2e)
"""
import argparse
import hashlib
import http.server
import json
import os
import sys
import tempfile
import threading
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import prefix_tail_equivalence as PT # noqa: E402
class Arm(http.server.BaseHTTPRequestHandler):
"""A fake /v1/responses server. cfg: arm ('reply'|'cold') and mode (see the tests); state in server.calls."""
def log_message(self, *a):
pass
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
srv = self.server
srv.calls += 1
items_in = body["input"]
digest = hashlib.sha256(json.dumps(items_in, sort_keys=True).encode()).hexdigest()[:8]
last = items_in[-1]
out = []
text = None
if last.get("type") == "function_call_output":
text = "done %d" % len(items_in)
elif "Use the" not in json.dumps(last):
text = "answer %s" % digest
if text is not None:
if srv.mode == "diverge" and srv.arm == "reply" and len(items_in) >= 6:
text += " (decode-state drift)"
if srv.mode == "nondet" and srv.arm == "cold":
text += " #%d" % srv.calls
out.append({"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": text}]})
else:
args = '{"command": ["ls", "-la"]}'
if srv.mode == "bad_args" and srv.arm == "reply":
args = '{"command": ["ls", "-la"'
if srv.mode == "bad_tool" and srv.arm == "reply":
out_name = "rm_rf"
else:
out_name = "shell"
out.append({"type": "function_call", "call_id": "call_" + digest, "name": out_name, "arguments": args})
n_in = 100 * len(items_in)
cached = 0
if srv.arm == "reply" and srv.mode != "no_cache" and len(items_in) > 2:
cached = n_in - 50
if srv.arm == "cold" and srv.mode == "warm_cold" and len(items_in) > 2:
cached = n_in - 50
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
for k, it in enumerate(out):
if it["type"] == "function_call":
a = it["arguments"]
for part in (a[:5], a[5:]):
self.wfile.write(("data: " + json.dumps({"type": "response.function_call_arguments.delta", "output_index": k, "delta": part}) + "\n\n").encode())
self.wfile.write(("data: " + json.dumps({"type": "response.function_call_arguments.done", "output_index": k, "arguments": a}) + "\n\n").encode())
self.wfile.write(("data: " + json.dumps({"type": "response.output_item.done", "output_index": k, "item": it}) + "\n\n").encode())
done = {"type": "response.completed", "response": {"status": "completed", "usage": {"input_tokens": n_in, "output_tokens": 7,
"input_tokens_details": {"cached_tokens": cached}}}}
if srv.mode == "cut" and srv.arm == "reply":
done = None # the stream just ends
if done:
self.wfile.write(("data: " + json.dumps(done) + "\n\n").encode())
def start(arm, mode):
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Arm)
srv.arm, srv.mode, srv.calls = arm, mode, 0
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
class Session(unittest.TestCase):
def run_pair(self, reply_mode="ok", cold_mode="ok", control=False, turns=4):
reply, cold = start("reply", reply_mode), start("cold", cold_mode)
for srv in (reply, cold):
self.addCleanup(srv.server_close)
self.addCleanup(srv.shutdown)
args = argparse.Namespace(cold_url="http://127.0.0.1:%d" % cold.server_address[1], reply_url="http://127.0.0.1:%d" % reply.server_address[1],
model="m", key_file=None, scenario=None, context_file=None, instructions=None, turns=turns, max_output=64,
control=control, min_cached_fraction=0.5, min_restore_fraction=0.8)
return PT.run_session(args)
def test_identical_arms_with_restores_pass(self):
res = self.run_pair(control=True)
self.assertEqual(res["verdict"], "PASS", res["reasons"])
self.assertGreaterEqual(res["requests"], 5, "tool rounds are requests too")
self.assertEqual(res["restored"], res["restore_candidates"])
self.assertTrue(any(p["integrity"]["reply"] == [] for p in res["pairs"]))
def test_a_drifting_reply_arm_fails_with_the_first_difference(self):
res = self.run_pair("diverge")
self.assertEqual(res["verdict"], "FAIL_OUTPUT_DIFFERS")
self.assertIn("char", res["reasons"][0])
def test_malformed_tool_arguments_on_the_reply_arm_fail_integrity(self):
res = self.run_pair("bad_args")
self.assertEqual(res["verdict"], "FAIL_TOOL_CALL_INTEGRITY")
self.assertIn("reply arm", res["reasons"][0])
self.assertIn("JSON", res["reasons"][0])
def test_an_undeclared_tool_name_fails_integrity(self):
res = self.run_pair("bad_tool")
self.assertEqual(res["verdict"], "FAIL_TOOL_CALL_INTEGRITY")
self.assertIn("undeclared tool", res["reasons"][0])
def test_a_cut_off_stream_fails_integrity(self):
res = self.run_pair("cut")
self.assertEqual(res["verdict"], "FAIL_TOOL_CALL_INTEGRITY")
self.assertIn("response.completed", res["reasons"][0])
def test_no_restore_means_no_evidence(self):
res = self.run_pair("no_cache")
self.assertEqual(res["verdict"], "INCONCLUSIVE_NO_RESTORE")
def test_a_warm_cold_arm_is_not_a_cold_arm(self):
res = self.run_pair(cold_mode="warm_cold")
self.assertEqual(res["verdict"], "INCONCLUSIVE_COLD_ARM_WARM")
def test_nondeterministic_cold_runs_are_inconclusive(self):
res = self.run_pair(cold_mode="nondet", control=True)
self.assertEqual(res["verdict"], "INCONCLUSIVE_NONDETERMINISTIC")
def test_transport_error_is_an_error(self):
args = argparse.Namespace(cold_url="http://127.0.0.1:9", reply_url="http://127.0.0.1:9", model="m", key_file=None, scenario=None,
context_file=None, instructions=None, turns=1, max_output=8, control=False, min_cached_fraction=0.5,
min_restore_fraction=0.8)
self.assertEqual(PT.run_session(args)["verdict"], "ERROR")
def test_cli_exit_codes_and_no_key_in_the_output(self):
reply, cold = start("reply", "diverge"), start("cold", "ok")
for srv in (reply, cold):
self.addCleanup(srv.server_close)
self.addCleanup(srv.shutdown)
with tempfile.TemporaryDirectory() as tmp:
keyf = os.path.join(tmp, "key")
with open(keyf, "w") as fh:
fh.write("sk-secret-test-key")
out = os.path.join(tmp, "res.json")
rc = PT.main(["run", "--cold-url", "http://127.0.0.1:%d" % cold.server_address[1], "--reply-url", "http://127.0.0.1:%d" % reply.server_address[1],
"--model", "m", "--key-file", keyf, "--out", out, "--turns", "4"])
self.assertEqual(rc, 1)
with open(out, "r", encoding="utf-8") as fh:
text = fh.read()
self.assertNotIn("sk-secret-test-key", text)
self.assertEqual(json.loads(text)["verdict"], "FAIL_OUTPUT_DIFFERS")
def test_two_phases_record_then_replay_on_a_restarted_server(self):
"""The production workflow: the reply arm is recorded, stopped, and the recorded bodies are replayed on a cold server."""
for reply_mode, want_rc, want in (("ok", 0, "PASS"), ("diverge", 1, "FAIL_OUTPUT_DIFFERS"), ("bad_args", 1, "FAIL_TOOL_CALL_INTEGRITY")):
reply = start("reply", reply_mode)
with tempfile.TemporaryDirectory() as tmp:
rec = os.path.join(tmp, "record.json")
rc = PT.main(["record", "--reply-url", "http://127.0.0.1:%d" % reply.server_address[1], "--model", "m", "--turns", "4", "--record-out", rec])
reply.shutdown()
reply.server_close()
self.assertEqual(rc, 0, reply_mode)
cold = start("cold", "ok") # a new process on another port, without the cache
out = os.path.join(tmp, "res.json")
rc = PT.main(["replay", "--cold-url", "http://127.0.0.1:%d" % cold.server_address[1], "--record", rec, "--control", "--out", out])
cold.shutdown()
cold.server_close()
self.assertEqual((rc, json.load(open(out, "r", encoding="utf-8"))["verdict"]), (want_rc, want), reply_mode)
def test_usage_error_exits_3(self):
with self.assertRaises(SystemExit) as cm:
PT.main(["run", "--model", "m"])
self.assertEqual(cm.exception.code, 3)
class Pure(unittest.TestCase):
def test_schema_errors(self):
schema = {"type": "object", "properties": {"command": {"type": "array", "items": {"type": "string"}}, "timeout_ms": {"type": "integer"}},
"required": ["command"], "additionalProperties": False}
self.assertEqual(PT.schema_errors(schema, {"command": ["ls"]}), [])
self.assertTrue(PT.schema_errors(schema, {}))
self.assertTrue(PT.schema_errors(schema, {"command": [1]}))
self.assertTrue(PT.schema_errors(schema, {"command": ["a"], "extra": 1}))
self.assertTrue(PT.schema_errors(schema, {"command": ["a"], "timeout_ms": True}))
def test_first_difference_names_item_and_char(self):
a = [{"type": "message", "text": "abcdef"}]
b = [{"type": "message", "text": "abcxef"}]
self.assertEqual(PT.first_difference(a, b), {"item": 0, "what": "text", "char": 3})
self.assertIsNone(PT.first_difference(a, a))
self.assertEqual(PT.first_difference(a, a + a)["what"], "item count")
def test_judge_empty_is_error(self):
self.assertEqual(PT.judge([])["verdict"], "ERROR")
if __name__ == "__main__":
unittest.main()