Files
leleka/scripts/e2e/codex/delta/logproxy.py
T

307 lines
14 KiB
Python

#!/usr/bin/env python3
"""Logging reverse proxy between the Codex CLI and a Responses endpoint (test tooling, stdlib only, Python 3.9+).
logproxy.py --listen 127.0.0.1:PORT --upstream http://127.0.0.1:8081 --out DIR
[--temperature 0] [--model-map LOCAL=UPSTREAM] [--max-rounds N]
The same proxy sits in front of vanilla Strata and of our stack, so every request and response is captured identically:
DIR/rounds.jsonl one line per HTTP request: seq, path, status, timings (ms since proxy start), sizes, sha256 of the body Codex sent
and of the body forwarded, the sampling fields forwarded, the usage and the output item summary of the response
DIR/rounds/NNNN.req.json.gz the request body exactly as Codex sent it (gzip)
DIR/rounds/NNNN.fwd.json.gz only when the proxy changed the body (temperature injection, model name mapping): the body forwarded
DIR/rounds/NNNN.resp.sse.gz the response body exactly as received from the engine (SSE stream or JSON), gzip
DIR/cap.reached created when more than --max-rounds POST .../responses requests arrived (later ones get a 503, nothing reaches the engine)
Round = a POST whose path ends in /responses (a model request). Authorization is forwarded and never logged.
The injected `temperature` makes the sampling identical for every variant (Codex sends none; vanilla Strata would otherwise use the model card's
sampling, our server greedy).
"""
import argparse
import gzip
import hashlib
import http.client
import json
import os
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit
HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers", "transfer-encoding", "upgrade", "host", "content-length"}
SECRET_HEADERS = {"authorization", "x-api-key", "cookie", "proxy-authorization"}
class State:
def __init__(self, args):
self.args = args
u = urlsplit(args.upstream)
self.up_host, self.up_port = u.hostname, u.port or 80
self.out = args.out
os.makedirs(os.path.join(self.out, "rounds"), exist_ok=True)
self.log = open(os.path.join(self.out, "rounds.jsonl"), "a", encoding="utf-8", buffering=1)
self.lock = threading.Lock()
self.seq = 0
self.rounds = 0
self.t0 = time.time()
self.model_map = dict(m.split("=", 1) for m in args.model_map)
def ms(self):
return int((time.time() - self.t0) * 1000)
def next_seq(self, is_round):
with self.lock:
self.seq += 1
if is_round:
self.rounds += 1
return self.seq, self.rounds
def write(self, rec):
with self.lock:
self.log.write(json.dumps(rec, separators=(",", ":"), ensure_ascii=False) + "\n")
def gz_write(path, data):
tmp = path + ".part"
with open(tmp, "wb") as f:
f.write(gzip.compress(data, 6, mtime=0))
os.replace(tmp, path)
def summarize_sse(body):
"""Usage, status and a short summary of the output items from an SSE body or a JSON body."""
out = {"events": 0}
text = body.decode("utf-8", errors="replace")
final = None
items = []
if text.lstrip().startswith("{"):
try:
final = json.loads(text)
except ValueError:
final = None
else:
ev = None
for line in text.splitlines():
if line.startswith("event:"):
ev = line[6:].strip()
elif line.startswith("data:"):
out["events"] += 1
try:
d = json.loads(line[5:].strip())
except ValueError:
continue
t = d.get("type") or ev
if t in ("response.completed", "response.incomplete", "response.failed"):
final = d.get("response") or d
out["terminal"] = t
elif t == "response.output_item.done":
items.append(d.get("item") or {})
elif t == "error":
out["error"] = d
if final:
out["status"] = final.get("status")
u = final.get("usage") or {}
out["input_tokens"] = u.get("input_tokens")
out["output_tokens"] = u.get("output_tokens")
out["cached_tokens"] = (u.get("input_tokens_details") or {}).get("cached_tokens")
out["reasoning_tokens"] = (u.get("output_tokens_details") or {}).get("reasoning_tokens")
if final.get("error"):
out["error"] = final["error"]
if final.get("incomplete_details"):
out["incomplete"] = final["incomplete_details"]
if not items:
items = final.get("output") or []
summ = []
for it in items:
k = {"type": it.get("type")}
if it.get("type") == "function_call":
k["name"] = it.get("name")
k["arg_bytes"] = len(it.get("arguments") or "")
elif it.get("type") == "message":
k["text_bytes"] = sum(len(c.get("text") or "") for c in it.get("content") or [] if isinstance(c, dict))
summ.append(k)
out["items"] = summ
return out
def summarize_req(body, headers):
out = {"content_encoding": headers.get("content-encoding"), "content_type": headers.get("content-type")}
if headers.get("content-encoding"):
return out
try:
d = json.loads(body)
except ValueError:
out["not_json"] = True
return out
if not isinstance(d, dict):
return out
inp = d.get("input")
out.update({"model": d.get("model"), "stream": d.get("stream"), "n_input_items": len(inp) if isinstance(inp, list) else None,
"n_tools": len(d.get("tools") or []), "previous_response_id": d.get("previous_response_id"),
"temperature": d.get("temperature"), "top_p": d.get("top_p"), "max_output_tokens": d.get("max_output_tokens"),
"reasoning": d.get("reasoning"), "tool_choice": d.get("tool_choice"), "parallel_tool_calls": d.get("parallel_tool_calls"),
"store": d.get("store"), "keys": sorted(d.keys())})
if isinstance(inp, list):
last = inp[-1] if inp else {}
out["last_item_type"] = last.get("type") or last.get("role") if isinstance(last, dict) else None
return out
def make_handler(st):
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server_version = "logproxy/1"
def log_message(self, *a):
pass
def _body(self):
if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower():
data = b""
while True:
size = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16)
if size == 0:
self.rfile.readline()
break
data += self.rfile.read(size)
self.rfile.readline()
return data
n = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(n) if n else b""
def _handle(self):
t_start = st.ms()
body = self._body()
path = self.path
is_round = self.command == "POST" and urlsplit(path).path.endswith("/responses")
seq, rounds = st.next_seq(is_round)
sname = "%04d" % seq
rec = {"seq": seq, "method": self.command, "path": path, "round": rounds if is_round else None, "t_start_ms": t_start,
"req_bytes": len(body), "req_sha256": hashlib.sha256(body).hexdigest(),
"req": summarize_req(body, {k.lower(): v for k, v in self.headers.items()}),
"req_headers": {k: v for k, v in self.headers.items() if k.lower() not in SECRET_HEADERS}}
if body:
gz_write(os.path.join(st.out, "rounds", sname + ".req.json.gz"), body)
if is_round and st.args.max_rounds and rounds > st.args.max_rounds:
open(os.path.join(st.out, "cap.reached"), "w").write("round %d > cap %d\n" % (rounds, st.args.max_rounds))
msg = json.dumps({"error": {"message": "round cap reached", "type": "server_error", "code": "round_cap"}}).encode()
self.send_response(503)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(msg)))
self.end_headers()
self.wfile.write(msg)
rec.update({"status": 503, "outcome": "cap", "t_end_ms": st.ms()})
st.write(rec)
return
fwd = body
if is_round and not self.headers.get("Content-Encoding"):
try:
d = json.loads(body)
except ValueError:
d = None
if isinstance(d, dict):
changed = False
if st.args.temperature is not None and "temperature" not in d:
d["temperature"] = st.args.temperature
changed = True
if d.get("model") in st.model_map:
d["model"] = st.model_map[d["model"]]
changed = True
if changed:
fwd = json.dumps(d, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
gz_write(os.path.join(st.out, "rounds", sname + ".fwd.json.gz"), fwd)
rec["fwd_sha256"] = hashlib.sha256(fwd).hexdigest()
rec["fwd_sampling"] = {"temperature": d.get("temperature"), "model": d.get("model")}
elif is_round:
rec["fwd_note"] = "body has a Content-Encoding; forwarded unchanged (no temperature injected)"
headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP}
headers["Host"] = "%s:%d" % (st.up_host, st.up_port)
headers["Content-Length"] = str(len(fwd))
resp_buf = bytearray()
t_first = None
outcome = "ok"
conn = http.client.HTTPConnection(st.up_host, st.up_port, timeout=None)
try:
conn.request(self.command, path, body=fwd if (fwd or self.command in ("POST", "PUT")) else None, headers=headers)
resp = conn.getresponse()
rec["status"] = resp.status
rh = {k: v for k, v in resp.getheaders()}
rec["resp_headers"] = {k: v for k, v in rh.items() if k.lower() not in SECRET_HEADERS}
self.send_response(resp.status)
streaming = "text/event-stream" in (rh.get("Content-Type") or rh.get("content-type") or "").lower() or resp.getheader("Content-Length") is None
for k, v in resp.getheaders():
if k.lower() in HOP or k.lower() in ("date", "server"):
continue
self.send_header(k, v)
if streaming:
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
while True:
chunk = resp.read1(65536) if streaming else resp.read(65536)
if not chunk:
break
if t_first is None:
t_first = st.ms()
resp_buf += chunk
if streaming:
self.wfile.write(b"%x\r\n" % len(chunk) + chunk + b"\r\n")
else:
self.wfile.write(chunk)
self.wfile.flush()
if streaming:
self.wfile.write(b"0\r\n\r\n")
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
outcome = "client_disconnected"
except Exception as e: # upstream failure
outcome = "proxy_error: %s: %s" % (type(e).__name__, e)
if "status" not in rec:
msg = json.dumps({"error": {"message": outcome, "type": "server_error"}}).encode()
try:
self.send_response(502)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(msg)))
self.end_headers()
self.wfile.write(msg)
except OSError:
pass
rec["status"] = 502
finally:
conn.close()
rec.update({"t_first_byte_ms": t_first, "t_end_ms": st.ms(), "resp_bytes": len(resp_buf), "outcome": outcome})
if resp_buf:
gz_write(os.path.join(st.out, "rounds", sname + ".resp.sse.gz"), bytes(resp_buf))
rec["resp"] = summarize_sse(bytes(resp_buf))
st.write(rec)
if outcome != "ok":
self.close_connection = True
do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = do_OPTIONS = _handle
return H
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--listen", required=True)
ap.add_argument("--upstream", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--temperature", type=float, default=None)
ap.add_argument("--model-map", action="append", default=[])
ap.add_argument("--max-rounds", type=int, default=0)
args = ap.parse_args()
st = State(args)
host, port = args.listen.rsplit(":", 1)
srv = ThreadingHTTPServer((host, int(port)), make_handler(st))
srv.daemon_threads = True
print("logproxy listening on %s -> %s, out %s" % (args.listen, args.upstream, args.out), flush=True)
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()