1202 lines
64 KiB
Python
1202 lines
64 KiB
Python
#!/usr/bin/env python3
|
|
"""End-to-end client for `strata-next` in front of `leleka-inference` (offline TEST DRIVER, not shipped).
|
|
|
|
Sends Codex-shaped Responses requests and checks the wire behaviour. Standard library only.
|
|
The API key is read from --key-file and is never printed or written to the results.
|
|
|
|
e2e_client.py --base http://127.0.0.1:8081 --key-file KEY --model qwen-iq3 --out results.json \
|
|
[--scenarios endpoints,simple,tools,...|all] [--context-dir DIR] [--pids inference=1,strata=2] [--soak-n 40]
|
|
|
|
Exit status 0 when every check passed, 1 otherwise. results.json holds every check, measurement and a /metrics snapshot.
|
|
"""
|
|
import argparse
|
|
import glob
|
|
import http.client
|
|
import json
|
|
import os
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
import traceback
|
|
import urllib.parse
|
|
|
|
# ---------------------------------------------------------------------------------------------------------------------
|
|
# transport
|
|
|
|
class Client:
|
|
def __init__(self, base, key, timeout=900.0):
|
|
u = urllib.parse.urlparse(base)
|
|
self.host, self.port = u.hostname, u.port
|
|
self.key, self.timeout = key, timeout
|
|
|
|
def conn(self, timeout=None):
|
|
return http.client.HTTPConnection(self.host, self.port, timeout=timeout or self.timeout)
|
|
|
|
def headers(self, extra=None, auth=True):
|
|
h = {"content-type": "application/json", "accept": "application/json"}
|
|
if auth and self.key:
|
|
h["authorization"] = "Bearer " + self.key
|
|
if extra:
|
|
h.update(extra)
|
|
return h
|
|
|
|
def call(self, method, path, body=None, auth=True, headers=None, timeout=None, raw=None):
|
|
c = self.conn(timeout)
|
|
t0 = time.monotonic()
|
|
try:
|
|
data = raw if raw is not None else (None if body is None else json.dumps(body))
|
|
c.request(method, path, body=data, headers=self.headers(headers, auth))
|
|
r = c.getresponse()
|
|
payload = r.read()
|
|
dt = time.monotonic() - t0
|
|
try:
|
|
parsed = json.loads(payload) if payload else None
|
|
except ValueError:
|
|
parsed = None
|
|
return Reply(r.status, dict(r.getheaders()), payload, parsed, dt)
|
|
finally:
|
|
c.close()
|
|
|
|
def stream(self, path, body, stop=None, timeout=None, headers=None):
|
|
"""POST and read an SSE stream. `stop(event_list)` returning True closes the socket early (cancel)."""
|
|
c = self.conn(timeout)
|
|
t0 = time.monotonic()
|
|
res = Stream(t0)
|
|
try:
|
|
c.request("POST", path, body=json.dumps(body), headers=self.headers({"accept": "text/event-stream", **(headers or {})}))
|
|
r = c.getresponse()
|
|
res.status = r.status
|
|
res.headers = dict(r.getheaders())
|
|
res.t_headers = time.monotonic() - t0
|
|
if r.status != 200 or "text/event-stream" not in res.headers.get("Content-Type", res.headers.get("content-type", "")):
|
|
res.error_body = r.read()
|
|
try:
|
|
res.error = json.loads(res.error_body)
|
|
except ValueError:
|
|
pass
|
|
return res
|
|
event, data = None, []
|
|
while True:
|
|
line = r.readline()
|
|
if not line:
|
|
break
|
|
now = time.monotonic() - t0
|
|
if res.t_first_byte is None:
|
|
res.t_first_byte = now
|
|
line = line.decode("utf-8", "replace").rstrip("\r\n")
|
|
if line.startswith(":"):
|
|
res.comments.append((now, line))
|
|
continue
|
|
if line == "":
|
|
if data:
|
|
raw = "\n".join(data)
|
|
res.add(now, event, raw)
|
|
if stop and stop(res):
|
|
res.aborted = True
|
|
break
|
|
event, data = None, []
|
|
continue
|
|
if line.startswith("event:"):
|
|
event = line[6:].strip()
|
|
elif line.startswith("data:"):
|
|
data.append(line[5:].lstrip(" "))
|
|
res.t_end = time.monotonic() - t0
|
|
except (socket.timeout, ConnectionError, http.client.HTTPException, OSError) as e:
|
|
res.transport_error = repr(e)
|
|
res.t_end = time.monotonic() - t0
|
|
finally:
|
|
try:
|
|
# closing the socket mid-stream is the cancel signal for the server
|
|
if c.sock is not None:
|
|
c.sock.shutdown(socket.SHUT_RDWR)
|
|
except OSError:
|
|
pass
|
|
c.close()
|
|
return res
|
|
|
|
|
|
class Reply:
|
|
def __init__(self, status, headers, payload, parsed, dt):
|
|
self.status, self.headers, self.payload, self.json, self.dt = status, headers, payload, parsed, dt
|
|
|
|
def err(self):
|
|
e = (self.json or {}).get("error") if isinstance(self.json, dict) else None
|
|
return e if isinstance(e, dict) else {}
|
|
|
|
|
|
class Stream:
|
|
def __init__(self, t0):
|
|
self.t0 = t0
|
|
self.status = None
|
|
self.headers = {}
|
|
self.t_headers = None
|
|
self.t_first_byte = None
|
|
self.t_end = None
|
|
self.events = [] # (t, name, parsed_or_raw)
|
|
self.comments = []
|
|
self.aborted = False
|
|
self.transport_error = None
|
|
self.error = None
|
|
self.error_body = b""
|
|
self.done_marker = False
|
|
self.bad_json = []
|
|
|
|
def add(self, t, name, raw):
|
|
if raw.strip() == "[DONE]":
|
|
self.done_marker = True
|
|
return
|
|
try:
|
|
d = json.loads(raw)
|
|
except ValueError:
|
|
self.bad_json.append(raw[:200])
|
|
d = raw
|
|
self.events.append((t, name, d))
|
|
|
|
def types(self):
|
|
return [e[2].get("type") if isinstance(e[2], dict) else None for e in self.events]
|
|
|
|
def first(self, typ):
|
|
for t, _, d in self.events:
|
|
if isinstance(d, dict) and d.get("type") == typ:
|
|
return t
|
|
return None
|
|
|
|
def count(self, typ):
|
|
return sum(1 for _, _, d in self.events if isinstance(d, dict) and d.get("type") == typ)
|
|
|
|
def terminal(self):
|
|
for t, _, d in reversed(self.events):
|
|
if isinstance(d, dict) and d.get("type") in ("response.completed", "response.incomplete", "response.failed"):
|
|
return d
|
|
return None
|
|
|
|
def response(self):
|
|
t = self.terminal()
|
|
return (t or {}).get("response") or {}
|
|
|
|
def text(self):
|
|
return "".join(d.get("delta", "") for _, _, d in self.events if isinstance(d, dict) and d.get("type") == "response.output_text.delta")
|
|
|
|
def delta_times(self):
|
|
return [t for t, _, d in self.events if isinstance(d, dict) and d.get("type") == "response.output_text.delta"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------------------------------
|
|
# result bookkeeping
|
|
|
|
class Scenario:
|
|
def __init__(self, name):
|
|
self.name, self.checks, self.metrics, self.notes = name, [], {}, []
|
|
self.t0 = time.time()
|
|
self.error = None
|
|
|
|
def check(self, name, ok, detail=""):
|
|
self.checks.append({"name": name, "ok": bool(ok), "detail": str(detail)[:600]})
|
|
print((" PASS " if ok else " FAIL ") + name + ((" :: " + str(detail)[:300]) if (detail and not ok) else ""), flush=True)
|
|
return bool(ok)
|
|
|
|
def metric(self, key, value):
|
|
self.metrics[key] = value
|
|
print(f" metric {key} = {value}", flush=True)
|
|
|
|
def note(self, text):
|
|
self.notes.append(text)
|
|
print(" note: " + text, flush=True)
|
|
|
|
def ok(self):
|
|
return self.error is None and all(c["ok"] for c in self.checks)
|
|
|
|
def as_dict(self):
|
|
return {"name": self.name, "ok": self.ok(), "seconds": round(time.time() - self.t0, 2), "error": self.error,
|
|
"checks": self.checks, "metrics": self.metrics, "notes": self.notes}
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------------------------------
|
|
# Codex-shaped requests
|
|
|
|
INSTRUCTIONS = (
|
|
"You are a coding agent running in the Codex CLI, a terminal-based coding assistant. You are expected to be precise, safe, and helpful.\n"
|
|
"Your capabilities: receive user prompts and other context provided by the harness, such as files in the workspace; communicate with the user by "
|
|
"streaming thinking and responses, and by making and updating plans; emit function calls to run terminal commands and apply patches.\n"
|
|
"When the task needs a command, call the `shell` tool with the command as an array of strings. Keep answers concise."
|
|
)
|
|
DEVELOPER = (
|
|
"<permissions instructions>\nFilesystem sandboxing defines which files can be read or written. `sandbox_mode` is `workspace-write`: "
|
|
"The sandbox permits reading files, and editing files in `cwd` and `writable_roots`. Network access is restricted.\n"
|
|
"Approval policy is currently never. Do not provide the `sandbox_permissions` for any reason, commands will be rejected.\n</permissions instructions>"
|
|
)
|
|
ENV_CONTEXT = (
|
|
"<environment_context>\n <cwd>/workspace/leleka</cwd>\n <approval_policy>never</approval_policy>\n <sandbox_mode>workspace-write</sandbox_mode>\n"
|
|
" <network_access>restricted</network_access>\n <shell>bash</shell>\n</environment_context>"
|
|
)
|
|
|
|
|
|
def msg(role, text):
|
|
kind = "output_text" if role == "assistant" else "input_text"
|
|
return {"type": "message", "role": role, "content": [{"type": kind, "text": text}]}
|
|
|
|
|
|
TOOLS = [
|
|
{"type": "function", "name": "shell", "strict": False,
|
|
"description": "Runs a shell command and returns its output.",
|
|
"parameters": {"type": "object", "properties": {
|
|
"command": {"type": "array", "items": {"type": "string"}, "description": "The command to execute"},
|
|
"workdir": {"type": "string", "description": "The working directory to execute the command in"},
|
|
"timeout_ms": {"type": "integer", "description": "The timeout for the command in milliseconds"}},
|
|
"required": ["command"], "additionalProperties": False}},
|
|
{"type": "function", "name": "read_file", "strict": False,
|
|
"description": "Reads a text file from the workspace and returns its contents.",
|
|
"parameters": {"type": "object", "properties": {
|
|
"path": {"type": "string", "description": "Path of the file relative to the workspace root"},
|
|
"start_line": {"type": "integer"}, "end_line": {"type": "integer"}},
|
|
"required": ["path"], "additionalProperties": False}},
|
|
{"type": "function", "name": "update_plan", "strict": False,
|
|
"description": "Updates the task plan. Provide an optional explanation and a list of plan items, each with a step and status.",
|
|
"parameters": {"type": "object", "properties": {
|
|
"explanation": {"type": "string"},
|
|
"plan": {"type": "array", "items": {"type": "object", "properties": {
|
|
"step": {"type": "string"},
|
|
"status": {"type": "string", "enum": ["pending", "in_progress", "completed"]}},
|
|
"required": ["step", "status"], "additionalProperties": False}}},
|
|
"required": ["plan"], "additionalProperties": False}},
|
|
{"type": "function", "name": "apply_patch", "strict": False,
|
|
"description": "Edits files by applying a patch. The input is the patch text in the apply_patch format.",
|
|
"parameters": {"type": "object", "properties": {"input": {"type": "string", "description": "The entire contents of the apply_patch command"}},
|
|
"required": ["input"], "additionalProperties": False}},
|
|
]
|
|
|
|
|
|
def codex_body(model, user_text, tools=True, effort="none", stream=True, store=False, max_out=None, extra_input=None, **kw):
|
|
body = {
|
|
"model": model,
|
|
"instructions": INSTRUCTIONS,
|
|
"input": [msg("developer", DEVELOPER), msg("user", ENV_CONTEXT)] + (extra_input or []) + ([msg("user", user_text)] if user_text else []),
|
|
"tool_choice": "auto",
|
|
"parallel_tool_calls": False,
|
|
"reasoning": {"effort": effort} if effort == "none" else {"effort": effort, "summary": "auto"},
|
|
"store": store,
|
|
"stream": stream,
|
|
"include": ["reasoning.encrypted_content"] if effort != "none" else [],
|
|
"prompt_cache_key": "019a0000-0000-7000-8000-00000000e2e0",
|
|
"text": {"verbosity": "low"},
|
|
}
|
|
if tools:
|
|
body["tools"] = TOOLS
|
|
if max_out:
|
|
body["max_output_tokens"] = max_out
|
|
body.update(kw)
|
|
return body
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------------------------------
|
|
# validators
|
|
|
|
def json_type_ok(t, v):
|
|
if t == "string":
|
|
return isinstance(v, str)
|
|
if t == "integer":
|
|
return isinstance(v, int) and not isinstance(v, bool)
|
|
if t == "number":
|
|
return isinstance(v, (int, float)) and not isinstance(v, bool)
|
|
if t == "boolean":
|
|
return isinstance(v, bool)
|
|
if t == "array":
|
|
return isinstance(v, list)
|
|
if t == "object":
|
|
return isinstance(v, dict)
|
|
if t == "null":
|
|
return v is None
|
|
return True
|
|
|
|
|
|
def validate(schema, v, path="$"):
|
|
errs = []
|
|
t = schema.get("type")
|
|
if t and not json_type_ok(t, v):
|
|
return [f"{path}: expected {t}, got {type(v).__name__}"]
|
|
if "enum" in schema and v not in schema["enum"]:
|
|
errs.append(f"{path}: {v!r} not in enum")
|
|
if t == "object" and isinstance(v, dict):
|
|
props = schema.get("properties", {})
|
|
for k in schema.get("required", []):
|
|
if k not in v:
|
|
errs.append(f"{path}: missing {k}")
|
|
for k, x in v.items():
|
|
if k in props:
|
|
errs += validate(props[k], x, f"{path}.{k}")
|
|
elif schema.get("additionalProperties") is False:
|
|
errs.append(f"{path}: unexpected {k}")
|
|
if t == "array" and isinstance(v, list) and "items" in schema:
|
|
for i, x in enumerate(v):
|
|
errs += validate(schema["items"], x, f"{path}[{i}]")
|
|
return errs
|
|
|
|
|
|
TOOL_BY_NAME = {t["name"]: t for t in TOOLS}
|
|
|
|
|
|
def check_calls(sc, resp, label, tools=TOOLS):
|
|
"""Every function_call item: known name, arguments parse as an object and satisfy the tool schema."""
|
|
calls = [i for i in resp.get("output", []) if i.get("type") == "function_call"]
|
|
by = {t["name"]: t for t in tools}
|
|
for c in calls:
|
|
name = c.get("name")
|
|
sc.check(f"{label}: call name '{name}' is a declared tool", name in by, c)
|
|
try:
|
|
args = json.loads(c.get("arguments", ""))
|
|
parsed = isinstance(args, dict)
|
|
except ValueError as e:
|
|
args, parsed = None, False
|
|
sc.check(f"{label}: arguments of {name} parse as JSON", False, f"{e}: {c.get('arguments','')[:200]}")
|
|
if parsed and name in by:
|
|
errs = validate(by[name]["parameters"], args)
|
|
sc.check(f"{label}: arguments of {name} satisfy the schema", not errs, errs)
|
|
sc.check(f"{label}: call has call_id", bool(c.get("call_id")), c)
|
|
return calls
|
|
|
|
|
|
def check_stream(sc, s, label, expect_terminal="response.completed"):
|
|
"""Wire-order invariants of a Responses SSE stream."""
|
|
sc.check(f"{label}: HTTP 200 event-stream", s.status == 200 and not s.transport_error, f"status={s.status} err={s.transport_error} body={s.error_body[:200]!r}")
|
|
if s.status != 200:
|
|
return
|
|
failed = s.response().get("error") if s.terminal() and s.terminal().get("type") == "response.failed" else None
|
|
if failed:
|
|
sc.note(f"{label}: response.failed {json.dumps(failed)[:300]}")
|
|
sc.check(f"{label}: every frame is JSON", not s.bad_json, s.bad_json[:2])
|
|
types = s.types()
|
|
evs = [d for _, _, d in s.events if isinstance(d, dict)]
|
|
sc.check(f"{label}: first event is response.created", bool(types) and types[0] == "response.created", types[:3])
|
|
terms = [t for t in types if t in ("response.completed", "response.incomplete", "response.failed")]
|
|
sc.check(f"{label}: exactly one terminal event", len(terms) == 1, terms)
|
|
sc.check(f"{label}: terminal event is last", bool(types) and types[-1] in ("response.completed", "response.incomplete", "response.failed"), types[-3:])
|
|
if expect_terminal:
|
|
sc.check(f"{label}: terminal is {expect_terminal}", terms[:1] == [expect_terminal], terms)
|
|
named = [(n, d.get("type")) for _, n, d in s.events if isinstance(d, dict) and n is not None]
|
|
sc.check(f"{label}: SSE event: name equals data.type", all(n == t for n, t in named), [x for x in named if x[0] != x[1]][:3])
|
|
seq = [d.get("sequence_number") for d in evs]
|
|
sc.check(f"{label}: sequence_number present and strictly increasing", all(isinstance(x, int) for x in seq) and all(b > a for a, b in zip(seq, seq[1:])), seq[:6])
|
|
# item bracketing
|
|
added = {d["output_index"]: d["item"].get("type") for d in evs if d.get("type") == "response.output_item.added"}
|
|
done = {d["output_index"]: d["item"] for d in evs if d.get("type") == "response.output_item.done"}
|
|
sc.check(f"{label}: every added item is done", set(added) == set(done), (added, list(done)))
|
|
resp = s.response()
|
|
final = resp.get("output", [])
|
|
if resp.get("status") != "failed":
|
|
sc.check(f"{label}: final output equals the done items", [i.get("type") for i in final] == [done[k].get("type") for k in sorted(done)], (len(final), len(done)))
|
|
# text integrity
|
|
deltas = "".join(d.get("delta", "") for d in evs if d.get("type") == "response.output_text.delta")
|
|
done_text = "".join(d.get("text", "") for d in evs if d.get("type") == "response.output_text.done")
|
|
final_text = "".join(p.get("text", "") for i in final if i.get("type") == "message" for p in i.get("content", []) if p.get("type") == "output_text")
|
|
sc.check(f"{label}: text deltas == output_text.done == final message", deltas == done_text == final_text, (len(deltas), len(done_text), len(final_text)))
|
|
# tool arguments integrity
|
|
for k, item in done.items():
|
|
if item.get("type") == "function_call":
|
|
frag = "".join(d.get("delta", "") for d in evs if d.get("type") == "response.function_call_arguments.delta" and d.get("output_index") == k)
|
|
fin = [d.get("arguments") for d in evs if d.get("type") == "response.function_call_arguments.done" and d.get("output_index") == k]
|
|
sc.check(f"{label}: arguments deltas == done == item", fin == [item.get("arguments")] and (frag == "" or frag == item.get("arguments")), (frag[:80], fin, item.get("arguments", "")[:80]))
|
|
u = resp.get("usage") or {}
|
|
if resp.get("status") != "failed":
|
|
sc.check(f"{label}: usage present and consistent",
|
|
u.get("input_tokens", 0) > 0 and u.get("output_tokens", 0) > 0 and u.get("total_tokens") == u.get("input_tokens", 0) + u.get("output_tokens", 0), u)
|
|
|
|
|
|
def ttft(s):
|
|
"""Time from request start to the first visible model output (text delta, else first function-call argument delta)."""
|
|
for typ in ("response.output_text.delta", "response.function_call_arguments.delta", "response.reasoning_text.delta"):
|
|
t = s.first(typ)
|
|
if t is not None:
|
|
return t
|
|
return s.first("response.output_item.done")
|
|
|
|
|
|
def rates(sc, s, prefix):
|
|
resp = s.response()
|
|
u = resp.get("usage") or {}
|
|
out = u.get("output_tokens", 0)
|
|
t_first = ttft(s)
|
|
sc.metric(prefix + "ttft_s", round(t_first, 3) if t_first is not None else None)
|
|
sc.metric(prefix + "created_s", round(s.first("response.created") or -1, 3))
|
|
sc.metric(prefix + "total_s", round(s.t_end, 3) if s.t_end else None)
|
|
sc.metric(prefix + "input_tokens", u.get("input_tokens"))
|
|
sc.metric(prefix + "cached_tokens", (u.get("input_tokens_details") or {}).get("cached_tokens"))
|
|
sc.metric(prefix + "output_tokens", out)
|
|
if t_first is not None and s.t_end and out > 1 and s.t_end - t_first > 0.05:
|
|
sc.metric(prefix + "decode_tok_s", round((out - 1) / (s.t_end - t_first), 2))
|
|
sc.metric(prefix + "keepalive_comments", len(s.comments))
|
|
|
|
|
|
def output_message_items(resp):
|
|
return [i for i in resp.get("output", []) if i.get("type") in ("message", "function_call", "reasoning")]
|
|
|
|
|
|
def replay_items(resp):
|
|
"""Items a stateless client sends back next turn (Codex replays the output items verbatim)."""
|
|
out = []
|
|
for i in resp.get("output", []):
|
|
if i.get("type") in ("message", "function_call", "reasoning"):
|
|
out.append(i)
|
|
return out
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------------------------------
|
|
# environment sampling (RSS of the stack processes, GPU memory)
|
|
|
|
def rss_kb(pid):
|
|
try:
|
|
with open(f"/proc/{pid}/status") as f:
|
|
for line in f:
|
|
if line.startswith("VmRSS:"):
|
|
return int(line.split()[1])
|
|
except OSError:
|
|
return None
|
|
return None
|
|
|
|
|
|
def gpu_used_mib():
|
|
try:
|
|
out = subprocess.run(["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=20).stdout
|
|
return int(out.strip().splitlines()[0])
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def mem_available_mib():
|
|
try:
|
|
with open("/proc/meminfo") as f:
|
|
for line in f:
|
|
if line.startswith("MemAvailable:"):
|
|
return int(line.split()[1]) // 1024
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
def sample(ctx):
|
|
s = {"t": round(time.time() - ctx.t_start, 1), "gpu_used_mib": gpu_used_mib(), "mem_available_mib": mem_available_mib()}
|
|
for name, pid in ctx.pids.items():
|
|
s["rss_mib_" + name] = (rss_kb(pid) or 0) // 1024
|
|
return s
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------------------------------
|
|
# scenarios
|
|
|
|
class Ctx:
|
|
pass
|
|
|
|
|
|
def metrics_snapshot(ctx):
|
|
r = ctx.c.call("GET", "/metrics")
|
|
return r.json if r.status == 200 else {"status": r.status}
|
|
|
|
|
|
def wait_idle(ctx, limit=60.0):
|
|
"""Seconds until /metrics reports no active generation (None when it never does)."""
|
|
t0 = time.monotonic()
|
|
while time.monotonic() - t0 < limit:
|
|
m = ctx.c.call("GET", "/metrics").json or {}
|
|
if m.get("active") is False and (m.get("queue_used") in (0, None)):
|
|
return time.monotonic() - t0
|
|
time.sleep(0.05)
|
|
return None
|
|
|
|
|
|
def sc_endpoints(ctx, sc):
|
|
c = ctx.c
|
|
r = c.call("GET", "/health", auth=False)
|
|
sc.check("GET /health without auth is 200 ok", r.status == 200 and (r.json or {}).get("status") == "ok", (r.status, r.payload[:100]))
|
|
r = c.call("GET", "/ready")
|
|
sc.check("GET /ready 200 with ready=true", r.status == 200 and (r.json or {}).get("ready") is True, (r.status, r.payload[:200]))
|
|
sc.metric("ready_body", r.json)
|
|
r = c.call("GET", "/status")
|
|
sc.check("GET /status ready, worker ready, max_context", r.status == 200 and (r.json or {}).get("ready") is True and (r.json or {}).get("worker") == "ready" and (r.json or {}).get("max_context", 0) > 0, r.payload[:200])
|
|
r = c.call("GET", "/metrics")
|
|
sc.check("GET /metrics schema_version 1 and worker ready", r.status == 200 and (r.json or {}).get("schema_version") == 1 and (r.json or {}).get("worker") == "ready", r.payload[:300])
|
|
sc.metric("metrics_initial", r.json)
|
|
r = c.call("GET", "/v1/models")
|
|
ids = [m.get("id") for m in ((r.json or {}).get("data") or [])]
|
|
sc.check("GET /v1/models lists the model", r.status == 200 and ctx.model in ids, r.payload[:200])
|
|
r = c.call("GET", "/v1/models/" + ctx.model)
|
|
sc.check("GET /v1/models/{id}", r.status == 200 and (r.json or {}).get("id") == ctx.model, r.payload[:200])
|
|
r = c.call("GET", "/v1/models/nope")
|
|
sc.check("unknown model id is 404 model_not_found", r.status == 404 and r.err().get("code") == "model_not_found", r.payload[:200])
|
|
r = c.call("GET", "/api/health", auth=False)
|
|
sc.check("GET /api/health 200", r.status == 200, (r.status, r.payload[:200]))
|
|
r = c.call("GET", "/admin/lifecycle")
|
|
sc.check("GET /admin/lifecycle not draining", r.status == 200 and (r.json or {}).get("draining") is False, r.payload[:300])
|
|
# auth
|
|
r = c.call("GET", "/status", auth=False)
|
|
sc.check("GET /status without key is 401", r.status == 401, (r.status, r.payload[:120]))
|
|
c2 = Client(ctx.base, "wrong-" + "x" * 40)
|
|
r = c2.call("POST", "/v1/responses", {"model": ctx.model, "input": "hi"})
|
|
sc.check("POST /v1/responses with a wrong key is 401", r.status == 401, (r.status, r.payload[:120]))
|
|
r = c.call("GET", "/v1/responses/resp_does_not_exist")
|
|
sc.check("GET unknown stored response is 404 response_not_found", r.status == 404 and r.err().get("code") == "response_not_found", r.payload[:200])
|
|
|
|
|
|
def sc_simple(ctx, sc):
|
|
# streaming, Codex-shaped, no tool needed
|
|
body = codex_body(ctx.model, "Reply with exactly the five words: the quick brown fox jumps", tools=True, max_out=64, temperature=0)
|
|
s = ctx.c.stream("/v1/responses", body)
|
|
check_stream(sc, s, "stream")
|
|
resp = s.response()
|
|
text = s.text()
|
|
sc.check("stream: non-empty text", len(text.strip()) > 0, text[:100])
|
|
sc.check("stream: status completed, no incomplete_details", resp.get("status") == "completed" and not resp.get("incomplete_details"), resp.get("incomplete_details"))
|
|
sc.check("stream: finished on its own (output_tokens < max_output_tokens)", (resp.get("usage") or {}).get("output_tokens", 999) < 64, resp.get("usage"))
|
|
sc.check("stream: reply mentions the words", "quick" in text.lower() and "fox" in text.lower(), text[:200])
|
|
sc.check("stream: response.id looks like resp_", str(resp.get("id", "")).startswith("resp_"), resp.get("id"))
|
|
sc.check("stream: store=false echoed", resp.get("store") is False, resp.get("store"))
|
|
rates(sc, s, "stream_")
|
|
sc.metric("stream_text", text[:200])
|
|
# non-streaming same request
|
|
body = codex_body(ctx.model, "Reply with exactly the five words: the quick brown fox jumps", tools=True, max_out=64, stream=False, temperature=0)
|
|
r = ctx.c.call("POST", "/v1/responses", body)
|
|
sc.check("json: HTTP 200", r.status == 200, r.payload[:300])
|
|
j = r.json or {}
|
|
jt = "".join(p.get("text", "") for i in j.get("output", []) if i.get("type") == "message" for p in i.get("content", []))
|
|
sc.check("json: status completed", j.get("status") == "completed", j.get("status"))
|
|
sc.check("json: greedy text equals the streamed text", jt == text, (jt[:100], text[:100]))
|
|
sc.metric("json_total_s", round(r.dt, 3))
|
|
u = j.get("usage") or {}
|
|
sc.metric("json_usage", u)
|
|
# input_tokens endpoint agrees with usage
|
|
cnt = ctx.c.call("POST", "/v1/responses/input_tokens", {k: v for k, v in body.items() if k not in ("stream", "max_output_tokens", "temperature", "store", "prompt_cache_key", "include")})
|
|
n = (cnt.json or {}).get("input_tokens")
|
|
sc.check("input_tokens endpoint == usage.input_tokens of the real generation", cnt.status == 200 and n == u.get("input_tokens"), (cnt.status, n, u.get("input_tokens"), cnt.payload[:200]))
|
|
# length stop
|
|
body = codex_body(ctx.model, "Write a long essay about the history of compilers. Make it at least 500 words.", tools=False, max_out=24, temperature=0)
|
|
s = ctx.c.stream("/v1/responses", body)
|
|
check_stream(sc, s, "length", expect_terminal="response.incomplete")
|
|
resp = s.response()
|
|
sc.check("length: status incomplete / max_output_tokens", resp.get("status") == "incomplete" and (resp.get("incomplete_details") or {}).get("reason") == "max_output_tokens", (resp.get("status"), resp.get("incomplete_details")))
|
|
sc.check("length: output_tokens == 24 (engine count)", (resp.get("usage") or {}).get("output_tokens") == 24, resp.get("usage"))
|
|
# instructions-only / string input form
|
|
r = ctx.c.call("POST", "/v1/responses", {"model": ctx.model, "input": "Say OK.", "max_output_tokens": 16, "temperature": 0})
|
|
sc.check("plain string input works", r.status == 200 and (r.json or {}).get("status") in ("completed", "incomplete"), r.payload[:200])
|
|
|
|
|
|
TOOL_TASKS = [
|
|
("shell", "Use the shell tool to list the files in the current directory (run `ls -la`)."),
|
|
("read_file", "Use the read_file tool to read the file src/main.rs, lines 1 to 40."),
|
|
("update_plan", "Use the update_plan tool to record a three step plan: inspect the code (completed), fix the bug (in_progress), run the tests (pending)."),
|
|
]
|
|
|
|
TOOL_RESULTS = {
|
|
"shell": "total 24\ndrwxr-xr-x 5 dev dev 4096 Oct 17 10:00 .\n-rw-r--r-- 1 dev dev 812 Oct 17 10:00 Cargo.toml\ndrwxr-xr-x 2 dev dev 4096 Oct 17 10:00 src\n-rw-r--r-- 1 dev dev 311 Oct 17 10:00 README.md\n",
|
|
"read_file": "fn main() {\n println!(\"hello\");\n}\n",
|
|
"update_plan": "Plan updated",
|
|
}
|
|
|
|
|
|
def sc_tools(ctx, sc):
|
|
for want, task in TOOL_TASKS:
|
|
label = f"tool[{want}]"
|
|
# (a) streamed, expect a function_call, then stateless replay with function_call_output
|
|
body = codex_body(ctx.model, task, max_out=512, temperature=0)
|
|
s = ctx.c.stream("/v1/responses", body)
|
|
check_stream(sc, s, label + " turn1")
|
|
resp = s.response()
|
|
calls = check_calls(sc, resp, label + " turn1")
|
|
sc.check(f"{label}: model emitted a function_call", len(calls) >= 1, [i.get("type") for i in resp.get("output", [])])
|
|
sc.check(f"{label}: called {want}", any(c.get("name") == want for c in calls), [c.get("name") for c in calls])
|
|
sc.check(f"{label}: stop reason completed", resp.get("status") == "completed", (resp.get("status"), resp.get("incomplete_details")))
|
|
rates(sc, s, label + "_t1_")
|
|
sc.metric(label + "_call", [{"name": c.get("name"), "arguments": c.get("arguments")} for c in calls][:2])
|
|
if not calls:
|
|
sc.note(f"{label}: no call; text={s.text()[:200]!r}")
|
|
continue
|
|
call = calls[0]
|
|
out = [msg("user", task)] if False else []
|
|
history = replay_items(resp)
|
|
history.append({"type": "function_call_output", "call_id": call["call_id"], "output": TOOL_RESULTS.get(call["name"], "ok")})
|
|
body2 = codex_body(ctx.model, task, max_out=512, temperature=0)
|
|
body2["input"] = body["input"] + history
|
|
s2 = ctx.c.stream("/v1/responses", body2)
|
|
check_stream(sc, s2, label + " turn2")
|
|
r2 = s2.response()
|
|
calls2 = check_calls(sc, r2, label + " turn2")
|
|
txt = s2.text().strip()
|
|
sc.check(f"{label}: continuation produced text or a further valid call", len(txt) > 0 or len(calls2) > 0, r2.get("output"))
|
|
sc.check(f"{label}: turn2 prefix reuse reported", True)
|
|
rates(sc, s2, label + "_t2_")
|
|
sc.metric(label + "_t2_text", txt[:160])
|
|
# forced tool choice, non-streaming, nested array of objects
|
|
body = codex_body(ctx.model, "Plan the work: write tests, then implement.", max_out=400, stream=False, temperature=0,
|
|
tool_choice={"type": "function", "name": "update_plan"})
|
|
r = ctx.c.call("POST", "/v1/responses", body)
|
|
sc.check("forced tool_choice: HTTP 200", r.status == 200, r.payload[:300])
|
|
j = r.json or {}
|
|
calls = check_calls(sc, j, "forced")
|
|
sc.check("forced tool_choice: update_plan was called", any(c.get("name") == "update_plan" for c in calls), [i.get("type") for i in j.get("output", [])])
|
|
# tool_choice none: must not call
|
|
body = codex_body(ctx.model, "Use the shell tool to run ls.", max_out=128, stream=False, temperature=0, tool_choice="none")
|
|
r = ctx.c.call("POST", "/v1/responses", body)
|
|
j = r.json or {}
|
|
sc.check("tool_choice none: no function_call item", r.status == 200 and not [i for i in j.get("output", []) if i.get("type") == "function_call"], r.payload[:300])
|
|
|
|
|
|
def sc_multiturn(ctx, sc):
|
|
# (A) previous_response_id with store=true; only the new user message is sent
|
|
ids, usages = [], []
|
|
qs = ["My project is called Leleka and it serves a Qwen model on one GPU. Remember the name. Reply OK.",
|
|
"What is the name of my project? Answer with one word.",
|
|
"And what does it serve, in five words or fewer?"]
|
|
prev = None
|
|
for n, q in enumerate(qs):
|
|
body = codex_body(ctx.model, q, max_out=48, store=True, temperature=0, tools=False)
|
|
if prev:
|
|
body = {"model": ctx.model, "instructions": INSTRUCTIONS, "input": [msg("user", q)], "previous_response_id": prev, "store": True, "stream": True,
|
|
"max_output_tokens": 48, "temperature": 0, "reasoning": {"effort": "none"}}
|
|
s = ctx.c.stream("/v1/responses", body)
|
|
check_stream(sc, s, f"prev-id turn{n+1}")
|
|
resp = s.response()
|
|
prev = resp.get("id")
|
|
ids.append(prev)
|
|
u = resp.get("usage") or {}
|
|
usages.append(u)
|
|
rates(sc, s, f"prev_t{n+1}_")
|
|
sc.metric(f"prev_t{n+1}_text", s.text()[:120])
|
|
if n == 1:
|
|
sc.check("prev-id: second turn remembers the project name", "leleka" in s.text().lower(), s.text()[:200])
|
|
sc.metric("prev_ids", ids)
|
|
ctx.shared["stored_ids"] = ids
|
|
for n in (1, 2):
|
|
cached = (usages[n].get("input_tokens_details") or {}).get("cached_tokens", 0)
|
|
sc.check(f"prev-id turn{n+1}: engine reused the conversation prefix (cached_tokens > 0)", cached > 0, usages[n])
|
|
sc.metric(f"prev_t{n+1}_prefill_tokens", usages[n].get("input_tokens", 0) - cached)
|
|
# (B) stateless full-history replay, store=false
|
|
history = []
|
|
for n, q in enumerate(qs):
|
|
body = codex_body(ctx.model, None, max_out=48, temperature=0, tools=False, extra_input=history + [msg("user", q)])
|
|
s = ctx.c.stream("/v1/responses", body)
|
|
check_stream(sc, s, f"replay turn{n+1}")
|
|
resp = s.response()
|
|
u = resp.get("usage") or {}
|
|
rates(sc, s, f"replay_t{n+1}_")
|
|
cached = (u.get("input_tokens_details") or {}).get("cached_tokens", 0)
|
|
sc.metric(f"replay_t{n+1}_prefill_tokens", u.get("input_tokens", 0) - cached)
|
|
if n >= 1:
|
|
sc.check(f"replay turn{n+1}: prefix reuse across a stateless replay (cached_tokens > 0)", cached > 0, u)
|
|
history += [msg("user", q)] + replay_items(resp)
|
|
# stored response resources
|
|
if ids and ids[0]:
|
|
r = ctx.c.call("GET", "/v1/responses/" + ids[0])
|
|
sc.check("GET stored response", r.status == 200 and (r.json or {}).get("id") == ids[0], r.payload[:200])
|
|
r = ctx.c.call("GET", "/v1/responses/" + ids[-1] + "/input_items")
|
|
sc.check("GET input_items lists expanded history", r.status == 200 and len((r.json or {}).get("data", [])) >= 3, r.payload[:200])
|
|
r = ctx.c.call("DELETE", "/v1/responses/" + ids[0])
|
|
sc.check("DELETE stored response", r.status == 200 and (r.json or {}).get("deleted") is True, r.payload[:200])
|
|
r = ctx.c.call("GET", "/v1/responses/" + ids[0])
|
|
sc.check("deleted response is 404", r.status == 404, r.status)
|
|
body = {"model": ctx.model, "input": [msg("user", "hi")], "previous_response_id": ids[0], "max_output_tokens": 8}
|
|
r = ctx.c.call("POST", "/v1/responses", body)
|
|
sc.check("continuing from a deleted id is 404 response_not_found", r.status == 404 and r.err().get("code") == "response_not_found", (r.status, r.payload[:200]))
|
|
|
|
|
|
def build_context(ctx, target_tokens):
|
|
"""Repository text (sanitized: only files from --context-dir, no config/key/env files) of at least target_tokens, counted by the server."""
|
|
files = []
|
|
for pat in ("**/*.rs", "**/*.md"):
|
|
files += sorted(glob.glob(os.path.join(ctx.context_dir, pat), recursive=True))
|
|
parts = []
|
|
size = 0
|
|
for f in files:
|
|
if any(x in f for x in (".env", "secret", "key", "token", "target/")):
|
|
continue
|
|
try:
|
|
t = open(f, encoding="utf-8").read()
|
|
except (OSError, UnicodeDecodeError):
|
|
continue
|
|
rel = os.path.relpath(f, ctx.context_dir).replace("\\", "/")
|
|
parts.append(f"=== {rel} ===\n{t}\n")
|
|
size += len(t)
|
|
if size > 6 * target_tokens and len(parts) > 4:
|
|
break
|
|
text = "".join(parts)
|
|
# trim/extend to the target by asking the server how many tokens the request has
|
|
def count(chars):
|
|
body = codex_body(ctx.model, "Context follows.\n" + text[:chars] + "\n\nQuestion: ", tools=True)
|
|
r = ctx.c.call("POST", "/v1/responses/input_tokens", {k: v for k, v in body.items() if k not in ("stream", "store", "prompt_cache_key", "include")})
|
|
return (r.json or {}).get("input_tokens", 0)
|
|
lo, hi = 2000, len(text)
|
|
n = count(hi)
|
|
if n < target_tokens:
|
|
return text, n
|
|
while hi - lo > 400:
|
|
mid = (lo + hi) // 2
|
|
if count(mid) >= target_tokens:
|
|
hi = mid
|
|
else:
|
|
lo = mid
|
|
return text[:hi], count(hi)
|
|
|
|
|
|
def sc_long(ctx, sc):
|
|
ctxt, n = build_context(ctx, ctx.long_tokens)
|
|
sc.metric("context_tokens_with_overhead", n)
|
|
sc.check(f"context built to >= {ctx.long_tokens} tokens", n >= ctx.long_tokens, n)
|
|
q1 = "Question: which Rust crate contains the Responses API worker for a text-level engine, and what file is it in? Answer in one sentence."
|
|
body = codex_body(ctx.model, "Repository context follows.\n" + ctxt + "\n\n" + q1, tools=False, max_out=96, temperature=0, store=False)
|
|
s = ctx.c.stream("/v1/responses", body)
|
|
check_stream(sc, s, "long turn1")
|
|
rates(sc, s, "long_t1_")
|
|
sc.metric("long_t1_text", s.text()[:200])
|
|
resp = s.response()
|
|
u1 = resp.get("usage") or {}
|
|
sc.check("long: prompt >= target tokens in usage", u1.get("input_tokens", 0) >= ctx.long_tokens, u1)
|
|
# follow-up on the same context: only the suffix may be prefilled
|
|
q2 = "Question: now name one thing in the context about caching or cancellation, in one sentence."
|
|
history = replay_items(resp)
|
|
body2 = dict(body)
|
|
body2["input"] = body["input"] + history + [msg("user", q2)]
|
|
s2 = ctx_stream = ctx.c.stream("/v1/responses", body2)
|
|
check_stream(sc, s2, "long turn2")
|
|
rates(sc, s2, "long_t2_")
|
|
u2 = s2.response().get("usage") or {}
|
|
c2 = (u2.get("input_tokens_details") or {}).get("cached_tokens", 0)
|
|
sc.metric("long_t2_prefill_tokens", u2.get("input_tokens", 0) - c2)
|
|
sc.check("long turn2: re-prefilled only the suffix (cached_tokens >= 90% of turn1 prompt)", c2 >= 0.9 * u1.get("input_tokens", 1), (c2, u1.get("input_tokens")))
|
|
if s.t_first_byte is not None and (s2.first("response.output_text.delta") or 0) > 0:
|
|
sc.metric("long_ttft_speedup_x", round((ttft(s) or 0) / max(ttft(s2) or 1e-9, 1e-9), 2))
|
|
# a different question over the same context from scratch (root/turn checkpoint reuse)
|
|
body3 = codex_body(ctx.model, "Repository context follows.\n" + ctxt + "\n\nQuestion: how many tools does a Codex request declare in the e2e client? Short answer.", tools=False, max_out=48, temperature=0)
|
|
s3 = ctx.c.stream("/v1/responses", body3)
|
|
check_stream(sc, s3, "long variant")
|
|
rates(sc, s3, "long_t3_")
|
|
c3 = ((s3.response().get("usage") or {}).get("input_tokens_details") or {}).get("cached_tokens", 0)
|
|
sc.check("long variant: shared context prefix reused", c3 > 0.5 * u1.get("input_tokens", 1), c3)
|
|
if s.comments:
|
|
sc.note(f"long turn1: {len(s.comments)} keep-alive comment(s) during prefill")
|
|
# Informational: the same long context with the Codex tool list. The model decides whether to call a tool; a malformed call
|
|
# ends the stream with response.failed (the model's format error, see docs/e2e-run.md), which is recorded, not scored.
|
|
body4 = codex_body(ctx.model, "Repository context follows.\n" + ctxt + "\n\n" + q1, tools=True, max_out=256, temperature=0)
|
|
s4 = ctx.c.stream("/v1/responses", body4)
|
|
r4 = s4.response()
|
|
sc.metric("long_with_tools_status", r4.get("status"))
|
|
sc.metric("long_with_tools_types", [i.get("type") for i in r4.get("output", [])])
|
|
sc.metric("long_with_tools_error", r4.get("error"))
|
|
rates(sc, s4, "long_t4_")
|
|
if r4.get("status") == "completed":
|
|
check_calls(sc, r4, "long with tools")
|
|
|
|
|
|
def sc_xlong(ctx, sc):
|
|
"""A prompt long enough that prefill outlasts the 15 s SSE keep-alive, then a follow-up that must only prefill the suffix."""
|
|
ctxt, n = build_context(ctx, ctx.xlong_tokens)
|
|
sc.metric("xlong_context_tokens_with_overhead", n)
|
|
sc.check(f"xlong context built to >= {ctx.xlong_tokens} tokens", n >= ctx.xlong_tokens, n)
|
|
q1 = "Question: name the file that implements the text-level engine worker. One sentence."
|
|
body = codex_body(ctx.model, "Repository context follows." + chr(10) + ctxt + chr(10) + chr(10) + q1, tools=False, max_out=64, temperature=0)
|
|
s = ctx.c.stream("/v1/responses", body)
|
|
check_stream(sc, s, "xlong turn1", expect_terminal=None)
|
|
rates(sc, s, "xlong_t1_")
|
|
u1 = s.response().get("usage") or {}
|
|
prefill_s = ttft(s) or 0
|
|
if prefill_s > 16:
|
|
sc.check("xlong: SSE keep-alive comments flowed during the long prefill", len(s.comments) >= 1, len(s.comments))
|
|
sc.metric("xlong_t1_prefill_tok_s", round(u1.get("input_tokens", 0) / prefill_s, 1) if prefill_s else None)
|
|
hist = replay_items(s.response())
|
|
body2 = dict(body)
|
|
body2["input"] = body["input"] + hist + [msg("user", "Question: and what is its worker entry function called? One sentence.")]
|
|
s2 = ctx.c.stream("/v1/responses", body2)
|
|
check_stream(sc, s2, "xlong turn2", expect_terminal=None)
|
|
rates(sc, s2, "xlong_t2_")
|
|
u2 = s2.response().get("usage") or {}
|
|
c2 = (u2.get("input_tokens_details") or {}).get("cached_tokens", 0)
|
|
sc.metric("xlong_t2_prefill_tokens", u2.get("input_tokens", 0) - c2)
|
|
sc.check("xlong turn2: only the suffix was prefilled (cached >= 90%)", c2 >= 0.9 * u1.get("input_tokens", 1), (c2, u1.get("input_tokens")))
|
|
|
|
|
|
def sc_cancel(ctx, sc):
|
|
# (1) disconnect mid-decode
|
|
body = codex_body(ctx.model, "Write a very long, detailed essay about the history of programming languages. Do not stop early.", tools=False, max_out=1500, temperature=0)
|
|
before = metrics_snapshot(ctx).get("generation", {})
|
|
t_close = {}
|
|
|
|
def stop(s):
|
|
if s.count("response.output_text.delta") >= 12:
|
|
t_close["t"] = time.monotonic()
|
|
return True
|
|
return False
|
|
s = ctx.c.stream("/v1/responses", body, stop=stop)
|
|
sc.check("cancel: stream was running and aborted client-side", s.aborted, (s.status, s.transport_error, len(s.events)))
|
|
freed = wait_idle(ctx, 60)
|
|
sc.check("cancel: engine idle again (metrics active=false, queue empty)", freed is not None, freed)
|
|
if freed is not None and "t" in t_close:
|
|
sc.metric("cancel_decode_free_s", round(time.monotonic() - t_close["t"], 3))
|
|
after = metrics_snapshot(ctx).get("generation", {})
|
|
sc.check("cancel: metrics count the cancelled generation", after.get("cancelled", 0) >= before.get("cancelled", 0) + 1, (before, after))
|
|
ctx.c.call("GET", "/status")
|
|
s = ctx.c.stream("/v1/responses", codex_body(ctx.model, "Reply with OK.", tools=False, max_out=16, temperature=0))
|
|
check_stream(sc, s, "after cancel (decode)")
|
|
sc.check("after cancel: the next request answers", len(s.text().strip()) > 0, s.text())
|
|
# (2) disconnect during prefill of a long prompt (before the first delta)
|
|
ctxt, n = build_context(ctx, 6000)
|
|
body = codex_body(ctx.model, "Context.\n" + ctxt + "\n\nSummarize the context in detail.", max_out=200, temperature=0)
|
|
t_close.clear()
|
|
|
|
def stop2(s):
|
|
if s.first("response.created") is not None:
|
|
t_close["t"] = time.monotonic()
|
|
time.sleep(1.5)
|
|
return True
|
|
return False
|
|
s = ctx.c.stream("/v1/responses", body, stop=stop2)
|
|
sc.check("cancel in prefill: aborted before any text", s.aborted and s.count("response.output_text.delta") == 0, (s.aborted, s.types()[:5]))
|
|
freed = wait_idle(ctx, 120)
|
|
sc.check("cancel in prefill: engine idle again", freed is not None, freed)
|
|
if freed is not None and "t" in t_close:
|
|
sc.metric("cancel_prefill_free_s", round(time.monotonic() - t_close["t"], 3))
|
|
s = ctx.c.stream("/v1/responses", codex_body(ctx.model, "Reply with OK.", tools=False, max_out=16, temperature=0))
|
|
check_stream(sc, s, "after cancel (prefill)")
|
|
st = ctx.c.call("GET", "/status").json or {}
|
|
sc.check("after cancels: still ready", st.get("ready") is True, st)
|
|
# (3) the same prompt as the cancelled one still gives a full answer
|
|
s = ctx.c.stream("/v1/responses", codex_body(ctx.model, "Context.\n" + ctxt + "\n\nSummarize the context in one sentence.", max_out=64, temperature=0))
|
|
check_stream(sc, s, "cancelled prompt re-sent", expect_terminal=None)
|
|
rates(sc, s, "cancel_resend_")
|
|
|
|
|
|
def sc_parallel(ctx, sc):
|
|
# A runs a long generation; B (stream), C (json) arrive while it runs: the engine serves one at a time.
|
|
res = {}
|
|
started = threading.Event()
|
|
|
|
def run_a():
|
|
body = codex_body(ctx.model, "Count from 1 to 120, one number per line, nothing else.", tools=False, max_out=420, temperature=0)
|
|
|
|
def stop(s):
|
|
if s.count("response.output_text.delta") >= 3:
|
|
started.set()
|
|
return False
|
|
res["A"] = ctx.c.stream("/v1/responses", body, stop=stop)
|
|
res["A_end"] = time.monotonic()
|
|
t0 = time.monotonic()
|
|
ta = threading.Thread(target=run_a)
|
|
ta.start()
|
|
sc.check("parallel: A started streaming", started.wait(60), None)
|
|
m = metrics_snapshot(ctx)
|
|
sc.metric("metrics_while_A_runs", {"active": m.get("active"), "queue_used": m.get("queue_used"), "queue_capacity": m.get("queue_capacity")})
|
|
sc.check("parallel: /metrics shows an active generation", m.get("active") is True, m)
|
|
|
|
def run_b():
|
|
res["B_start"] = time.monotonic()
|
|
res["B"] = ctx.c.stream("/v1/responses", codex_body(ctx.model, "Reply with the single word: BETA", tools=False, max_out=16, temperature=0))
|
|
res["B_end"] = time.monotonic()
|
|
|
|
def run_c():
|
|
res["C_start"] = time.monotonic()
|
|
res["C"] = ctx.c.call("POST", "/v1/responses", codex_body(ctx.model, "Reply with the single word: GAMMA", tools=False, max_out=16, temperature=0, stream=False))
|
|
res["C_end"] = time.monotonic()
|
|
tb, tc = threading.Thread(target=run_b), threading.Thread(target=run_c)
|
|
tb.start()
|
|
time.sleep(0.3)
|
|
tc.start()
|
|
time.sleep(0.5)
|
|
m = metrics_snapshot(ctx)
|
|
sc.metric("metrics_with_B_C_waiting", {"active": m.get("active"), "queue_used": m.get("queue_used")})
|
|
# health endpoints stay responsive while the engine is busy
|
|
t = time.monotonic()
|
|
st = ctx.c.call("GET", "/status")
|
|
sc.check("parallel: /status answers while busy", st.status == 200 and (time.monotonic() - t) < 2.0, (st.status, round(time.monotonic() - t, 2)))
|
|
for t_ in (ta, tb, tc):
|
|
t_.join(300)
|
|
A, B, C = res.get("A"), res.get("B"), res.get("C")
|
|
check_stream(sc, A, "A")
|
|
check_stream(sc, B, "B (queued)")
|
|
sc.check("parallel: C (json, queued) answered 200", C is not None and C.status == 200 and (C.json or {}).get("status") == "completed", C and C.payload[:200])
|
|
sc.check("parallel: B text is BETA", B is not None and "BETA" in B.text().upper(), B and B.text())
|
|
sc.check("parallel: no request lost or merged (A has many lines)", A is not None and A.text().count("\n") > 30, A and A.text()[:80])
|
|
# B was queued behind A: B's first text came after A's terminal
|
|
b_first_abs = (res["B_start"] - t0) + (ttft(B) or 0)
|
|
a_end_abs = res["A_end"] - t0
|
|
sc.metric("A_total_s", round(a_end_abs, 2))
|
|
sc.metric("B_created_s_after_start", round((res["B_start"] - t0) + (B.first("response.created") or 0), 2))
|
|
sc.metric("B_first_text_s", round(b_first_abs, 2))
|
|
sc.metric("B_wait_after_A_end_s", round(b_first_abs - a_end_abs, 2))
|
|
sc.check("parallel: B queued behind A (its text starts after A finished)", b_first_abs >= a_end_abs - 0.2, (b_first_abs, a_end_abs))
|
|
wait_idle(ctx, 30)
|
|
# overload: more simultaneous POSTs than max_in_flight_requests (17 by default)
|
|
out = []
|
|
lock = threading.Lock()
|
|
|
|
def tiny(i):
|
|
r = ctx.c.call("POST", "/v1/responses", codex_body(ctx.model, f"Reply with the number {i}.", tools=False, max_out=6, temperature=0, stream=False), timeout=600)
|
|
with lock:
|
|
out.append(r)
|
|
ths = [threading.Thread(target=tiny, args=(i,)) for i in range(ctx.burst)]
|
|
t0 = time.monotonic()
|
|
for t_ in ths:
|
|
t_.start()
|
|
for t_ in ths:
|
|
t_.join(900)
|
|
codes = sorted(r.status for r in out)
|
|
sc.metric("burst_status_codes", {str(k): codes.count(k) for k in set(codes)})
|
|
sc.metric("burst_total_s", round(time.monotonic() - t0, 1))
|
|
ok = [r for r in out if r.status == 200]
|
|
over = [r for r in out if r.status == 429]
|
|
sc.check("burst: every request got 200 or 429 runtime_overloaded", len(ok) + len(over) == len(out) and all(r.err().get("code") == "runtime_overloaded" for r in over), codes)
|
|
sc.check("burst: all admitted requests completed", all((r.json or {}).get("status") in ("completed", "incomplete") for r in ok), [r.payload[:100] for r in ok if (r.json or {}).get("status") not in ("completed", "incomplete")][:2])
|
|
sc.check("burst: 429 carries Retry-After", all(any(k.lower() == "retry-after" for k in r.headers) for r in over), None)
|
|
wait_idle(ctx, 120)
|
|
st = ctx.c.call("GET", "/status").json or {}
|
|
sc.check("burst: still ready afterwards", st.get("ready") is True, st)
|
|
|
|
|
|
INVALID = [
|
|
("malformed JSON", None, b'{"model": "x", "input": ', 400, None),
|
|
("missing model", {"input": "hi"}, None, 400, None),
|
|
("unknown model", {"model": "no-such-model", "input": "hi"}, None, (400, 404), None),
|
|
("missing input", {"model": "@M"}, None, 400, None),
|
|
("empty input array", {"model": "@M", "input": []}, None, 400, None),
|
|
("input of wrong type", {"model": "@M", "input": 5}, None, 400, None),
|
|
("unknown top-level field", {"model": "@M", "input": "hi", "bogus_field": 1}, None, 400, None),
|
|
("max_output_tokens zero", {"model": "@M", "input": "hi", "max_output_tokens": 0}, None, 400, None),
|
|
("max_output_tokens above the runtime cap", {"model": "@M", "input": "hi", "max_output_tokens": 99999}, None, 400, None),
|
|
("negative max_output_tokens", {"model": "@M", "input": "hi", "max_output_tokens": -3}, None, 400, None),
|
|
("temperature out of range", {"model": "@M", "input": "hi", "temperature": 9}, None, 400, None),
|
|
("top_p out of range", {"model": "@M", "input": "hi", "top_p": 2}, None, 400, None),
|
|
("tool without a name", {"model": "@M", "input": "hi", "tools": [{"type": "function", "parameters": {"type": "object"}}]}, None, 400, None),
|
|
("tool with an invalid name", {"model": "@M", "input": "hi", "tools": [{"type": "function", "name": "bad name!", "parameters": {"type": "object"}}]}, None, 400, None),
|
|
("duplicate tool names", {"model": "@M", "input": "hi", "tools": [{"type": "function", "name": "a", "parameters": {"type": "object"}}, {"type": "function", "name": "a", "parameters": {"type": "object"}}]}, None, 400, None),
|
|
("tool_choice naming an undeclared tool", {"model": "@M", "input": "hi", "tools": [{"type": "function", "name": "a", "parameters": {"type": "object"}}], "tool_choice": {"type": "function", "name": "zzz"}}, None, 400, None),
|
|
("hosted tool", {"model": "@M", "input": "hi", "tools": [{"type": "web_search"}]}, None, 400, None),
|
|
("unknown previous_response_id", {"model": "@M", "input": "hi", "previous_response_id": "resp_nope"}, None, 404, "response_not_found"),
|
|
("function_call_output without a call", {"model": "@M", "input": [{"type": "function_call_output", "call_id": "call_zzz", "output": "x"}]}, None, 400, None),
|
|
("image input", {"model": "@M", "input": [{"type": "message", "role": "user", "content": [{"type": "input_image", "image_url": "data:image/png;base64,AAAA"}]}]}, None, 400, None),
|
|
("reasoning_budget_tokens", {"model": "@M", "input": "hi", "reasoning_budget_tokens": 10}, None, 400, "unsupported_request_field"),
|
|
("bad reasoning effort", {"model": "@M", "input": "hi", "reasoning": {"effort": "turbo"}}, None, 400, None),
|
|
("text.format json_schema without schema", {"model": "@M", "input": "hi", "text": {"format": {"type": "json_schema", "name": "x"}}}, None, 400, None),
|
|
("context overflow", "OVERFLOW", None, 400, None),
|
|
]
|
|
|
|
|
|
def sc_invalid(ctx, sc):
|
|
for name, body, raw, expect, code in INVALID:
|
|
if body == "OVERFLOW":
|
|
body = {"model": ctx.model, "input": "hello " * 300000, "max_output_tokens": 16}
|
|
if isinstance(body, dict):
|
|
body = json.loads(json.dumps(body).replace("@M", ctx.model))
|
|
r = ctx.c.call("POST", "/v1/responses", body, raw=raw, timeout=120)
|
|
exp = expect if isinstance(expect, tuple) else (expect,)
|
|
shape = bool(r.err().get("message")) and "type" in r.err()
|
|
sc.check(f"invalid[{name}]: status in {exp} (got {r.status}, code={r.err().get('code')})", r.status in exp, r.payload[:240])
|
|
sc.check(f"invalid[{name}]: error body has message/type/code", shape or r.status == 200, r.payload[:200])
|
|
if code:
|
|
sc.check(f"invalid[{name}]: code {code}", r.err().get("code") == code, r.err())
|
|
sc.metric(f"invalid[{name}]", [r.status, r.err().get("code")])
|
|
# same invalid requests on the streaming path never produce a half-open stream
|
|
s = ctx.c.stream("/v1/responses", {"model": ctx.model, "input": "hi", "stream": True, "max_output_tokens": 0})
|
|
sc.check("invalid stream request answers a plain JSON 400, no SSE", s.status == 400, (s.status, s.error_body[:200]))
|
|
wait_idle(ctx, 10)
|
|
st = ctx.c.call("GET", "/status").json or {}
|
|
sc.check("invalid: server still ready", st.get("ready") is True, st)
|
|
|
|
|
|
def sc_compat(ctx, sc):
|
|
# Chat Completions and Messages share the worker; one small request each.
|
|
body = {"model": ctx.model, "messages": [{"role": "system", "content": "You are terse."}, {"role": "user", "content": "Say hello in three words."}],
|
|
"max_tokens": 32, "temperature": 0, "stream": False}
|
|
r = ctx.c.call("POST", "/v1/chat/completions", body)
|
|
ch = (r.json or {}).get("choices", [{}])[0]
|
|
sc.check("chat completions: 200 with content and finish_reason", r.status == 200 and ch.get("message", {}).get("content") and ch.get("finish_reason") in ("stop", "length"), r.payload[:300])
|
|
body = {"model": ctx.model, "max_tokens": 32, "temperature": 0, "messages": [{"role": "user", "content": "Say hello in three words."}]}
|
|
r = ctx.c.call("POST", "/v1/messages", body, headers={"anthropic-version": "2023-06-01"})
|
|
sc.check("messages: 200 with content and stop_reason", r.status == 200 and (r.json or {}).get("content") and (r.json or {}).get("stop_reason") in ("end_turn", "max_tokens"), r.payload[:300])
|
|
body = {"model": ctx.model, "tools": [{"type": "function", "function": {"name": "shell", "description": "run", "parameters": TOOLS[0]["parameters"]}}],
|
|
"messages": [{"role": "user", "content": "Run `ls` with the shell tool."}], "max_tokens": 200, "temperature": 0}
|
|
r = ctx.c.call("POST", "/v1/chat/completions", body)
|
|
ch = (r.json or {}).get("choices", [{}])[0]
|
|
tc = ch.get("message", {}).get("tool_calls") or []
|
|
ok = r.status == 200 and ch.get("finish_reason") == "tool_calls" and tc
|
|
if ok:
|
|
try:
|
|
a = json.loads(tc[0]["function"]["arguments"])
|
|
ok = not validate(TOOLS[0]["parameters"], a)
|
|
except ValueError:
|
|
ok = False
|
|
sc.check("chat completions: tool call with valid arguments, finish_reason tool_calls", ok, r.payload[:400])
|
|
|
|
|
|
PROMPTS = [
|
|
"What is the capital of France? One word.", "Name three prime numbers. Short.", "Translate 'good morning' to German.",
|
|
"What does the Rust keyword `mut` do? One sentence.", "Give a one-line shell command that counts lines in all .rs files.",
|
|
"What is 17 times 23?", "Name the largest planet in the solar system.", "Is a tomato a fruit? Answer yes or no.",
|
|
]
|
|
|
|
|
|
def sc_soak(ctx, sc):
|
|
n = ctx.soak_n
|
|
base = sample(ctx)
|
|
sc.metric("soak_baseline", base)
|
|
samples = [base]
|
|
lat, tps, bad = [], [], 0
|
|
gen0 = metrics_snapshot(ctx).get("generation", {})
|
|
for i in range(n):
|
|
p = PROMPTS[i % len(PROMPTS)]
|
|
tool = (i % 4 == 3)
|
|
if tool:
|
|
p = "Use the shell tool to print the current date (run `date`)."
|
|
body = codex_body(ctx.model, p, tools=True, max_out=160 if tool else 48, temperature=0, stream=(i % 2 == 0))
|
|
t = time.monotonic()
|
|
if body["stream"]:
|
|
s = ctx.c.stream("/v1/responses", body)
|
|
resp = s.response()
|
|
ok = s.status == 200 and s.terminal() is not None and s.types()[0] == "response.created" and resp.get("status") in ("completed", "incomplete")
|
|
tt = ttft(s)
|
|
u = resp.get("usage") or {}
|
|
if tt is not None and s.t_end and u.get("output_tokens", 0) > 4 and s.t_end - tt > 0.05:
|
|
tps.append((u["output_tokens"] - 1) / (s.t_end - tt))
|
|
else:
|
|
r = ctx.c.call("POST", "/v1/responses", body)
|
|
resp = r.json or {}
|
|
ok = r.status == 200 and resp.get("status") in ("completed", "incomplete")
|
|
dt = time.monotonic() - t
|
|
lat.append(dt)
|
|
if tool and ok:
|
|
for c in [x for x in resp.get("output", []) if x.get("type") == "function_call"]:
|
|
try:
|
|
a = json.loads(c["arguments"])
|
|
ok = ok and not validate(TOOL_BY_NAME[c["name"]]["parameters"], a)
|
|
except (ValueError, KeyError):
|
|
ok = False
|
|
if not ok:
|
|
bad += 1
|
|
sc.note(f"soak request {i} failed: {str(resp)[:200]}")
|
|
if i % 5 == 4:
|
|
samples.append(sample(ctx))
|
|
sc.check(f"soak: all {n} consecutive requests succeeded", bad == 0, f"{bad} bad")
|
|
sc.metric("soak_samples", samples)
|
|
lat_sorted = sorted(lat)
|
|
sc.metric("soak_latency_s", {"min": round(lat_sorted[0], 2), "p50": round(lat_sorted[len(lat) // 2], 2), "p90": round(lat_sorted[int(len(lat) * 0.9)], 2), "max": round(lat_sorted[-1], 2)})
|
|
if tps:
|
|
sc.metric("soak_decode_tok_s_mean", round(sum(tps) / len(tps), 2))
|
|
sc.check("soak: latency of the last third is not worse than 1.5x the first third", sum(lat[-n // 3:]) <= 1.5 * sum(lat[:n // 3]) + 1.0, (sum(lat[:n // 3]), sum(lat[-n // 3:])))
|
|
for key in [k for k in base if k.startswith("rss_mib_")]:
|
|
a, b = samples[1][key] if len(samples) > 1 else base[key], samples[-1][key]
|
|
grow = b - a
|
|
sc.metric(f"soak_{key}_growth_after_first_5", grow)
|
|
sc.check(f"soak: {key} growth after warm-up < 256 MiB", grow < 256, (a, b))
|
|
g0, g1 = (samples[1].get("gpu_used_mib") if len(samples) > 1 else None), samples[-1].get("gpu_used_mib")
|
|
if g0 is not None and g1 is not None:
|
|
sc.metric("soak_gpu_growth_mib", g1 - g0)
|
|
sc.check("soak: GPU memory growth after warm-up < 64 MiB", g1 - g0 < 64, (g0, g1))
|
|
gen1 = metrics_snapshot(ctx).get("generation", {})
|
|
sc.metric("soak_metrics_delta", {k: gen1.get(k, 0) - gen0.get(k, 0) for k in ("started", "completed", "cancelled", "failed_or_interrupted")})
|
|
sc.check("soak: metrics count every generation as completed", gen1.get("completed", 0) - gen0.get("completed", 0) == n, (gen0, gen1))
|
|
|
|
|
|
def sc_determinism(ctx, sc):
|
|
body = codex_body(ctx.model, "List five programming languages, comma separated, nothing else.", tools=False, max_out=40, temperature=0, stream=False)
|
|
outs = []
|
|
for _ in range(3):
|
|
r = ctx.c.call("POST", "/v1/responses", body)
|
|
j = r.json or {}
|
|
outs.append("".join(p.get("text", "") for i in j.get("output", []) if i.get("type") == "message" for p in i.get("content", [])))
|
|
sc.check("greedy: three identical requests give identical text", len(set(outs)) == 1, outs)
|
|
body["temperature"], body["seed"] = 0.8, 1234
|
|
outs = []
|
|
for _ in range(2):
|
|
r = ctx.c.call("POST", "/v1/responses", body)
|
|
j = r.json or {}
|
|
outs.append("".join(p.get("text", "") for i in j.get("output", []) if i.get("type") == "message" for p in i.get("content", [])))
|
|
if outs[0] == outs[1]:
|
|
sc.check("sampled with a fixed seed: reproducible", True)
|
|
else:
|
|
# documented envelope: with the adaptive VRAM expert tier GPU and CPU experts round differently and placement follows copy timing
|
|
sc.note(f"sampled with a fixed seed differs between two runs (adaptive expert tier envelope): {outs}")
|
|
sc.metric("sampled_text", outs[0][:120])
|
|
|
|
|
|
def sc_reasoning(ctx, sc):
|
|
# Codex default: reasoning effort medium with a summary request. Thinking tokens come first, then answer.
|
|
body = codex_body(ctx.model, "What is 12 * 13? Think briefly, then answer with just the number.", effort="medium", max_out=1536, temperature=0)
|
|
s = ctx.c.stream("/v1/responses", body)
|
|
check_stream(sc, s, "reasoning", expect_terminal=None)
|
|
resp = s.response()
|
|
types = [i.get("type") for i in resp.get("output", [])]
|
|
sc.metric("reasoning_output_types", types)
|
|
sc.metric("reasoning_status", resp.get("status"))
|
|
u = resp.get("usage") or {}
|
|
sc.metric("reasoning_usage", u)
|
|
if resp.get("status") == "completed":
|
|
sc.check("reasoning: answer contains 156", "156" in s.text(), s.text()[:200])
|
|
sc.check("reasoning: a reasoning item precedes the message", types[:1] == ["reasoning"] or "reasoning" in types, types)
|
|
sc.check("reasoning: reasoning_tokens reported and <= output_tokens", 0 <= (u.get("output_tokens_details") or {}).get("reasoning_tokens", 0) <= u.get("output_tokens", 0), u)
|
|
else:
|
|
sc.note(f"reasoning ended {resp.get('status')}: {resp.get('incomplete_details')}")
|
|
rates(sc, s, "reasoning_")
|
|
# reasoning turn replay with the reasoning item (Codex replays it) must be accepted
|
|
hist = replay_items(resp)
|
|
if hist:
|
|
body2 = codex_body(ctx.model, None, effort="medium", max_out=256, temperature=0, extra_input=[msg("user", "What is 12 * 13? Think briefly, then answer with just the number.")] + hist + [msg("user", "Now multiply that by 2. Just the number.")])
|
|
s2 = ctx.c.stream("/v1/responses", body2)
|
|
sc.check("reasoning replay: accepted (HTTP 200)", s2.status == 200, (s2.status, s2.error_body[:300]))
|
|
if s2.status == 200:
|
|
check_stream(sc, s2, "reasoning replay", expect_terminal=None)
|
|
rates(sc, s2, "reasoning_t2_")
|
|
|
|
|
|
SCENARIOS = [
|
|
("endpoints", sc_endpoints), ("simple", sc_simple), ("tools", sc_tools), ("multiturn", sc_multiturn), ("long", sc_long), ("xlong", sc_xlong),
|
|
("cancel", sc_cancel), ("parallel", sc_parallel), ("invalid", sc_invalid), ("compat", sc_compat), ("determinism", sc_determinism),
|
|
("reasoning", sc_reasoning), ("soak", sc_soak),
|
|
]
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--base", required=True)
|
|
ap.add_argument("--key-file", required=True)
|
|
ap.add_argument("--model", required=True)
|
|
ap.add_argument("--out", required=True)
|
|
ap.add_argument("--scenarios", default="all")
|
|
ap.add_argument("--context-dir", default=None)
|
|
ap.add_argument("--long-tokens", type=int, default=8500)
|
|
ap.add_argument("--xlong-tokens", type=int, default=24000)
|
|
ap.add_argument("--soak-n", type=int, default=40)
|
|
ap.add_argument("--burst", type=int, default=20)
|
|
ap.add_argument("--pids", default="", help="name=pid,... processes whose RSS is sampled")
|
|
a = ap.parse_args()
|
|
key = open(a.key_file).read().strip()
|
|
ctx = Ctx()
|
|
ctx.c, ctx.base, ctx.model, ctx.shared = Client(a.base, key), a.base, a.model, {}
|
|
ctx.context_dir, ctx.long_tokens, ctx.soak_n, ctx.burst = a.context_dir, a.long_tokens, a.soak_n, a.burst
|
|
ctx.xlong_tokens = a.xlong_tokens
|
|
ctx.pids = {k: int(v) for k, v in (p.split("=") for p in a.pids.split(",") if p)}
|
|
ctx.t_start = time.time()
|
|
wanted = [n for n, _ in SCENARIOS] if a.scenarios == "all" else a.scenarios.split(",")
|
|
results = []
|
|
print(f"scenarios: {wanted}", flush=True)
|
|
for name, fn in SCENARIOS:
|
|
if name not in wanted:
|
|
continue
|
|
print(f"== {name}", flush=True)
|
|
sc = Scenario(name)
|
|
try:
|
|
fn(ctx, sc)
|
|
except Exception:
|
|
sc.error = traceback.format_exc()[-1500:]
|
|
print(" ERROR " + sc.error, flush=True)
|
|
try:
|
|
sc.metrics["env_after"] = sample(ctx)
|
|
sc.metrics["server_metrics_after"] = metrics_snapshot(ctx)
|
|
except Exception:
|
|
pass
|
|
results.append(sc.as_dict())
|
|
with open(a.out, "w") as f:
|
|
json.dump({"scenarios": results}, f, indent=1)
|
|
total = sum(len(r["checks"]) for r in results)
|
|
failed = [(r["name"], c["name"]) for r in results for c in r["checks"] if not c["ok"]]
|
|
print(f"\nSUMMARY: {len(results)} scenarios, {total} checks, {len(failed)} failed, {sum(1 for r in results if r['error'])} errors", flush=True)
|
|
for n, c in failed:
|
|
print(f" FAILED [{n}] {c}")
|
|
sys.exit(0 if not failed and not any(r["error"] for r in results) else 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|