#!/usr/bin/env python3 """(Copy of the codex-compare replay tool with one addition: `out_sha` = sha256 over the model's output deltas of each request, the identity record of the speed program.) Replay the requests a logging proxy forwarded (`proxy/rounds/NNNN.fwd.json.gz` of a codex-compare cell) to a running stack, in order, one at a time (test tooling, stdlib only). replay_fwd.py --cell DIR [--cell DIR ...] --url http://127.0.0.1:8081 --model qwen-iq3 --key-file FILE --out result.jsonl [--max-requests N] The prompts are the ones a vanilla (or any) arm answered in a real Codex session, so every stack under test reads the same 10-120k-token histories. The reply of the stack is NOT fed back (the next recorded request carries the recorded reply), so the work per request is the same for every configuration and the prefix cache sees the same text. Each request is sent as recorded with `model` replaced and temperature 0; the stream is read to its end. One JSON line per request: seq, input/output tokens, wall seconds, time to the first event, status. Speed per request comes from the engine's own log (the caller cuts it at the recorded offsets): this script only drives. """ import argparse import gzip import hashlib import json import os import sys import time import urllib.error import urllib.request def main(): ap = argparse.ArgumentParser() ap.add_argument("--cell", action="append", required=True) ap.add_argument("--url", required=True) ap.add_argument("--model", required=True) ap.add_argument("--key-file", default="") ap.add_argument("--out", required=True) ap.add_argument("--max-requests", type=int, default=0) ap.add_argument("--timeout", type=int, default=900) ap.add_argument("--tune", default="", help='JSON object sent as strata_tune (per-request engine settings), e.g. {"pcie_frac":0.35}') a = ap.parse_args() key = open(a.key_file).read().strip() if a.key_file else "" out = open(a.out, "a", encoding="utf-8") for cell in a.cell: rounds = os.path.join(cell, "proxy", "rounds") names = sorted(n for n in os.listdir(rounds) if n.endswith(".fwd.json.gz")) if a.max_requests: names = names[: a.max_requests] for n in names: body = json.loads(gzip.open(os.path.join(rounds, n)).read()) body["model"] = a.model body["temperature"] = 0.0 if a.tune: body["strata_tune"] = json.loads(a.tune) # the recorded history of a vanilla session carries the vanilla's opaque reasoning blob ("strata.r1:..."), which Leleka refuses (HTTP 400); its own sessions keep None there for it in body.get("input") or []: if isinstance(it, dict) and it.get("type") == "reasoning" and it.get("encrypted_content"): it["encrypted_content"] = None sid = body.get("prompt_cache_key") or "" hdr = {"Content-Type": "application/json", "Accept": "text/event-stream", "session-id": sid, "thread-id": sid, "x-codex-window-id": sid + ":0"} if key: hdr["Authorization"] = "Bearer " + key data = json.dumps(body).encode() t0 = time.time() rec = {"cell": os.path.basename(cell.rstrip("/")), "seq": n.split(".")[0], "req_bytes": len(data)} try: req = urllib.request.Request(a.url.rstrip("/") + "/v1/responses", data=data, headers=hdr, method="POST") with urllib.request.urlopen(req, timeout=a.timeout) as r: rec["status"] = r.status first = None last = b"" h = hashlib.sha256() nd = 0 for line in r: if first is None: first = time.time() - t0 if line.startswith(b"data:") and b".delta" in line: try: d = json.loads(line[5:]).get("delta") except ValueError: d = None if isinstance(d, str): h.update(d.encode("utf-8", "replace")) h.update(b"|") nd += 1 if line.startswith(b"data:") and b"response.completed" in line: last = line rec["t_first_s"] = round(first or 0, 3) rec["out_sha"] = h.hexdigest() rec["n_delta"] = nd if last: u = json.loads(last[5:]).get("response", {}).get("usage", {}) rec["input_tokens"] = u.get("input_tokens") rec["output_tokens"] = u.get("output_tokens") rec["cached_tokens"] = (u.get("input_tokens_details") or {}).get("cached_tokens") except urllib.error.HTTPError as e: rec["error"] = "HTTP %d %s" % (e.code, e.read()[:300].decode("utf-8", "replace")) except Exception as e: # recorded, the replay goes on rec["error"] = repr(e)[:200] rec["wall_s"] = round(time.time() - t0, 3) out.write(json.dumps(rec) + "\n") out.flush() print(json.dumps(rec), flush=True) return 0 if __name__ == "__main__": sys.exit(main())