No default changes. scripts/e2e/prefix_tail_equivalence.py scores the `reply` prefix-cache tail live: record an agent session against the reply arm (history built from its own output, so it resumes from its own reply checkpoint), replay the exact request bodies on a cold server (--prefix-cache-mib 0), and judge greedy identity of every output item, tool-call integrity of each arm (declared name, call_id, JSON arguments against the tool schema, streamed deltas == done == item, response.completed), restore evidence (cached_tokens) and, with --control, cold-vs-cold determinism. Verdicts PASS / FAIL_* / INCONCLUSIVE_*. Two sequential phases because one 5090 cannot hold two serve instances. Tested on in-process fake servers (15 tests); it has NOT been run against the engine. The plan (scripts/e2e/prefix_tail_equivalence_plan.md) also records the open numeric-gate decision (q_tail_gate needs teacher-forced captures). docs/prefix-cache.md: the stale "EXPERIMENTAL: off by default" lines now agree with the measured paragraph, and both say that the rtx5090-32g profile sets the tail while the live equivalence gate is open. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
446 lines
26 KiB
Python
446 lines
26 KiB
Python
#!/usr/bin/env python3
|
|
"""Paired equivalence check of the prefix-cache `reply` tail (STRA-328): reply-checkpoint restore vs a cold prefill of the same tokens.
|
|
|
|
OFFLINE TEST DRIVER, stdlib only, Python >= 3.9; never part of serving. It launches no engine and touches no GPU by itself: the operator runs two
|
|
`leleka-serve` instances on the 5090 (not at the same time as other GPU jobs) and this script talks to both over /v1/responses.
|
|
|
|
THE QUESTION. With `--prefix-cache-tail reply` the next turn of an agent session resumes from a checkpoint taken after the committed reply, so the
|
|
cells past the prompt were written by the DECODE kernels, not by prefill (docs/prefix-cache.md, "Request-end checkpoints"). A cold prefill of the
|
|
very same tokens writes them with the prefill kernels. The two states are not bit-identical by construction; the existing evidence (job 9d4,
|
|
flips 1.45 % vs a chunk-cut control 1.45 %) shows only that `reply` sits at the noise floor and could not score `reply` itself (a replay's greedy
|
|
replies diverge from the recorded ones). This script scores it live: the SAME input goes to both arms at every request of a multi-turn agent
|
|
session, the history being built from the reply-arm's own output (so the reply arm resumes from its own reply checkpoint, as in production).
|
|
|
|
ARMS (identical in everything except the cache; the operator starts them, this script only checks what it can see)
|
|
cold `--prefix-cache-mib 0` (no prefix cache, every request prefilled from token 0) [or a fresh process per request: see --cold-note]
|
|
reply `--prefix-cache-mib <N or auto> --prefix-cache-tail reply`
|
|
Same model digest, context, KV type, speculation settings, seed policy and `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0` (docs/prefix-cache.md: the
|
|
static tier, so the expert placement does not move between arms). Greedy: every request carries temperature 0.
|
|
|
|
PER REQUEST (one pair = the same body to both arms; request order inside a pair is reply first, then cold, so the reply arm's cache state is the
|
|
production one)
|
|
1. outputs: the output items (message text, function_call name and arguments string, reasoning text) must be IDENTICAL, string for string.
|
|
2. tool-call integrity, checked on EACH arm separately: every function_call has a declared name, a non-empty call_id, `arguments` that parses as a
|
|
JSON object and satisfies the tool's schema (types of the properties, required keys), the streamed argument deltas concatenate to the `done`
|
|
arguments and to the item's, and the stream ends with response.completed (a cut-off or failed stream is an integrity failure).
|
|
3. restore evidence: the reply arm reports `usage.input_tokens_details.cached_tokens`; a request after the first counts as RESTORED when
|
|
cached_tokens >= --min-cached-fraction of its input_tokens (default 0.5); the cold arm must report ~0. Without restores the run proves nothing.
|
|
4. control (--control): the cold request is sent TWICE; if the two cold outputs differ, greedy decoding is not run-to-run deterministic on this
|
|
setup and no difference between the arms can be attributed to the restore (INCONCLUSIVE_NONDETERMINISTIC).
|
|
|
|
VERDICT (pure function `judge()`, unit-tested in test_prefix_tail_equivalence.py)
|
|
PASS every pair identical, no integrity failure on either arm, restores observed on >= --min-restore-fraction of the
|
|
requests after the first, control (when used) deterministic.
|
|
FAIL_OUTPUT_DIFFERS some pair differs (the first differing request, item and character are recorded).
|
|
FAIL_TOOL_CALL_INTEGRITY a function_call (or a stream) of either arm is malformed; arm and request recorded. Reported before OUTPUT_DIFFERS.
|
|
INCONCLUSIVE_NO_RESTORE the reply arm restored on too few requests (check the server flags / cache budget); the outputs are not evidence.
|
|
INCONCLUSIVE_NONDETERMINISTIC the control found cold != cold.
|
|
INCONCLUSIVE_COLD_ARM_WARM the cold arm itself served cached tokens (it is not cold: start it with `--prefix-cache-mib 0`).
|
|
ERROR transport or protocol failure.
|
|
Exit code: 0 PASS, 1 FAIL_*, 2 INCONCLUSIVE_*, 3 usage, 4 ERROR.
|
|
|
|
The numeric complement (AC1: q_pair / class gate numbers) is separate and uses the logs of the same two arms: see
|
|
scripts/e2e/prefix_tail_equivalence_plan.md, section "Numeric gate".
|
|
|
|
TWO PHASES. A 5090 cannot hold two serve instances, so the normal run is sequential: `record` against the reply arm (phase 1), then restart the
|
|
server WITHOUT the prefix cache and `replay` the recorded requests unchanged against it (phase 2). `run` does both at once when two servers fit.
|
|
|
|
COMMANDS (server; nothing else on the GPU)
|
|
1. reply arm up (`--prefix-cache-mib <N|auto> --prefix-cache-tail reply`):
|
|
python3 scripts/e2e/prefix_tail_equivalence.py record --reply-url http://127.0.0.1:8081 --model <model id> --key-file <key file> \\
|
|
--context-file <text of ~60-70k tokens> --turns 12 --record-out <run root outside Git>/tail-record.json
|
|
2. stop it; start the cold arm with the same flags except `--prefix-cache-mib 0`:
|
|
python3 scripts/e2e/prefix_tail_equivalence.py replay --cold-url http://127.0.0.1:8081 --record <run root>/tail-record.json --control \\
|
|
--key-file <key file> --out <run root>/tail-equivalence.json
|
|
(both arms at once: `run --cold-url U1 --reply-url U2 --model M ... --control --out F`)
|
|
|
|
The result file holds prompts' hashes and the reply text: keep it outside Git. The API key is never written to any output.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.insert(0, HERE)
|
|
|
|
EXIT = {"PASS": 0, "FAIL_OUTPUT_DIFFERS": 1, "FAIL_TOOL_CALL_INTEGRITY": 1, "INCONCLUSIVE_NO_RESTORE": 2, "INCONCLUSIVE_NONDETERMINISTIC": 2,
|
|
"INCONCLUSIVE_COLD_ARM_WARM": 2, "ERROR": 4}
|
|
MAX_TOOL_ROUNDS = 4
|
|
DEFAULT_TURNS = [
|
|
"Use the shell tool to list the files in the current directory (run `ls -la`).",
|
|
"Use the read_file tool to read the file src/main.rs, lines 1 to 40, then summarise it in two sentences.",
|
|
"Use the update_plan tool to record a three step plan: inspect the code (completed), fix the bug (in_progress), run the tests (pending).",
|
|
"Now say in one sentence what you would do next. Do not call a tool.",
|
|
]
|
|
|
|
|
|
def sha256_text(text):
|
|
return hashlib.sha256(text.encode("utf8")).hexdigest()
|
|
|
|
|
|
# ---- schema check (small subset of JSON Schema: type, properties, required, items) -------------------------------------------------------------
|
|
def _type_ok(t, v):
|
|
return {"object": isinstance(v, dict), "array": isinstance(v, list), "string": isinstance(v, str), "boolean": isinstance(v, bool),
|
|
"integer": isinstance(v, int) and not isinstance(v, bool),
|
|
"number": isinstance(v, (int, float)) and not isinstance(v, bool), "null": v is None}.get(t, True)
|
|
|
|
|
|
def schema_errors(schema, v, path="$"):
|
|
errs = []
|
|
t = schema.get("type")
|
|
if t and not _type_ok(t, v):
|
|
return ["%s: expected %s" % (path, t)]
|
|
if isinstance(v, dict):
|
|
for k in schema.get("required", []):
|
|
if k not in v:
|
|
errs.append("%s: missing required key %s" % (path, k))
|
|
for k, sub in (schema.get("properties") or {}).items():
|
|
if k in v:
|
|
errs.extend(schema_errors(sub, v[k], path + "." + k))
|
|
if schema.get("additionalProperties") is False:
|
|
errs.extend("%s: unexpected key %s" % (path, k) for k in v if k not in (schema.get("properties") or {}))
|
|
if isinstance(v, list) and isinstance(schema.get("items"), dict):
|
|
for i, x in enumerate(v):
|
|
errs.extend(schema_errors(schema["items"], x, "%s[%d]" % (path, i)))
|
|
return errs
|
|
|
|
|
|
# ---- one streamed request ----------------------------------------------------------------------------------------------------------------------
|
|
def stream_request(base, key, body, timeout=3600):
|
|
"""Returns {items, usage, status, terminal, deltas_ok, error}. items: the output items as the server finished them."""
|
|
headers = {"Content-Type": "application/json"}
|
|
if key:
|
|
headers["Authorization"] = "Bearer " + key
|
|
req = urllib.request.Request(base.rstrip("/") + "/v1/responses", json.dumps(body).encode(), headers)
|
|
out = {"items": [], "usage": {}, "status": None, "terminal": None, "arg_deltas": {}, "arg_done": {}, "error": None}
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
for raw in r:
|
|
line = raw.decode("utf8", "replace").strip()
|
|
if not line.startswith("data:"):
|
|
continue
|
|
try:
|
|
d = json.loads(line[5:])
|
|
except ValueError:
|
|
continue
|
|
ty = d.get("type", "")
|
|
if ty == "response.output_item.done":
|
|
out["items"].append((d.get("output_index"), d.get("item") or {}))
|
|
elif ty == "response.function_call_arguments.delta":
|
|
out["arg_deltas"].setdefault(d.get("output_index"), []).append(d.get("delta", ""))
|
|
elif ty == "response.function_call_arguments.done":
|
|
out["arg_done"][d.get("output_index")] = d.get("arguments")
|
|
elif ty in ("response.completed", "response.incomplete", "response.failed"):
|
|
resp = d.get("response") or {}
|
|
out["terminal"], out["status"], out["usage"] = ty, resp.get("status"), resp.get("usage") or {}
|
|
if not out["items"] and isinstance(resp.get("output"), list):
|
|
out["items"] = list(enumerate(resp["output"]))
|
|
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
out["error"] = "%s: %s" % (type(exc).__name__, exc)
|
|
out["items"] = [item for _, item in sorted(out["items"], key=lambda p: (p[0] is None, p[0]))]
|
|
return out
|
|
|
|
|
|
def normalise(items):
|
|
"""The comparable form of an arm's output: type + the text-bearing fields only (ids and timestamps differ by construction)."""
|
|
norm = []
|
|
for it in items:
|
|
ty = it.get("type")
|
|
if ty == "function_call":
|
|
norm.append({"type": ty, "name": it.get("name"), "arguments": it.get("arguments")})
|
|
elif ty == "message":
|
|
norm.append({"type": ty, "text": "".join(c.get("text", "") for c in it.get("content", []) if isinstance(c, dict))})
|
|
elif ty == "reasoning":
|
|
norm.append({"type": ty, "text": "".join(c.get("text", "") for c in (it.get("content") or []) if isinstance(c, dict))})
|
|
else:
|
|
norm.append({"type": ty})
|
|
return norm
|
|
|
|
|
|
def first_difference(a, b):
|
|
"""(item index, 'type'|'field'|'char', detail) of the first difference between two normalised outputs, or None."""
|
|
for i in range(max(len(a), len(b))):
|
|
if i >= len(a) or i >= len(b):
|
|
return {"item": i, "what": "item count", "a": len(a), "b": len(b)}
|
|
if a[i] == b[i]:
|
|
continue
|
|
for field in sorted(set(a[i]) | set(b[i])):
|
|
x, y = a[i].get(field), b[i].get(field)
|
|
if x != y:
|
|
at = next((j for j in range(min(len(x or ""), len(y or ""))) if (x or "")[j] != (y or "")[j]), min(len(x or ""), len(y or ""))) \
|
|
if isinstance(x, str) and isinstance(y, str) else None
|
|
return {"item": i, "what": field, "char": at}
|
|
return None
|
|
|
|
|
|
def integrity_errors(res, tools):
|
|
"""Tool-call and stream integrity of ONE arm's response. Returns a list of strings (empty = intact)."""
|
|
errs = []
|
|
if res["error"]:
|
|
return ["transport: " + res["error"]]
|
|
if res["terminal"] != "response.completed":
|
|
errs.append("stream ended with %s (status %s), not response.completed" % (res["terminal"], res["status"]))
|
|
by = dict((t["name"], t) for t in tools if isinstance(t, dict) and t.get("name"))
|
|
for k, it in enumerate(res["items"]):
|
|
if it.get("type") != "function_call":
|
|
continue
|
|
name = it.get("name")
|
|
if name not in by:
|
|
errs.append("item %d: call to undeclared tool %r" % (k, name))
|
|
if not it.get("call_id"):
|
|
errs.append("item %d: no call_id" % k)
|
|
try:
|
|
args = json.loads(it.get("arguments", ""))
|
|
except ValueError as exc:
|
|
errs.append("item %d: arguments do not parse as JSON (%s): %.120r" % (k, exc, it.get("arguments", "")))
|
|
continue
|
|
if not isinstance(args, dict):
|
|
errs.append("item %d: arguments are not a JSON object" % k)
|
|
elif name in by:
|
|
errs.extend("item %d: %s" % (k, e) for e in schema_errors(by[name].get("parameters", {}), args))
|
|
deltas = "".join(res["arg_deltas"].get(k, []))
|
|
done = res["arg_done"].get(k)
|
|
if done is not None and done != it.get("arguments"):
|
|
errs.append("item %d: arguments.done differs from the item's arguments" % k)
|
|
if deltas and deltas != it.get("arguments"):
|
|
errs.append("item %d: streamed argument deltas differ from the item's arguments" % k)
|
|
return errs
|
|
|
|
|
|
# ---- the verdict, a pure function of the pair records ------------------------------------------------------------------------------------------
|
|
def judge(pairs, min_restore_fraction=0.8, control=False):
|
|
"""pairs: list of dicts {index, equal, diff, restored (None for the first request), integrity: {reply: [...], cold: [...]}, control_equal (or None),
|
|
error (or None)}. Returns {verdict, reasons, restored, restore_candidates}."""
|
|
reasons = []
|
|
if not pairs:
|
|
return {"verdict": "ERROR", "reasons": ["no request was completed"], "restored": 0, "restore_candidates": 0}
|
|
errors = [p for p in pairs if p.get("error")]
|
|
if errors:
|
|
return {"verdict": "ERROR", "reasons": ["request %s: %s" % (p["index"], p["error"]) for p in errors], "restored": 0, "restore_candidates": 0}
|
|
cands = [p for p in pairs if p.get("restored") is not None]
|
|
restored = sum(1 for p in cands if p["restored"])
|
|
broken = [(p["index"], arm, e) for p in pairs for arm in ("reply", "cold") for e in p["integrity"].get(arm, [])]
|
|
if broken:
|
|
return {"verdict": "FAIL_TOOL_CALL_INTEGRITY", "reasons": ["request %s, %s arm: %s" % b for b in broken[:10]], "restored": restored,
|
|
"restore_candidates": len(cands)}
|
|
warm = [p["index"] for p in pairs if p.get("cold_warm")]
|
|
if warm:
|
|
return {"verdict": "INCONCLUSIVE_COLD_ARM_WARM", "reasons": ["the cold arm reported cached tokens at request(s) %s" % warm], "restored": restored,
|
|
"restore_candidates": len(cands)}
|
|
if control and any(p.get("control_equal") is False for p in pairs):
|
|
bad = [p["index"] for p in pairs if p.get("control_equal") is False]
|
|
return {"verdict": "INCONCLUSIVE_NONDETERMINISTIC", "reasons": ["two cold runs of the same request differ at request(s) %s" % bad],
|
|
"restored": restored, "restore_candidates": len(cands)}
|
|
differ = [p for p in pairs if not p["equal"]]
|
|
if differ:
|
|
return {"verdict": "FAIL_OUTPUT_DIFFERS", "reasons": ["request %d: %s" % (p["index"], json.dumps(p["diff"])) for p in differ[:10]],
|
|
"restored": restored, "restore_candidates": len(cands)}
|
|
if not cands or restored < min_restore_fraction * len(cands):
|
|
return {"verdict": "INCONCLUSIVE_NO_RESTORE", "reasons": ["the reply arm restored %d of %d requests after the first (need %.0f %%)" % (
|
|
restored, len(cands), 100 * min_restore_fraction)], "restored": restored, "restore_candidates": len(cands)}
|
|
return {"verdict": "PASS", "reasons": reasons, "restored": restored, "restore_candidates": len(cands)}
|
|
|
|
|
|
# ---- the session --------------------------------------------------------------------------------------------------------------------------------
|
|
def message(role, text):
|
|
return {"type": "message", "role": role, "content": [{"type": "input_text" if role != "assistant" else "output_text", "text": text}]}
|
|
|
|
|
|
def load_scenario(args):
|
|
import e2e_client as ec # stdlib-only sibling: TOOLS and the canned tool results of the wire-behaviour scenarios
|
|
tools = ec.TOOLS
|
|
results = dict(ec.TOOL_RESULTS)
|
|
turns = list(DEFAULT_TURNS)
|
|
if args.scenario:
|
|
with open(args.scenario, "r", encoding="utf-8") as fh:
|
|
doc = json.load(fh)
|
|
tools, results, turns = doc.get("tools", tools), doc.get("tool_results", results), doc.get("user_turns", turns)
|
|
context = []
|
|
for path in args.context_file or []:
|
|
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
context.append(message("user", fh.read()))
|
|
return tools, results, turns, context
|
|
|
|
|
|
def request_body(args, tools, history):
|
|
body = {"model": args.model, "input": history, "tools": tools, "tool_choice": "auto", "parallel_tool_calls": False, "store": False,
|
|
"stream": True, "temperature": 0, "max_output_tokens": args.max_output}
|
|
if args.instructions:
|
|
body["instructions"] = args.instructions
|
|
return body
|
|
|
|
|
|
def res_to_json(res):
|
|
return {"items": res["items"], "usage": res["usage"], "status": res["status"], "terminal": res["terminal"], "error": res["error"],
|
|
"arg_deltas": dict((str(k), v) for k, v in res["arg_deltas"].items()), "arg_done": dict((str(k), v) for k, v in res["arg_done"].items())}
|
|
|
|
|
|
def res_from_json(doc):
|
|
return {"items": doc["items"], "usage": doc["usage"], "status": doc["status"], "terminal": doc["terminal"], "error": doc["error"],
|
|
"arg_deltas": dict((int(k), v) for k, v in doc["arg_deltas"].items()), "arg_done": dict((int(k), v) for k, v in doc["arg_done"].items())}
|
|
|
|
|
|
def read_key(args):
|
|
if getattr(args, "key_file", None):
|
|
with open(args.key_file, "r", encoding="utf-8") as fh:
|
|
return fh.read().strip()
|
|
return None
|
|
|
|
|
|
def drive_reply(args, send=stream_request):
|
|
"""Phase 1: the agent session against the REPLY arm only. The history is always built from that arm's own output, as an agent's next request would
|
|
be, so every request after the first can resume from the arm's reply checkpoint. Returns {tools, records}; a record holds the exact request body
|
|
and the arm's response, which phase 2 sends unchanged to the cold arm."""
|
|
key = read_key(args)
|
|
tools, results, turns, history = load_scenario(args)
|
|
records = []
|
|
for turn_no, user_text in enumerate(turns[:args.turns], 1):
|
|
history.append(message("user", user_text))
|
|
for _round in range(MAX_TOOL_ROUNDS):
|
|
body = request_body(args, tools, history)
|
|
reply = send(args.reply_url, key, body)
|
|
records.append({"index": len(records) + 1, "turn": turn_no, "body": json.loads(json.dumps(body)), "reply": res_to_json(reply)}) # a copy: history grows
|
|
if reply["error"]:
|
|
return {"tools": tools, "records": records}
|
|
calls = [it for it in reply["items"] if it.get("type") == "function_call"]
|
|
for it in reply["items"]:
|
|
if it.get("type") == "message":
|
|
history.append(message("assistant", "".join(c.get("text", "") for c in it.get("content", []) if isinstance(c, dict))))
|
|
elif it.get("type") == "function_call":
|
|
history.append({"type": "function_call", "call_id": it.get("call_id"), "name": it.get("name"), "arguments": it.get("arguments")})
|
|
if not calls:
|
|
break
|
|
for it in calls:
|
|
history.append({"type": "function_call_output", "call_id": it.get("call_id"), "output": results.get(it.get("name"), "ok")})
|
|
return {"tools": tools, "records": records}
|
|
|
|
|
|
def score(args, recorded, send=stream_request):
|
|
"""Phase 2: the recorded bodies, unchanged, to the COLD arm (twice with --control); compare, check integrity, judge."""
|
|
key = read_key(args)
|
|
tools = recorded["tools"]
|
|
t0 = time.monotonic()
|
|
pairs = []
|
|
for rc in recorded["records"]:
|
|
reply = res_from_json(rc["reply"])
|
|
body = rc["body"]
|
|
index = rc["index"]
|
|
rec = {"index": index, "turn": rc["turn"], "prompt_items": len(body["input"]), "prompt_sha256": sha256_text(json.dumps(body["input"], sort_keys=True)),
|
|
"error": None}
|
|
if reply["error"]:
|
|
rec["error"] = "reply arm: %s" % reply["error"]
|
|
pairs.append(rec)
|
|
break
|
|
cold = send(args.cold_url, key, body)
|
|
cold2 = send(args.cold_url, key, body) if args.control else None
|
|
if cold["error"]:
|
|
rec["error"] = "cold arm: %s" % cold["error"]
|
|
a, b = normalise(reply["items"]), normalise(cold["items"])
|
|
rec["equal"] = a == b
|
|
rec["diff"] = None if rec["equal"] else first_difference(a, b)
|
|
rec["integrity"] = {"reply": integrity_errors(reply, tools), "cold": integrity_errors(cold, tools)}
|
|
rec["control_equal"] = None if cold2 is None else (normalise(cold2["items"]) == b)
|
|
ru, cu = reply["usage"], cold["usage"]
|
|
cached = lambda u: (u.get("input_tokens_details") or {}).get("cached_tokens") # noqa: E731
|
|
rec["usage"] = {"reply": {"input": ru.get("input_tokens"), "cached": cached(ru), "output": ru.get("output_tokens")},
|
|
"cold": {"input": cu.get("input_tokens"), "cached": cached(cu), "output": cu.get("output_tokens")}}
|
|
rec["restored"] = None
|
|
rec["cold_warm"] = bool(cu.get("input_tokens") and (cached(cu) or 0) >= args.min_cached_fraction * cu.get("input_tokens"))
|
|
if index > 1:
|
|
inp, cch = ru.get("input_tokens"), cached(ru)
|
|
rec["restored"] = bool(inp and cch is not None and cch >= args.min_cached_fraction * inp)
|
|
pairs.append(rec)
|
|
if rec["error"]:
|
|
break
|
|
j = judge(pairs, args.min_restore_fraction, args.control)
|
|
return {"schema": "prefix-tail-equivalence-v1", "verdict": j["verdict"], "reasons": j["reasons"], "restored": j["restored"],
|
|
"restore_candidates": j["restore_candidates"], "requests": len(pairs), "control": bool(args.control),
|
|
"min_cached_fraction": args.min_cached_fraction, "min_restore_fraction": args.min_restore_fraction, "elapsed_s": round(time.monotonic() - t0, 1),
|
|
"tools": [t.get("name") for t in tools], "pairs": pairs}
|
|
|
|
|
|
def run_session(args, send=stream_request):
|
|
"""Both phases in one process (both arms up at the same time: needs room for two servers)."""
|
|
return score(args, drive_reply(args, send), send)
|
|
|
|
|
|
def write_json(path, doc):
|
|
with open(path, "w", encoding="utf-8", newline="\n") as fh:
|
|
fh.write(json.dumps(doc, indent=2) + "\n")
|
|
|
|
|
|
class _Parser(argparse.ArgumentParser):
|
|
def error(self, message):
|
|
sys.stderr.write("%s: error: %s\n" % (self.prog, message))
|
|
raise SystemExit(3)
|
|
|
|
|
|
def add_session_options(p):
|
|
p.add_argument("--model", required=True)
|
|
p.add_argument("--key-file")
|
|
p.add_argument("--scenario", help="JSON {tools, tool_results, user_turns}; default: the tools and canned results of e2e_client.py")
|
|
p.add_argument("--context-file", action="append", help="text prepended as a user message (repeatable); use ~60-70k tokens for the production regime")
|
|
p.add_argument("--instructions")
|
|
p.add_argument("--turns", type=int, default=len(DEFAULT_TURNS))
|
|
p.add_argument("--max-output", type=int, default=512)
|
|
|
|
|
|
def add_score_options(p):
|
|
p.add_argument("--control", action="store_true", help="send every cold request twice (determinism control)")
|
|
p.add_argument("--min-cached-fraction", type=float, default=0.5)
|
|
p.add_argument("--min-restore-fraction", type=float, default=0.8)
|
|
|
|
|
|
def report(result, out):
|
|
write_json(out, result)
|
|
sys.stdout.write("%s: %d requests, restored %d of %d, %s\n" % (result["verdict"], result["requests"], result["restored"], result["restore_candidates"],
|
|
"; ".join(result["reasons"][:3])))
|
|
return EXIT[result["verdict"]]
|
|
|
|
|
|
def main(argv=None):
|
|
parser = _Parser(prog="prefix_tail_equivalence.py", description=__doc__.split("\n")[0])
|
|
sub = parser.add_subparsers(dest="command")
|
|
sub.required = True
|
|
p = sub.add_parser("run", help="both arms up at once: record against the reply arm, replay against the cold arm, judge")
|
|
p.add_argument("--cold-url", required=True)
|
|
p.add_argument("--reply-url", required=True)
|
|
p.add_argument("--out", required=True, help="result JSON (run roots outside Git)")
|
|
add_session_options(p)
|
|
add_score_options(p)
|
|
p = sub.add_parser("record", help="phase 1, reply arm only: drive the session and write the exact requests and the arm's answers")
|
|
p.add_argument("--reply-url", required=True)
|
|
p.add_argument("--record-out", required=True, help="recording JSON (holds prompts and replies: outside Git)")
|
|
add_session_options(p)
|
|
p = sub.add_parser("replay", help="phase 2, cold arm only (restart the server without the cache first): send the recorded requests, judge")
|
|
p.add_argument("--cold-url", required=True)
|
|
p.add_argument("--record", required=True)
|
|
p.add_argument("--key-file")
|
|
p.add_argument("--out", required=True)
|
|
add_score_options(p)
|
|
args = parser.parse_args(argv)
|
|
try:
|
|
if args.command == "run":
|
|
return report(run_session(args), args.out)
|
|
if args.command == "record":
|
|
recorded = drive_reply(args)
|
|
write_json(args.record_out, recorded)
|
|
bad = [r["index"] for r in recorded["records"] if r["reply"]["error"]]
|
|
sys.stdout.write("recorded %d requests%s\n" % (len(recorded["records"]), (", transport error at %s" % bad) if bad else ""))
|
|
return EXIT["ERROR"] if bad else 0
|
|
with open(args.record, "r", encoding="utf-8") as fh:
|
|
recorded = json.load(fh)
|
|
return report(score(args, recorded), args.out)
|
|
except (OSError, ValueError, ImportError) as exc:
|
|
sys.stderr.write("ERROR: %s\n" % exc)
|
|
return EXIT["ERROR"]
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|