Merge claude/stra-308 into train-a (STRA-245)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-28 22:14:32 +01:00
co-authored by Claude Sonnet 5.5
2 changed files with 230 additions and 19 deletions
+79 -14
View File
@@ -16,8 +16,22 @@ work. This driver fixes that:
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 or I/O failure; 2 bad arguments or a damaged H0 file; 3 prompt hash mismatch (the message names the turn; the pair is
invalid, E2(3)). A turn whose output_tokens differs from N_k is flagged length_unmatched; it is not a failure.
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.
"""
@@ -35,7 +49,8 @@ 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 = 0, 1, 2, 3
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.
@@ -98,7 +113,7 @@ def stream(base, key, model, items, max_out):
t_first = None
deltas = 0
text, ids = [], []
usage, status = {}, None
usage, status, terminal, reason, detail = {}, None, None, None, None
try:
with urllib.request.urlopen(req, timeout=3600) as r:
for raw in r:
@@ -120,9 +135,13 @@ def stream(base, key, model, items, max_out):
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", {})
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:
@@ -130,7 +149,29 @@ def stream(base, key, model, items, max_out):
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, "status": status}
"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 ----------------------------------------------------------------------------------------------------------------------------------
@@ -192,6 +233,10 @@ def cmd_record(a):
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,
@@ -293,21 +338,41 @@ def cmd_replay(a):
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"]
row = {"turn": k + 1, "prompt_sha256": prompt_hashes[k], "reply_sha256": sha256_text(res["reply"]), "prompt_tokens": res["prompt_tokens"],
"cached_tokens": res["cached_tokens"], "output_tokens": out_tok, "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,
"reply_matches_h0": sha256_text(res["reply"]) == t["reply_sha256"], "status": res["status"]}
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
agg = aggregates(rows, wall) if rows else {}
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": "failed" if failed else "ok", "error": failed, "started_utc": started, "finished_utc": utc_now(), "turns": rows,
"length_unmatched_turns": [r["turn"] for r in rows if r["length_unmatched"]],
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)
return EXIT_FAIL if failed else EXIT_OK
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):
+151 -5
View File
@@ -27,8 +27,12 @@ def n_for_turn(k):
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):
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
@@ -53,7 +57,22 @@ class FakeEngine:
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())
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]
@@ -228,12 +247,12 @@ class TestReplay(Base):
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 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 "long " * 20, n_req + 5
return "short again", n_req - 1
return "same %d" % turn, n_req
e = FakeEngine(odd)
try:
@@ -244,7 +263,134 @@ class TestReplay(Base):
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
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)