okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-142b-serve into f-1426e1085c1d

main
19.7 KiB402 linesraw
1#!/usr/bin/env python3
2"""Replay frozen requests against an already configured, running Strata server.
3
4No launch, restart, model selection, or configuration changes are performed.
5Set STRATA_BENCHMARK_API_KEY if the server needs a bearer token.
6"""
7import argparse
8from datetime import datetime, timezone
9import gzip
10import hashlib
11import http.client
12import json
13import math
14import os
15from pathlib import Path
16import re
17import socket
18import sys
19import threading
20import time
21from urllib.parse import urlsplit
22
23ROOT = Path(__file__).resolve().parent
24SECRET = os.environ.get("STRATA_BENCHMARK_API_KEY", "")
25
26
27def sha(data):
28    return hashlib.sha256(data).hexdigest()
29
30
31def utc():
32    return datetime.now(timezone.utc).isoformat()
33
34
35def error_text(error):
36    text = str(error)
37    return text.replace(SECRET, "[redacted]") if SECRET else text
38
39
40def save(path, value):
41    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
42
43
44class Client:
45    def __init__(self, url, timeout):
46        parsed = urlsplit(url)
47        if (parsed.scheme not in ("http", "https") or not parsed.hostname
48                or parsed.username or parsed.password or parsed.query or parsed.fragment
49                or parsed.path not in ("", "/")):
50            raise ValueError("--url must be an http(s) origin without credentials, path, query, or fragment")
51        self.origin, self.timeout = url.rstrip("/"), timeout
52        self.host, self.port = parsed.hostname, parsed.port
53        self.connection_type = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
54
55    def connection(self, timeout=None):
56        return self.connection_type(self.host, self.port, timeout=timeout or self.timeout)
57
58    def headers(self, streaming=False):
59        headers = {"Content-Type": "application/json"}
60        if streaming:
61            headers["Accept"] = "text/event-stream"
62        if SECRET:
63            headers["Authorization"] = "Bearer " + SECRET
64        return headers
65
66    def json_request(self, method, path, body=None, timeout=None):
67        connection = self.connection(timeout)
68        try:
69            connection.request(method, path, body=body, headers=self.headers())
70            response = connection.getresponse()
71            payload = response.read()
72            if response.status != 200:
73                raise ValueError(f"{method} {path}: HTTP {response.status}: {payload[:4096]!r}")
74            value = json.loads(payload)
75            if not isinstance(value, dict) or "error" in value:
76                raise ValueError(f"{method} {path}: invalid/API error response: {value!r}")
77            return value
78        finally:
79            connection.close()
80
81    def served_state(self):
82        state = {}
83        for path in ("/v1/status", "/health"):
84            try:
85                state[path] = {"response": self.json_request("GET", path, timeout=min(5, self.timeout))}
86            except Exception as error:
87                state[path] = {"error": error_text(error)}
88        return state
89
90    def stream(self, body, directory, row):
91        started = time.monotonic()
92        connection = self.connection()
93        network_socket, timed_out = [], threading.Event()
94
95        def expire():
96            timed_out.set()
97            current = network_socket[0] if network_socket else connection.sock
98            if current is not None:
99                try:
100                    current.shutdown(socket.SHUT_RDWR)
101                except OSError:
102                    pass
103
104        timer = threading.Timer(self.timeout, expire)
105        timer.daemon = True
106        timer.start()
107        done, data = False, []
108        content, reasoning, calls = [], [], {}
109        row.update(content="", reasoning_content="", tool_calls=[], usage={}, timings={},
110                   finish_reason=None, client_ttft_s=None, sse_chunks=0)
111
112        def consume(payload, parsed_log):
113            nonlocal done
114            elapsed = time.monotonic() - started
115            if payload == "[DONE]":
116                done = True
117                parsed_log.write(json.dumps({"elapsed_s": elapsed, "done": True}) + "\n")
118                return
119            chunk = json.loads(payload)
120            parsed_log.write(json.dumps({"elapsed_s": elapsed, "chunk": chunk}, ensure_ascii=False) + "\n")
121            parsed_log.flush()
122            if not isinstance(chunk, dict) or "error" in chunk:
123                raise ValueError(f"Invalid/API error SSE chunk: {chunk!r}")
124            row["sse_chunks"] += 1
125            if "id" in chunk:
126                row["completion_id"] = chunk["id"]
127            for key in ("usage", "timings"):
128                if key in chunk:
129                    if not isinstance(chunk[key], dict):
130                        raise ValueError(f"SSE {key} must be an object")
131                    row[key] = chunk[key]
132            choices = chunk.get("choices", [])
133            if not isinstance(choices, list):
134                raise ValueError("SSE choices must be a list")
135            for choice in choices:
136                if not isinstance(choice, dict) or choice.get("index", 0) != 0:
137                    raise ValueError("Replay supports a single completion (index 0)")
138                if choice.get("finish_reason") is not None:
139                    row["finish_reason"] = choice["finish_reason"]
140                delta = choice.get("delta", {})
141                if not isinstance(delta, dict):
142                    raise ValueError("SSE delta must be an object")
143                nonempty = False
144                for key, target in (("content", content), ("reasoning_content", reasoning)):
145                    value = delta.get(key)
146                    if value is not None and not isinstance(value, str):
147                        raise ValueError(f"Non-string {key} delta")
148                    if value:
149                        target.append(value)
150                        nonempty = True
151                deltas = delta.get("tool_calls", [])
152                if not isinstance(deltas, list):
153                    raise ValueError("SSE tool_calls must be a list")
154                for call in deltas:
155                    if not isinstance(call, dict):
156                        raise ValueError("SSE tool call must be an object")
157                    index = call.get("index", 0)
158                    if type(index) is not int or index < 0:
159                        raise ValueError("Invalid tool-call index")
160                    current = calls.setdefault(index, {"id": "", "type": "function", "function": {"name": "", "arguments": ""}})
161                    function = call.get("function", {})
162                    if not isinstance(function, dict):
163                        raise ValueError("SSE tool-call function must be an object")
164                    for key in ("id", "type"):
165                        if call.get(key):
166                            if not isinstance(call[key], str):
167                                raise ValueError(f"Non-string tool-call {key}")
168                            current[key] = call[key]
169                            nonempty = True
170                    for key in ("name", "arguments"):
171                        if function.get(key):
172                            if not isinstance(function[key], str):
173                                raise ValueError(f"Non-string function {key}")
174                            current["function"][key] += function[key]
175                            nonempty = True
176                if nonempty and row["client_ttft_s"] is None:
177                    row["client_ttft_s"] = elapsed
178
179        try:
180            connection.request("POST", "/v1/chat/completions", body=body, headers=self.headers(streaming=True))
181            if connection.sock is not None:
182                network_socket.append(connection.sock)
183            response = connection.getresponse()
184            row["http_status"] = response.status
185            if response.status != 200:
186                payload = response.read(4096)
187                (directory / "http-error.bin").write_bytes(payload)
188                raise ValueError(f"POST /v1/chat/completions: HTTP {response.status}: {payload!r}")
189            if not response.getheader("Content-Type", "").lower().startswith("text/event-stream"):
190                payload = response.read(4096)
191                (directory / "http-error.bin").write_bytes(payload)
192                raise ValueError(f"Expected text/event-stream, got {payload!r}")
193            with (directory / "response.sse").open("wb") as raw, (directory / "stream.jsonl").open("w", encoding="utf-8") as parsed:
194                while not done:
195                    remaining = self.timeout - (time.monotonic() - started)
196                    if timed_out.is_set() or remaining <= 0:
197                        raise TimeoutError("Absolute request timeout exceeded")
198                    if network_socket:
199                        network_socket[0].settimeout(remaining)
200                    line = response.readline(2 * 1024 * 1024 + 1)
201                    if not line:
202                        if data:
203                            consume("\n".join(data), parsed)
204                        break
205                    raw.write(line)
206                    raw.flush()
207                    if len(line) > 2 * 1024 * 1024:
208                        raise ValueError("SSE line exceeds 2 MiB")
209                    text = line.decode("utf-8").rstrip("\r\n")
210                    if not text:
211                        if data:
212                            consume("\n".join(data), parsed)
213                            data = []
214                    elif not text.startswith(":"):
215                        field, separator, value = text.partition(":")
216                        if separator and value.startswith(" "):
217                            value = value[1:]
218                        if field == "data":
219                            data.append(value)
220                if timed_out.is_set():
221                    raise TimeoutError("Absolute request timeout exceeded")
222                if not done or row["finish_reason"] is None or not row["usage"]:
223                    raise ValueError("Incomplete SSE: [DONE], finish reason, and usage are required")
224        except Exception:
225            if timed_out.is_set():
226                raise TimeoutError("Absolute request timeout exceeded") from None
227            raise
228        finally:
229            timer.cancel()
230            connection.close()
231            row.update(content="".join(content), reasoning_content="".join(reasoning),
232                       tool_calls=[calls[index] for index in sorted(calls)],
233                       client_total_s=time.monotonic() - started)
234
235
236def frozen(entry):
237    path = (ROOT / entry["path"]).resolve()
238    if not path.is_relative_to(ROOT) or path.suffix != ".gz":
239        raise ValueError("Frozen request path must be a .gz file inside the report")
240    body = gzip.decompress(path.read_bytes())
241    if sha(body) != entry["request_sha256"]:
242        raise ValueError("Frozen request SHA-256 mismatch: " + str(entry["id"]))
243    request = json.loads(body)
244    if not isinstance(request, dict) or request.get("stream") is not True:
245        raise ValueError("Frozen request must be a streaming JSON object")
246    return body, request
247
248
249def rates(row):
250    timings = row["timings"]
251    row["reused_prompt_tokens"] = timings.get("cache_n")
252    row["fresh_prompt_tokens"] = timings.get("prompt_n")
253    for target, count, elapsed in (("engine_prefill_tok_s", "prompt_n", "prompt_ms"),
254                                   ("engine_decode_tok_s", "predicted_n", "predicted_ms")):
255        n, ms = timings.get(count), timings.get(elapsed)
256        row[target] = n * 1000 / ms if type(n) in (int, float) and type(ms) in (int, float) and n >= 0 and ms > 0 else None
257
258
259def eligibility(entry, request, row):
260    reasons, expected = [], entry["expected_prompt_tokens"]
261    if row["usage"].get("prompt_tokens") != expected:
262        reasons.append("usage prompt_tokens differs from frozen expectation")
263    reused, fresh = row.get("reused_prompt_tokens"), row.get("fresh_prompt_tokens")
264    if type(reused) is not int or type(fresh) is not int or fresh + reused != expected:
265        reasons.append("timings prompt_n + cache_n differs from frozen expectation")
266    measured = entry["role"] == "measured"
267    if entry["suite"] == "decode":
268        if measured and (type(reused) is not int or reused / expected < .999):
269            reasons.append("decode reused less than 99.9% of the frozen prefix")
270    elif entry["role"] != "continuation" and reused != 0:
271        reasons.append("fresh request unexpectedly reused prompt tokens")
272    if measured:
273        generated = entry.get("expected_completion_tokens", 512)
274        if row["finish_reason"] != "length" or row["usage"].get("completion_tokens") != generated or row["timings"].get("predicted_n") != generated:
275            reasons.append("measured completion did not consume the exact fixed decode budget")
276    if row.get("engine_prefill_tok_s") is None or row.get("engine_decode_tok_s") is None:
277        reasons.append("engine throughput timings are unavailable or invalid")
278    if entry["suite"] == "disk":
279        if row["finish_reason"] != "stop":
280            reasons.append("disk request did not finish at EOS")
281        previous = entry.get("previous_prefix_tokens")
282        if entry["role"] == "continuation" and previous is not None:
283            ratio = reused / previous if type(reused) is int and previous > 0 else None
284            row["previous_prefix_reuse_fraction"] = ratio
285            if ratio is None or ratio < .99:
286                reasons.append("disk continuation reused less than 99% of the previous prefix")
287        if "expected_needles" in entry:
288            try:
289                actual = json.loads(row["content"])
290            except ValueError:
291                actual = None
292            row["needle_grade"] = {"expected": entry["expected_needles"], "actual": actual,
293                                   "passed": actual == entry["expected_needles"]}
294            if not row["needle_grade"]["passed"]:
295                reasons.append("disk answer differs from the eight frozen needle values")
296    return reasons
297
298
299def selected(entries, args):
300    rows = [entry for entry in entries if entry["suite"] == args.suite]
301    if args.suite == "disk":
302        rows = [entry for entry in rows if entry["role"] == args.disk_phase
303                and (args.depth is None or entry["depth"] == args.depth)
304                and (args.round is None or entry["round"] == args.round)]
305    elif args.suite == "decode":
306        rows = [entry for entry in rows if args.round is None or entry["round"] == args.round]
307    else:
308        warmups = [entry for entry in rows if entry["role"] == "warmup"]
309        measured = [entry for entry in rows if entry["role"] == "measured"
310                    and (args.round is None or entry["round"] == args.round)]
311        rows = warmups + measured if measured else []
312    if not rows:
313        raise ValueError("No requests match the selected suite/round/depth/phase")
314    return rows
315
316
317def main():
318    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
319    parser.add_argument("--url", default="http://127.0.0.1:18089")
320    parser.add_argument("--suite", choices=("confirmation", "screen", "decode", "disk"))
321    parser.add_argument("--round", type=int)
322    parser.add_argument("--depth", type=int, help="Disk suite depth filter")
323    parser.add_argument("--disk-phase", choices=("initial", "continuation"), default="initial")
324    parser.add_argument("--out", type=Path, required=True, help="New output directory; never overwritten")
325    parser.add_argument("--timeout", type=float, default=120, help="Per-request seconds, at least 1 (1M initial needs a larger value)")
326    parser.add_argument("--slot-action", choices=("save", "restore"), help="Only perform this native slot action; no replay or restart")
327    parser.add_argument("--slot-filename", help="Explicit safe regular-file basename inside the server's configured slot-save directory")
328    args = parser.parse_args()
329    if args.out.exists():
330        parser.error("--out must be a new directory")
331    args.out.mkdir(parents=True)
332    run = {"started_at_utc": utc(), "harness_sha256": sha(Path(__file__).read_bytes()),
333           "url": args.url, "suite": args.suite, "round": args.round, "depth": args.depth,
334           "disk_phase": args.disk_phase, "timeout_s": args.timeout, "results": [], "status": "running"}
335    try:
336        if not math.isfinite(args.timeout) or args.timeout < 1:
337            raise ValueError("--timeout must be finite and at least 1 second")
338        client = Client(args.url, args.timeout)
339        if args.slot_action:
340            name = args.slot_filename or ""
341            if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,254}", name) or ".." in name:
342                raise ValueError("--slot-filename must be an explicit safe regular-file basename")
343            run["served_before"] = client.served_state()
344            started = time.monotonic()
345            action = {"action": args.slot_action, "filename": name, "status": "running"}
346            run["slot_action"] = action
347            try:
348                action["response"] = client.json_request("POST", "/slots/0?action=" + args.slot_action,
349                                                         json.dumps({"filename": name}).encode())
350                action["status"] = "completed"
351            except Exception as error:
352                action.update(status="failed", error=error_text(error))
353                raise
354            finally:
355                action["client_total_s"] = time.monotonic() - started
356                run["served_after"] = client.served_state()
357        else:
358            if not args.suite or args.slot_filename:
359                raise ValueError("Use --suite for replay, or --slot-action with --slot-filename")
360            index_path = ROOT / "requests/index.json"
361            index_bytes = index_path.read_bytes()
362            run["index_sha256"] = sha(index_bytes)
363            entries = selected(json.loads(index_bytes)["requests"], args)
364            # Preflight every chosen file before sending even the warmup.
365            for entry in entries:
366                frozen(entry)
367            for ordinal, entry in enumerate(entries):
368                directory = args.out / (f"{ordinal:03d}-" + re.sub(r"[^A-Za-z0-9_.-]", "_", str(entry["id"]))[:100])
369                directory.mkdir()
370                row = {"request": entry, "harness_sha256": run["harness_sha256"],
371                       "started_at_utc": utc(), "status": "running", "eligible": False,
372                       "served_before": client.served_state()}
373                run["results"].append(row)
374                try:
375                    body, request = frozen(entry)
376                    client.stream(body, directory, row)
377                    rates(row)
378                    reasons = eligibility(entry, request, row)
379                    row.update(status="completed", eligible=not reasons, ineligible_reasons=reasons)
380                except Exception as error:
381                    row.update(status="failed", error=error_text(error), eligible=False)
382                finally:
383                    row.update(finished_at_utc=utc(), served_after=client.served_state())
384                    save(directory / "result.json", row)
385                    save(args.out / "run.json", run)
386                print(f"{entry['id']}: {row['status']}, eligible={row['eligible']}", flush=True)
387                if row["status"] == "failed":
388                    break
389            if any(not row["eligible"] for row in run["results"]):
390                raise ValueError("One or more replay requests failed or were ineligible; inspect actual outputs")
391        run["status"] = "completed"
392    except Exception as error:
393        run.update(status="failed", error=error_text(error))
394        print(run["error"], file=sys.stderr)
395    finally:
396        run["finished_at_utc"] = utc()
397        save(args.out / "run.json", run)
398    return 0 if run["status"] == "completed" else 1
399
400
401if __name__ == "__main__":
402    sys.exit(main())