Files
leleka/scripts/e2e/replay_session.py
Pavlo RatushnyiandClaude Sonnet 5.5 7b7e56d389 fix(e2e): replay driver fails a cut-off or failed stream, records token evidence, flags exceeded bound (STRA-308 rework)
D308-1: a turn whose stream ends without a terminal event, with response.failed, with a
non-bound response.incomplete, or without usage.input_tokens is recorded as a failed turn
(integrity_failure reason), later turns are not sent, run status "failed", exit 1.
record-h0 refuses such a stream (no H0 written).
E2(3)/E7 (BA decision 9dcb717a): per turn the server-reported prompt_tokens, the H0
prompt_tokens, their equality, cached/output tokens and output_tokens_source are recorded;
the run lists prompt_tokens_differ_from_h0_turns.
E7(b): output_tokens > N_k marks the arm invalid (bound_exceeded_turns, arm_valid false,
invalid_reasons OUTPUT_BOUND_EXCEEDED, status arm_invalid, exit 4); shorter stays
LENGTH-UNMATCHED. Tests: 28 (8 new, 1 replaced).

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

401 lines
23 KiB
Python

#!/usr/bin/env python3
"""Replay driver for the long (256k-class) session: identical work for every arm, run and machine (rule E7 of STRA-245; STRA-308).
Offline test tooling, stdlib only, Python >= 3.9. It does not launch an engine and is never part of serving.
long_session.py feeds each reply into the next prompt and sends no sampling field, so two arms (or two runs of one arm) do not execute the same
work. This driver fixes that:
record-h0 runs the session live ONCE (explicit greedy) and writes the history H0 to a file outside Git: per turn the reply text, its sha256,
its token ids (when the engine exposes them), the user-message hash, the prompt hash and the token counts, plus context_tokens and
target_tokens of the session.
replay builds the prompt of turn k from the session's user messages and the H0 replies of turns 1..k-1 (never from the arm's own reply),
so prompts are identical across arms, runs and machines; every request carries explicit greedy sampling ("temperature": 0) and
max_output_tokens = N_k (the H0 reply length of turn k). It records per turn the prompt sha256, the reply sha256, prompt/cached/output
tokens, TTFT and latency, and the aggregates defined once in aggregates().
replay_session.py record-h0 --base-url URL --out H0.json [--src DIR --target-tokens N --context N --max-output N --turns N --model M --key-file F]
replay_session.py replay --h0 H0.json --base-url URL --out RUN.json [--expect-prompt-sha SHA[,SHA...]] [--src DIR --model M --key-file F ...]
Exit codes: 0 ok; 1 request, I/O or output-integrity failure; 2 bad arguments or a damaged H0 file; 3 prompt hash mismatch (the message names the
turn; the pair is invalid, E2(3)); 4 the arm did not honour the forced length bound (output_tokens > N_k, E7(b): the arm configuration is invalid).
A turn whose output_tokens is BELOW N_k is flagged length_unmatched; it is not a failure.
Output integrity (E2(5), E7(d); STRA-308 rework D308-1): a turn counts only when its stream ends with response.completed, or with
response.incomplete caused by the output bound (incomplete_details.reason max_output_tokens / max_tokens, or no reason with output_tokens >= N_k),
and reports usage.input_tokens. A stream that ends without a terminal event (cut off), ends with response.failed, ends with another
response.incomplete, or reports no usage.input_tokens is an output-integrity failure of that arm: the turn is recorded (status, integrity_failure
reason), later turns are not sent, the run JSON has status "failed" and an error naming the turn and the reason, and the exit code is 1. It is
never recorded as an ok run.
Token evidence for the E2(3) / E7 identity rule (BA decision 9dcb717a: equal prompt text counts only with equal server-reported prompt_tokens): every
turn records the server-reported prompt_tokens, cached_tokens and output_tokens (output_tokens_source says "usage" or, when the server sent no
usage.output_tokens, "deltas"), the H0 prompt_tokens of the turn and whether they are equal; the run JSON lists the turns whose prompt_tokens differ
from H0 (prompt_tokens_differ_from_h0_turns). Equality ACROSS arms is judged by the evaluator from the records of the pair, not here. An output_tokens
above N_k marks the arm invalid (bound_exceeded_turns, arm_valid false, invalid_reasons OUTPUT_BOUND_EXCEEDED, status "arm_invalid", exit 4).
Clock: time.monotonic only (a wall clock can step during a 1,300 s arm). Same client program for every arm. The API key comes from --key-file
or E2E_API_KEY and is never written to any output. The H0 file and the run files hold prompts' hashes and reply text: keep them outside Git.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
import sys
import time
import urllib.error
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import long_session as ls # noqa: E402 (collect, take and QUESTIONS are reused; its stream() is not: it has no sampling field and a wall clock)
H0_VERSION = 1
EXIT_OK, EXIT_FAIL, EXIT_USAGE, EXIT_HASH, EXIT_INVALID_ARM = 0, 1, 2, 3, 4
BOUND_REASONS = ("max_output_tokens", "max_tokens") # incomplete_details.reason values that mean "stopped by the output bound"
GREEDY = {"temperature": 0} # Responses field: ours takes the greedy path at 0; vanilla Strata honours the GEN key temperature (digest 3.2) and gets
# the model card's sampling when none is sent (digest 1.3, a8091f4d), so it is always sent.
def sha256_text(text):
return hashlib.sha256(text.encode("utf8")).hexdigest()
def prompt_sha256(items):
"""Hash of the exact conversation the engine is asked to continue (canonical JSON of the input items)."""
return sha256_text(json.dumps(items, sort_keys=True, separators=(",", ":"), ensure_ascii=False))
def user_item(chunk, turn_index):
return {"role": "user", "content": [{"type": "input_text", "text": chunk + "\n\n" + ls.QUESTIONS[turn_index % len(ls.QUESTIONS)]}]}
def assistant_item(reply):
return {"role": "assistant", "content": [{"type": "output_text", "text": reply}]}
# ---- aggregates, defined ONCE (rule E7(d)) ---------------------------------------------------------------------------------------------------
def decode_time(turn):
"""decode_time_k = latency_k - TTFT_k. A turn that produced no output (ttft_s null) has no decode time and its TTFT is its whole latency."""
if turn.get("ttft_s") is None:
return 0.0
return turn["latency_s"] - turn["ttft_s"]
def aggregates(turns, wall):
"""turns: dicts with ttft_s, latency_s, output_tokens, n_k (the H0 length of the turn). wall: first request sent to last response completed.
ttft_sum = sum of per-turn TTFT.
decode_tps = total output tokens / total decode time (NOT a mean of per-turn rates).
wall_norm = wall - decode_time + N_total x decode_time / output_tokens_total (equal to wall when every length matches)."""
ttft_sum = sum(t["latency_s"] if t.get("ttft_s") is None else t["ttft_s"] for t in turns)
dec = sum(decode_time(t) for t in turns)
out_total = sum(t["output_tokens"] for t in turns)
n_total = sum(t["n_k"] for t in turns)
decode_tps = out_total / dec if dec > 0 else None
if out_total > 0:
wall_norm = wall - dec + n_total * dec / out_total
else:
wall_norm = wall
return {"ttft_sum": ttft_sum, "decode_time_s": dec, "output_tokens_total": out_total, "n_total": n_total, "decode_tps": decode_tps,
"wall": wall, "wall_norm": wall_norm}
# ---- the request ------------------------------------------------------------------------------------------------------------------------------
def stream(base, key, model, items, max_out):
"""One streamed /v1/responses request with explicit greedy sampling and max_output_tokens = max_out. All times are time.monotonic values."""
body = {"model": model, "input": items, "max_output_tokens": max_out, "stream": True}
body.update(GREEDY)
headers = {"Content-Type": "application/json"}
if key:
headers["Authorization"] = "Bearer " + key
req = urllib.request.Request(base.rstrip("/") + "/v1/responses", json.dumps(body).encode(), headers)
t_send = time.monotonic()
t_first = None
deltas = 0
text, ids = [], []
usage, status, terminal, reason, detail = {}, None, None, None, 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") or ty.endswith("reasoning_text.delta"):
if t_first is None:
t_first = time.monotonic()
deltas += 1
if ty.endswith("output_text.delta"):
text.append(d.get("delta", ""))
for k in ("token_ids", "output_token_ids"): # only when the engine exposes them; the plain Responses stream does not
if isinstance(d.get(k), list):
ids.extend(x for x in d[k] if isinstance(x, int))
elif ty in ("response.completed", "response.incomplete", "response.failed"):
resp = d.get("response") or {}
usage = resp.get("usage") or {}
status = resp.get("status")
terminal = ty
reason = (resp.get("incomplete_details") or {}).get("reason")
err = resp.get("error")
detail = (err.get("message") or err.get("code") or json.dumps(err)) if isinstance(err, dict) else err
except urllib.error.HTTPError as e:
return {"error": "HTTP %d" % e.code, "body": e.read()[:300].decode("utf8", "replace"), "t_send": t_send, "t_end": time.monotonic()}
except (urllib.error.URLError, OSError, ValueError) as e:
return {"error": "%s: %s" % (type(e).__name__, e), "t_send": t_send, "t_end": time.monotonic()}
t_end = time.monotonic()
return {"t_send": t_send, "t_first": t_first, "t_end": t_end, "reply": "".join(text), "token_ids": ids or None, "deltas": deltas,
"prompt_tokens": usage.get("input_tokens"), "cached_tokens": (usage.get("input_tokens_details") or {}).get("cached_tokens"),
"output_tokens": usage.get("output_tokens") if usage.get("output_tokens") is not None else deltas,
"output_tokens_source": "usage" if usage.get("output_tokens") is not None else "deltas", "status": status, "terminal": terminal,
"incomplete_reason": reason, "error_detail": detail}
def integrity_failure(res, n_k=None):
"""None when the turn ended properly, else the reason (E2(5), E7(d)). n_k: the forced bound of the turn (None while recording H0)."""
terminal = res.get("terminal")
if terminal is None:
return "the stream ended without response.completed (cut off or no terminal event)"
if terminal == "response.failed" or res.get("status") == "failed":
detail = res.get("error_detail")
return "response.failed" + (": %s" % detail if detail else "")
if terminal == "response.incomplete" or res.get("status") == "incomplete":
reason = res.get("incomplete_reason")
no_reason_ok = reason is None and (n_k is None or (res.get("output_tokens") or 0) >= n_k)
if reason not in BOUND_REASONS and not no_reason_ok:
return "response.incomplete (reason %s)" % reason
elif res.get("status") not in ("completed", None):
return "response status %r" % res.get("status")
if res.get("prompt_tokens") is None:
return "no usage.input_tokens reported (E2(3) needs the server-reported prompt_tokens)"
return None
# ---- common ----------------------------------------------------------------------------------------------------------------------------------
def read_key(path):
if path:
with open(path, encoding="utf-8") as f:
return f.readline().strip()
return os.environ.get("E2E_API_KEY", "")
def write_json(path, obj):
d = os.path.dirname(os.path.abspath(path))
os.makedirs(d, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(obj, f, indent=1)
f.write("\n")
def utc_now():
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def common_args(ap):
ap.add_argument("--base-url", default=os.environ.get("E2E_BASE_URL"))
ap.add_argument("--out", required=True)
ap.add_argument("--src", default=os.path.expanduser("~/work/leleka-head/src/crates"), help="directory of .rs files the user messages are cut from")
ap.add_argument("--model", default=os.environ.get("E2E_MODEL", ""))
ap.add_argument("--key-file", default=None, help="first line = API key (else E2E_API_KEY); never written to an output")
def h0_id(turns):
return sha256_text(json.dumps([[t["user_sha256"], t["reply_sha256"], t["output_tokens"]] for t in turns], separators=(",", ":")))
# ---- record-h0 -------------------------------------------------------------------------------------------------------------------------------
def cmd_record(a):
if not a.base_url:
print("record-h0: --base-url (or E2E_BASE_URL) is required", file=sys.stderr)
return EXIT_USAGE
files = ls.collect(a.src)
if not files:
print("record-h0: no .rs files above 1500 bytes under --src", file=sys.stderr)
return EXIT_USAGE
key = read_key(a.key_file)
items, turns, pos = [], [], 0
chars_per_token = 3.3 # same sizing rule as long_session.py; the chosen chunk size is stored so replay never re-derives it from an engine's token counts
per_turn = a.target_tokens // a.turns
used_tokens = 0
for k in range(a.turns):
room = int((a.context - a.max_output - 8 - used_tokens - 400) * 0.96)
want = per_turn if k < a.turns - 1 else min(max(a.target_tokens - used_tokens, per_turn), room)
chunk_chars = int(min(want, room) * chars_per_token)
chunk, pos = ls.take(files, pos, chunk_chars)
user = user_item(chunk, k)
items.append(user)
res = stream(a.base_url, key, a.model, items, a.max_output)
if "error" in res:
print("record-h0: turn %d failed: %s" % (k + 1, res["error"]), file=sys.stderr)
return EXIT_FAIL
why = integrity_failure(res)
if why:
print("record-h0: turn %d output-integrity failure: %s" % (k + 1, why), file=sys.stderr)
return EXIT_FAIL
reply = res["reply"]
turns.append({"turn": k + 1, "chunk_chars": chunk_chars, "user_sha256": sha256_text(json.dumps(user, sort_keys=True, separators=(",", ":"), ensure_ascii=False)),
"prompt_sha256": prompt_sha256(items), "reply_sha256": sha256_text(reply), "reply_text": reply,
"reply_token_ids": res["token_ids"], "prompt_tokens": res["prompt_tokens"], "cached_tokens": res["cached_tokens"],
"output_tokens": res["output_tokens"]})
print(json.dumps({k2: v for k2, v in turns[-1].items() if k2 not in ("reply_text", "reply_token_ids")}), flush=True)
if res["prompt_tokens"]:
used_tokens = res["prompt_tokens"] + (res["output_tokens"] or 0)
chars_per_token = sum(len(i["content"][0]["text"]) for i in items) / res["prompt_tokens"]
items.append(assistant_item(reply))
h0 = {"h0_version": H0_VERSION, "h0_id": h0_id(turns), "recorded_utc": utc_now(), "context_tokens": a.context, "target_tokens": a.target_tokens,
"max_output": a.max_output, "model": a.model, "sampling": GREEDY, "turns": turns}
write_json(a.out, h0)
return EXIT_OK
# ---- replay ----------------------------------------------------------------------------------------------------------------------------------
def load_h0(path):
with open(path, encoding="utf-8") as f:
h0 = json.load(f)
need = ("turn", "chunk_chars", "user_sha256", "reply_sha256", "reply_text", "output_tokens", "prompt_tokens", "cached_tokens")
if h0.get("h0_version") != H0_VERSION or not isinstance(h0.get("turns"), list) or not h0["turns"]:
raise ValueError("not an H0 v%d file" % H0_VERSION)
for t in h0["turns"]:
miss = [k for k in need if k not in t]
if miss:
raise ValueError("H0 turn %s lacks %s" % (t.get("turn"), ",".join(miss)))
if sha256_text(t["reply_text"]) != t["reply_sha256"]:
raise ValueError("H0 turn %d: reply_text does not match reply_sha256" % t["turn"])
return h0
def build_replay_prompts(files, h0):
"""Prompt k = user messages 1..k and the H0 replies 1..k-1. Returns (prompts, user_sha256 per turn)."""
items, prompts, user_hashes, pos = [], [], [], 0
for k, t in enumerate(h0["turns"]):
chunk, pos = ls.take(files, pos, t["chunk_chars"])
user = user_item(chunk, k)
user_hashes.append(sha256_text(json.dumps(user, sort_keys=True, separators=(",", ":"), ensure_ascii=False)))
items.append(user)
prompts.append(list(items))
items.append(assistant_item(t["reply_text"]))
return prompts, user_hashes
def cmd_replay(a):
if not a.base_url:
print("replay: --base-url (or E2E_BASE_URL) is required", file=sys.stderr)
return EXIT_USAGE
try:
h0 = load_h0(a.h0)
except (OSError, ValueError) as e:
print("replay: bad H0 file: %s" % e, file=sys.stderr)
return EXIT_USAGE
for flag, got, want in (("--turns", a.turns, len(h0["turns"])), ("--target-tokens", a.target_tokens, h0.get("target_tokens")),
("--context", a.context, h0.get("context_tokens"))):
if got is not None and got != want:
print("replay: %s %s differs from the H0 file (%s); the session would not be the recorded one" % (flag, got, want), file=sys.stderr)
return EXIT_USAGE
files = ls.collect(a.src)
if not files:
print("replay: no .rs files above 1500 bytes under --src", file=sys.stderr)
return EXIT_USAGE
prompts, user_hashes = build_replay_prompts(files, h0)
prompt_hashes = [prompt_sha256(p) for p in prompts]
expect = [s.strip().lower() for s in a.expect_prompt_sha.split(",") if s.strip()] if a.expect_prompt_sha else []
if len(expect) > len(prompts):
print("replay: --expect-prompt-sha lists %d hashes for %d turns" % (len(expect), len(prompts)), file=sys.stderr)
return EXIT_USAGE
bad = []
for k, t in enumerate(h0["turns"]):
if user_hashes[k] != t["user_sha256"]:
bad.append("turn %d: user message differs from the H0 recording (--src is not the recorded source)" % (k + 1))
for k, want in enumerate(expect):
if prompt_hashes[k] != want:
bad.append("turn %d: prompt sha256 %s != expected %s" % (k + 1, prompt_hashes[k], want))
base_out = {"mode": "replay", "h0_id": h0.get("h0_id"), "context_tokens": h0.get("context_tokens"), "target_tokens": h0.get("target_tokens"),
"model": a.model, "sampling": GREEDY}
if bad:
for m in bad:
print("PROMPT HASH MISMATCH " + m, file=sys.stderr)
base_out.update({"status": "prompt_hash_mismatch", "mismatches": bad, "turns": [{"turn": k + 1, "prompt_sha256": h} for k, h in enumerate(prompt_hashes)]})
write_json(a.out, base_out)
return EXIT_HASH
key = read_key(a.key_file)
rows, t_first_send, t_last_end, failed = [], None, None, None
started = utc_now()
for k, t in enumerate(h0["turns"]):
n_k = t["output_tokens"]
res = stream(a.base_url, key, a.model, prompts[k], n_k)
if t_first_send is None:
t_first_send = res["t_send"]
t_last_end = res["t_end"]
if "error" in res:
failed = "turn %d: %s" % (k + 1, res["error"])
print("replay: " + failed, file=sys.stderr)
break
ttft = res["t_first"] - res["t_send"] if res["t_first"] is not None else None
latency = res["t_end"] - res["t_send"]
out_tok = res["output_tokens"]
why = integrity_failure(res, n_k)
h0_pt = t.get("prompt_tokens")
pt = res["prompt_tokens"]
row = {"turn": k + 1, "prompt_sha256": prompt_hashes[k], "reply_sha256": sha256_text(res["reply"]), "prompt_tokens": pt,
"h0_prompt_tokens": h0_pt, "prompt_tokens_match_h0": (pt == h0_pt) if pt is not None and h0_pt is not None else None,
"cached_tokens": res["cached_tokens"], "output_tokens": out_tok, "output_tokens_source": res["output_tokens_source"], "n_k": n_k,
"ttft_s": ttft, "latency_s": latency, "decode_time_s": decode_time({"ttft_s": ttft, "latency_s": latency}), "length_unmatched": out_tok != n_k,
"bound_exceeded": out_tok > n_k, "reply_matches_h0": sha256_text(res["reply"]) == t["reply_sha256"], "status": res["status"],
"terminal_event": res["terminal"], "integrity_failure": why}
rows.append(row)
print(json.dumps(row), flush=True)
if why:
failed = "turn %d: output-integrity failure: %s" % (k + 1, why)
print("replay: " + failed, file=sys.stderr)
break
wall = (t_last_end - t_first_send) if t_first_send is not None else 0.0
good = [r for r in rows if not r["integrity_failure"]] # a failed turn is recorded but never enters the aggregates
agg = aggregates(good, wall) if good else {}
exceeded = [r["turn"] for r in good if r["bound_exceeded"]]
invalid_reasons = ["OUTPUT_BOUND_EXCEEDED turn %d: output_tokens %d > N_k %d" % (r["turn"], r["output_tokens"], r["n_k"]) for r in good if r["bound_exceeded"]]
status = "failed" if failed else ("arm_invalid" if exceeded else "ok")
out = dict(base_out)
out.update({"status": status, "error": failed, "started_utc": started, "finished_utc": utc_now(), "turns": rows,
"length_unmatched_turns": [r["turn"] for r in good if r["length_unmatched"]],
"bound_exceeded_turns": exceeded, "arm_valid": not exceeded and not failed, "invalid_reasons": invalid_reasons,
"prompt_tokens_differ_from_h0_turns": [r["turn"] for r in rows if r["prompt_tokens_match_h0"] is False],
"reply_diverges_from_h0_turns": [r["turn"] for r in rows if not r["reply_matches_h0"]]})
out.update(agg)
write_json(a.out, out)
if failed:
return EXIT_FAIL
if exceeded:
print("replay: arm invalid: " + "; ".join(invalid_reasons), file=sys.stderr)
return EXIT_INVALID_ARM
return EXIT_OK
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="mode", required=True)
rec = sub.add_parser("record-h0", help="run the session live with explicit greedy and write H0")
common_args(rec)
rec.add_argument("--turns", type=int, default=5)
rec.add_argument("--target-tokens", type=int, default=245000)
rec.add_argument("--max-output", type=int, default=300)
rec.add_argument("--context", type=int, default=262144)
rep = sub.add_parser("replay", help="replay H0 against an engine")
common_args(rep)
rep.add_argument("--h0", required=True)
rep.add_argument("--expect-prompt-sha", default=None, help="comma separated sha256 per turn; a mismatch exits 3 naming the turn")
rep.add_argument("--turns", type=int, default=None, help="must equal the H0 file (default: from H0)")
rep.add_argument("--target-tokens", type=int, default=None, help="must equal the H0 file (default: from H0)")
rep.add_argument("--context", type=int, default=None, help="must equal the H0 file (default: from H0)")
rep.add_argument("--max-output", type=int, default=None, help="accepted for CLI symmetry; the per-turn limit is N_k from H0")
a = ap.parse_args(argv)
return cmd_record(a) if a.mode == "record-h0" else cmd_replay(a)
if __name__ == "__main__":
sys.exit(main())