Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
test(benchmarks): measure fixed-length SDK chat decode streams (#801)
svonava70e6d860ad31
diff --git a/tools/benchmarks/stream_decode/README.md b/tools/benchmarks/stream_decode/README.mdnew file mode 100644index 000000000..4a56c5cd3--- /dev/null+++ b/tools/benchmarks/stream_decode/README.md@@ -0,0 +1,103 @@+# Single-stream decode benchmark++This records fixed-length, serial chat completions through `sie_sdk.SIEClient`+and SIE's actual `/v1/chat/completions` proxy. It addresses the measurement part+of [#435](https://github.com/superlinked/sie/issues/435). It does not yet contain+a qualified GPU result or justify a performance change.++The dedicated benchmark server observes SGLang 0.5.20 inside its child process.+It chains SIE's production startup hooks, then observes+`TokenizerManager._tokenize_one_request` and `generate_request`. Native SIE+`adapter.generate` instrumentation cannot observe this chat route.++The observer retains actual prepared input IDs, effective sampling, raw output+events and cumulative completion counts. SDK chunk IDs must match the backend+request ID. Prompt, model, source manifest, clock domain and fixed trial count+must also match. Each call writes one initial occupancy record; events stay in+memory until stream completion or cancellation. No per-event file writes or+retokenization occur. This instrumentation adds host+overhead and must be identical in every compared arm.++## Run in a dedicated, bounded Linux GPU environment++Use a frozen public checkpoint, server configuration and environment. Preload+the model and verify readiness before admitting the client. Own the server's+process group and enforce an external absolute deadline, including teardown.+The benchmark wrapper does not allocate GPUs or supervise server lifetime.+Use public synthetic prompts: raw requests and outputs are retained as evidence.++From a clean checkout with the pinned CUDA13/SGLang bundle installed:++```sh+mise exec -- python -m tools.benchmarks.stream_decode.server \+ --trace-directory /tmp/decode-a-server --cohort decode-a -- \+ serve --host 127.0.0.1 --port 8080 --device cuda:0 \+ --models-dir /tmp/frozen-model-configs \+ --models Qwen/Qwen3.8-27B-FP8 --preload Qwen/Qwen3.8-27B-FP8++# In another shell, after model readiness and observer installation:+mise exec -- python -m tools.benchmarks.stream_decode.client \+ --url http://127.0.0.1:8080 --model Qwen/Qwen3.8-27B-FP8 \+ --prompt /tmp/fixed-public-prompt.txt \+ --server-manifest /tmp/decode-a-server/server.json \+ --output /tmp/decode-a-client --completion-tokens 128 \+ --warmups 2 --repeats 6 --request-seconds 120 --total-seconds 1200++mise exec -- python -m tools.benchmarks.stream_decode.analysis \+ --client-directory /tmp/decode-a-client \+ --server-directory /tmp/decode-a-server \+ --prompt-tokens 670 --completion-tokens 128 \+ --output /tmp/decode-a-analysis.json+```++The prompt-token count above is an example: freeze the actual chat-template+token count before the experiment. A mismatch invalidates the cohort. Use a+new directory and cohort for each planned arm; retain failed attempts. The+client requests greedy sampling, a fixed seed, reasoning off, and equal+minimum/maximum output tokens. Operator template settings remain authoritative;+analysis rejects a run that enabled thinking or changed these settings.++Each request runs in a fresh child with its own wall deadline, plus bounded+parent termination/reaping. HTTP proxies and remote fallback are disabled.+There is no retry after an admitted failed stream. Client construction and+post-request file writes are outside the client timing interval.++## Interpret the measurements++Client TTFT is the time until the first visible text delta. Total latency runs+from request iteration to completed stream. Completion tokens divided by total+latency includes TTFT and is reported separately.++Decode rate uses actual cumulative completion counts and host observation+timestamps before chat formatting: `(last_count - first_count) / elapsed`.+After-first-token rate is available only when the first observed count is+exactly one. SGLang may coalesce outputs, particularly with speculative+decoding; a first count above one produces only an after-first-observation rate.+An SSE event is never assumed to represent one token. These timestamps are not+GPU kernel timings. Kernel profiling belongs in separate fixed calls so profiler+overhead cannot silently enter timing measurements.++The analyzer rejects incomplete streams, retries, wrong lengths, mismatched+IDs/text, malformed or regressing counts, missing usage, changed prepared inputs,+overlapping trials and extra backend requests inside the measured schedule.+Native startup and health generations pass through unchanged; their intervals+are retained, and any overlap with the measured schedule invalidates the run.+Engine cleanup may finish after the SDK receives its terminal response; all+recorded engine events must still lie inside both applicable timing intervals.++CPU controls exercise the actual SIE CUDA chat route with a synthetic child,+the real SDK over local HTTP, concurrent observation/cancellation, startup-hook+restoration, child deadlines, and negative evidence cases. They do not establish+GPU correctness, kernel performance or model quality.++```sh+mise run test -- tools/benchmarks/stream_decode+mise exec -- ruff check tools/benchmarks/stream_decode+mise exec -- ruff format --check tools/benchmarks/stream_decode+```++Reviewed upstream boundary: [SGLang 0.5.20 TokenizerManager](https://github.com/sgl-project/sglang/blob/v0.5.20/python/sglang/srt/managers/tokenizer_manager.py)+and [chat formatting](https://github.com/sgl-project/sglang/blob/v0.5.20/python/sglang/srt/entrypoints/openai/serving_chat.py),+including [sampling normalization](https://github.com/sgl-project/sglang/blob/v0.5.20/python/sglang/srt/sampling/sampling_params.py).+All three installed sources must match the checked-in hashes before observation.+The client requires a matching observer installation record before sending requests.diff --git a/tools/benchmarks/stream_decode/__init__.py b/tools/benchmarks/stream_decode/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tools/benchmarks/stream_decode/_hooks/__init__.py b/tools/benchmarks/stream_decode/_hooks/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tools/benchmarks/stream_decode/_hooks/sitecustomize.py b/tools/benchmarks/stream_decode/_hooks/sitecustomize.pynew file mode 100644index 000000000..5c36052cb--- /dev/null+++ b/tools/benchmarks/stream_decode/_hooks/sitecustomize.py@@ -0,0 +1,6 @@+"""Preserve production child compatibility hooks before installing observation."""++import importlib++importlib.import_module("sie_server.adapters.sglang._compat.sitecustomize")+importlib.import_module("tools.benchmarks.stream_decode.observer").install()diff --git a/tools/benchmarks/stream_decode/analysis.py b/tools/benchmarks/stream_decode/analysis.pynew file mode 100644index 000000000..df63e37e6--- /dev/null+++ b/tools/benchmarks/stream_decode/analysis.py@@ -0,0 +1,321 @@+"""Compute count-based decode rates without treating SSE events as tokens."""++from __future__ import annotations++import argparse+import hashlib+import json+import math+import statistics+from pathlib import Path+from typing import Any++from tools.benchmarks.stream_decode.observer import SOURCE_FILES, SOURCE_SHA256, VERSION, digest, save++MIN_OBSERVATIONS = 2+++def require(condition: bool, message: str) -> None:+ if not condition:+ raise ValueError(message)+++def count(value: Any) -> bool:+ return type(value) is int and value >= 0+++def analyze_trial(+ client: dict[str, Any], backend: dict[str, Any], prompt_tokens: int, output_tokens: int+) -> dict[str, Any]:+ require(client.get("completed") is True and backend.get("completed") is True, "incomplete stream")+ require(client.get("retry_count") == 0 and client.get("http_requests") == 1, "retried or multiple HTTP requests")+ require(+ bool(client.get("clock_domain")) and client["clock_domain"] == backend.get("clock_domain"),+ "different or unknown clock domain",+ )+ start, end = client["started_ns"], client["finished_ns"]+ require(type(start) is int and type(end) is int and start < end, "invalid client interval")+ backend_start, backend_end = backend["started_ns"], backend["finished_ns"]+ require(+ type(backend_start) is int and type(backend_end) is int and backend_start < backend_end,+ "invalid backend interval",+ )+ require(start <= backend_start <= end, "backend call outside client interval")+ chunks = client["chunks"]+ require(bool(chunks), "missing SDK chunks")+ text, first_visible, last_visible = "", None, None+ usage = []+ finishes = []+ client_ids = set()+ previous = start+ for row in chunks:+ at = row["at_ns"]+ require(type(at) is int and previous <= at <= end, "invalid SDK chunk clock")+ previous = at+ chunk = row["chunk"]+ require(isinstance(chunk, dict), "invalid SDK chunk")+ require(isinstance(chunk.get("id"), str) and bool(chunk["id"]), "missing SDK request id")+ client_ids.add(chunk["id"])+ if chunk.get("usage") is not None:+ usage.append(chunk["usage"])+ choices = chunk.get("choices")+ require(isinstance(choices, list) and len(choices) <= 1, "expected one completion")+ if not choices:+ continue+ choice = choices[0]+ require(choice.get("index") == 0, "unexpected completion index")+ delta = choice.get("delta", {})+ require(+ not delta.get("reasoning_content") and not delta.get("tool_calls"),+ "benchmark requires plain answer-only text",+ )+ content = delta.get("content")+ require(content is None or isinstance(content, str), "invalid text delta")+ if content:+ text += content+ first_visible = at if first_visible is None else first_visible+ last_visible = at+ if choice.get("finish_reason") is not None:+ finishes.append(choice["finish_reason"])+ require(first_visible is not None and last_visible is not None, "no visible output")+ require(finishes == ["length"], "output did not reach its fixed token cap")+ require(len(usage) == 1, "terminal usage absent or duplicated")+ require(+ all(+ count(u.get("prompt_tokens"))+ and count(u.get("completion_tokens"))+ and u["prompt_tokens"] == prompt_tokens+ and u["completion_tokens"] == output_tokens+ for u in usage+ ),+ "prompt or completion length differs from fixed protocol",+ )+ events = backend["events"]+ require(bool(events), "backend token events absent")+ advances = []+ previous_count, previous_text, previous_time = 0, "", backend["started_ns"]+ terminal = []+ identifiers = set()+ incremental = backend.get("incremental_streaming_output")+ require(type(incremental) is bool, "unknown backend streaming mode")+ for row in events:+ at, event = row["at_ns"], row["event"]+ require(type(at) is int and previous_time <= at <= min(end, backend_end), "invalid backend event clock")+ previous_time = at+ require(isinstance(event, dict) and isinstance(event.get("meta_info"), dict), "invalid backend event")+ meta = event["meta_info"]+ tokens = meta.get("completion_tokens")+ require(+ count(tokens) and previous_count <= tokens <= output_tokens, "missing or regressing backend token count"+ )+ require(+ count(meta.get("prompt_tokens")) and meta["prompt_tokens"] == prompt_tokens, "backend prompt length changed"+ )+ cumulative = event.get("text")+ require(isinstance(cumulative, str), "missing backend text")+ if incremental:+ cumulative = previous_text + cumulative+ require(isinstance(cumulative, str) and cumulative.startswith(previous_text), "backend text is not cumulative")+ if tokens > previous_count:+ advances.append({"at_ns": at, "tokens": tokens, "new_tokens": tokens - previous_count})+ previous_count, previous_text = tokens, cumulative+ require(isinstance(meta.get("id"), str) and bool(meta["id"]), "missing backend request id")+ identifiers.add(meta["id"])+ finish = meta.get("finish_reason")+ if isinstance(finish, dict):+ finish = finish.get("type")+ if finish is not None:+ terminal.append(finish)+ require(len(identifiers) == 1 and client_ids == identifiers, "mixed or mismatched stream request ids")+ require(terminal == ["length"] and previous_count == output_tokens, "backend stream incomplete or wrong length")+ require(previous_text == text, "SDK and backend output differ")+ require(len(advances) >= MIN_OBSERVATIONS, "too few token observations to measure decode")+ first, last = advances[0], advances[-1]+ interval = (last["at_ns"] - first["at_ns"]) / 1e9+ require(math.isfinite(interval) and interval > 0, "nonpositive decode interval")+ rate = (last["tokens"] - first["tokens"]) / interval+ return {+ "client_ttft_s": (first_visible - start) / 1e9,+ "client_total_s": (end - start) / 1e9,+ "completion_tokens_per_total_s": output_tokens / ((end - start) / 1e9),+ "backend_first_observation_tokens": first["tokens"],+ "backend_decode_interval_s": interval,+ "backend_after_first_observation_tokens_per_s": rate,+ "backend_after_first_token_tokens_per_s": rate if first["tokens"] == 1 else None,+ "exact_first_token_observed": first["tokens"] == 1,+ "backend_token_advance_groups": len(advances),+ "largest_token_advance_group": max(a["new_tokens"] for a in advances),+ "prompt_tokens": prompt_tokens,+ "completion_tokens": output_tokens,+ "output_sha256": hashlib.sha256(text.encode()).hexdigest(),+ }+++def bindings(client: dict[str, Any], backend: dict[str, Any], plan: dict[str, Any], prompt_tokens: int) -> str:+ """Check the actual wire request and prepared engine input, independently."""+ require(client.get("plan_sha256") == digest(plan), "client plan changed")+ require(client.get("clock_domain") == plan["clock_domain"], "planned clock domain changed")+ require(client.get("cohort") == backend.get("cohort") == plan["cohort"], "cohort changed")+ require(backend.get("server_manifest_sha256") == plan["server_manifest_sha256"], "server source changed")+ require(+ backend.get("source_sha256") == SOURCE_SHA256 and backend.get("version") == VERSION, "unreviewed engine source"+ )+ wire, child = client["request_body"], backend["chat_body"]+ messages = [{"role": "user", "content": plan["prompt"]}]+ require(wire.get("model") == plan["model"], "SDK model changed")+ require(child.get("model") == backend["served_model_name"], "child model changed")+ require(wire.get("messages") == child.get("messages") == messages, "prompt changed")+ for name, expected in plan["sampling"].items():+ require(wire.get(name) == child.get(name) == expected, f"wire sampling changed: {name}")+ for body in (wire, child):+ require(+ body.get("stream") is True and body.get("stream_options") == {"include_usage": True},+ "stream contract changed",+ )+ require(body.get("chat_template_kwargs", {}).get("enable_thinking") is False, "thinking was not disabled")+ tokenized = backend["tokenized"]+ ids = tokenized["input_ids"]+ require(+ isinstance(ids, list) and len(ids) == prompt_tokens and all(count(i) for i in ids),+ "prepared prompt tokens differ",+ )+ require(tokenized["has_multimodal_inputs"] is False, "unexpected multimodal input")+ require(+ {tokenized["rid"]} == {row["event"]["meta_info"]["id"] for row in backend["events"]},+ "prepared request id differs",+ )+ effective = tokenized["sampling"]+ expected = {+ "temperature": 1.0,+ "top_p": 1.0,+ "top_k": 1,+ "min_p": 0.0,+ "presence_penalty": 0.0,+ "frequency_penalty": 0.0,+ "repetition_penalty": 1.0,+ "sampling_seed": 17,+ "n": 1,+ "min_new_tokens": plan["completion_tokens"],+ "max_new_tokens": plan["completion_tokens"],+ }+ require(all(effective.get(k) == v for k, v in expected.items()), "effective sampling changed")+ require(+ all(+ effective.get(k) is None+ for k in ("json_schema", "regex", "ebnf", "structural_tag", "custom_params", "logit_bias")+ ),+ "unexpected constrained sampling",+ )+ # IDs vary per request; model, full prepared IDs and sampling must not.+ return digest(+ {+ "model_path": backend["model_path"],+ "served_model_name": backend["served_model_name"],+ "input_ids": ids,+ "sampling": effective,+ "adapted_sampling": backend["adapted_sampling"],+ "chat_body": child,+ }+ )+++def analyze(client_dir: Path, server_dir: Path, prompt_tokens: int, output_tokens: int) -> dict[str, Any]:+ plan = json.loads((client_dir / "plan.json").read_text())+ manifest = json.loads((server_dir / "server.json").read_text())+ require(digest(manifest) == plan["server_manifest_sha256"], "server manifest changed")+ require(plan["cohort"] == manifest["cohort"], "server cohort differs")+ require(plan["prompt_sha256"] == hashlib.sha256(plan["prompt"].encode()).hexdigest(), "prompt hash differs")+ require(plan["completion_tokens"] == output_tokens, "output length differs from client plan")+ controller = json.loads((client_dir / "controller.json").read_text())+ require(controller.get("completed") is True, "controller incomplete")+ children = controller["children"]+ require(+ len(children) == plan["warmups"] + plan["repeats"]+ and all(+ row["index"] == i and row["returncode"] == 0 and row["timed_out"] is False and not row["signals"]+ for i, row in enumerate(children)+ ),+ "failed or missing child",+ )+ clients = [json.loads(p.read_text()) for p in sorted(client_dir.glob("trial-*.json"))]+ require(len(clients) == plan["warmups"] + plan["repeats"], "missing or extra client trials")+ servers = [json.loads(p.read_text()) for p in sorted(server_dir.glob("stream-*.json"))]+ installed = {row["pid"]: row for row in (json.loads(p.read_text()) for p in server_dir.glob("installed-*.json"))}+ matched = set()+ signatures = set()+ rows = []+ for index, client in enumerate(clients):+ require(client["index"] == index and client["warmup"] == (index < plan["warmups"]), "trial order changed")+ if index:+ require(clients[index - 1]["finished_ns"] <= client["started_ns"], "client trials overlap")+ ids = {row["chunk"].get("id") for row in client["chunks"]}+ require(len(ids) == 1 and None not in ids, "missing or mixed SDK ids")+ candidates = [s for s in servers if {row["event"].get("meta_info", {}).get("id") for row in s["events"]} == ids]+ require(len(candidates) == 1, "client interval does not bind exactly one backend stream")+ server = candidates[0]+ require(server["id"] not in matched, "backend stream reused")+ matched.add(server["id"])+ marker = installed.get(server["pid"], {})+ require(+ marker.get("server_manifest_sha256") == plan["server_manifest_sha256"]+ and marker.get("source_sha256") == SOURCE_SHA256+ and marker.get("source_files") == SOURCE_FILES+ and marker.get("version") == VERSION,+ "matching observer installation absent",+ )+ signatures.add(bindings(client, server, plan, prompt_tokens))+ rows.append(+ {+ "index": index,+ "warmup": client["warmup"],+ "backend_id": server["id"],+ **analyze_trial(client, server, prompt_tokens, output_tokens),+ }+ )+ measured = [r for r in rows if not r["warmup"]]+ require(bool(measured), "no measured trials")+ require(len(signatures) == 1, "prepared input/model/sampling changed between trials")++ def overlaps(record: dict[str, Any]) -> bool:+ start, end = record["started_ns"], record["finished_ns"]+ require(+ type(start) is int and (end is None or (type(end) is int and end >= start)),+ "invalid background interval",+ )+ require(record["clock_domain"] == plan["clock_domain"], "background clock domain differs")+ return start <= clients[-1]["finished_ns"] and (end is None or end >= clients[0]["started_ns"])++ inside_window = [s for s in servers if overlaps(s)]+ require(len(inside_window) == len(matched), "unexpected backend stream during measured schedule")+ background = [json.loads(p.read_text()) for p in sorted(server_dir.glob("background-*.json"))]+ require(not any(overlaps(row) for row in background), "background generation overlaps measured schedule")+ return {+ "valid": True,+ "trials": rows,+ "measured_trials": len(measured),+ "client_ttft_median_s": statistics.median(r["client_ttft_s"] for r in measured),+ "after_first_observation_median_tokens_per_s": statistics.median(+ r["backend_after_first_observation_tokens_per_s"] for r in measured+ ),+ "exact_first_token_observed_in_all_trials": all(r["exact_first_token_observed"] for r in rows),+ "unmatched_backend_streams": len(servers) - len(matched),+ "background_calls_outside_schedule": len(background),+ "prepared_request_sha256": next(iter(signatures)),+ "server_manifest_sha256": digest(manifest),+ "scope": "Instrumented local SIE SDK chat streaming; cumulative token counts and host timestamps observed at SGLang TokenizerManager before chat formatting. TTFT is first visible SDK text. No one-token-per-SSE assumption, tokenization estimate, GPU kernel-time claim or speedup inference.",+ }+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--client-directory", type=Path, required=True)+ parser.add_argument("--server-directory", type=Path, required=True)+ parser.add_argument("--prompt-tokens", type=int, required=True)+ parser.add_argument("--completion-tokens", type=int, required=True)+ parser.add_argument("--output", type=Path, required=True)+ args = parser.parse_args()+ save(args.output, analyze(args.client_directory, args.server_directory, args.prompt_tokens, args.completion_tokens))+++if __name__ == "__main__":+ main()diff --git a/tools/benchmarks/stream_decode/client.py b/tools/benchmarks/stream_decode/client.pynew file mode 100644index 000000000..64b1d94a2--- /dev/null+++ b/tools/benchmarks/stream_decode/client.py@@ -0,0 +1,266 @@+"""Record fixed-length, serial SDK chat streams with bounded child lifetimes."""++from __future__ import annotations++import argparse+import contextlib+import hashlib+import json+import math+import signal+import subprocess+import sys+import time+from collections.abc import Iterator+from pathlib import Path+from types import GeneratorType+from typing import Any+from urllib.parse import urlsplit++import httpx+from sie_sdk import SIEClient++from tools.benchmarks.stream_decode.analysis import require+from tools.benchmarks.stream_decode.observer import MAX_EVENTS, SOURCE_FILES, VERSION, clock_domain, digest, save++MIN_TOKENS, MAX_TOKENS = 2, 4096+MAX_TRIALS, MAX_REQUEST_SECONDS = 100, 600+CHILD_CLEANUP_SECONDS = 6+++def child_deadline(seconds: float) -> Iterator[None]:+ """A wall deadline survives parent death and a stream of tiny HTTP reads."""++ def expired(_signum: int, _frame: Any) -> None:+ raise TimeoutError("fixed child wall deadline expired")++ previous = signal.signal(signal.SIGALRM, expired)+ signal.setitimer(signal.ITIMER_REAL, seconds)+ try:+ yield+ finally:+ signal.setitimer(signal.ITIMER_REAL, 0)+ signal.signal(signal.SIGALRM, previous)+++def one(plan: dict[str, Any], index: int, output: Path) -> None:+ """A fresh process owns one stream, its partial record, and no retry."""+ record: dict[str, Any] = {+ "index": index,+ "warmup": index < plan["warmups"],+ "completed": False,+ "clock_domain": clock_domain(),+ "chunks": [],+ "http_requests": 0,+ "plan_sha256": digest(plan),+ "cohort": plan["cohort"],+ }++ def request(req: httpx.Request) -> None:+ record["http_requests"] += 1+ require(record["http_requests"] == 1, "benchmark refuses a second HTTP attempt")+ require(req.url.path == "/v1/chat/completions", "unexpected SDK endpoint")+ record["request_body"] = json.loads(req.content)++ def interrupted(_signum: int, _frame: Any) -> None:+ raise TimeoutError("fixed per-request deadline expired")++ previous = signal.signal(signal.SIGTERM, interrupted)+ record["started_ns"] = time.perf_counter_ns()+ try:+ with (+ child_deadline(plan["request_seconds"]),+ httpx.Client(base_url=plan["url"], trust_env=False, event_hooks={"request": [request]}) as http,+ SIEClient(plan["url"], remote="forbid", timeout_s=plan["request_seconds"], http_client=http) as client,+ ):+ stream = client.stream_chat_completions(+ plan["model"],+ [{"role": "user", "content": plan["prompt"]}],+ max_completion_tokens=plan["completion_tokens"],+ temperature=0,+ top_p=1,+ top_k=1,+ presence_penalty=0,+ frequency_penalty=0,+ repetition_penalty=1,+ seed=17,+ stream_options={"include_usage": True},+ include_reasoning=False,+ extra_body={+ "min_tokens": plan["completion_tokens"],+ "chat_template_kwargs": {"enable_thinking": False},+ },+ wait_for_capacity=False,+ max_oom_retries=0,+ provision_timeout_s=plan["request_seconds"],+ )+ if not isinstance(stream, GeneratorType):+ raise TypeError("the SDK stream must support deterministic generator closure")+ # Client construction is outside the timed request.+ record["started_ns"] = time.perf_counter_ns()+ try:+ with contextlib.closing(stream):+ for chunk in stream:+ at_ns = time.perf_counter_ns()+ record["chunks"].append({"at_ns": at_ns, "chunk": chunk})+ require(len(record["chunks"]) <= MAX_EVENTS, "SDK stream exceeded fixed event bound")+ record["finished_ns"] = time.perf_counter_ns()+ record["completed"] = True+ finally:+ record["retry_count"] = client.last_retry_count+ except BaseException as error:+ record["error"] = {"type": type(error).__name__, "message": str(error)}+ raise+ finally:+ record.setdefault("finished_ns", time.perf_counter_ns())+ signal.signal(signal.SIGTERM, previous)+ save(output, record)+++def stop_child(process: subprocess.Popen[Any]) -> list[str]:+ signals = []+ if process.poll() is None:+ with contextlib.suppress(ProcessLookupError):+ process.terminate()+ signals.append("SIGTERM")+ try:+ process.wait(timeout=3)+ except subprocess.TimeoutExpired:+ with contextlib.suppress(ProcessLookupError):+ process.kill()+ signals.append("SIGKILL")+ process.wait(timeout=3)+ return signals+++def run(args: argparse.Namespace) -> None:+ target = urlsplit(args.url)+ require(+ target.scheme == "http" and target.hostname in {"127.0.0.1", "localhost", "::1"},+ "benchmark client requires its dedicated local HTTP server",+ )+ require(+ target.username is None and target.password is None and not target.query and not target.fragment,+ "URL must not contain credentials, query, or fragment",+ )+ require(MIN_TOKENS <= args.completion_tokens <= MAX_TOKENS, "completion token count must be between 2 and 4096")+ require(0 <= args.warmups <= MAX_TRIALS and 1 <= args.repeats <= MAX_TRIALS, "invalid fixed trial count")+ require(+ math.isfinite(args.total_seconds)+ and 0 < args.request_seconds <= MAX_REQUEST_SECONDS+ and args.total_seconds > args.request_seconds + CHILD_CLEANUP_SECONDS,+ "invalid child/total deadline",+ )+ require(not args.output.exists(), "use a fresh output directory")+ prompt = args.prompt.read_text()+ require(bool(prompt.strip()), "prompt is empty")+ manifest = json.loads(args.server_manifest.read_text())+ markers = [json.loads(path.read_text()) for path in args.server_manifest.parent.glob("installed-*.json")]+ require(+ any(+ marker.get("version") == VERSION+ and marker.get("source_files") == SOURCE_FILES+ and marker.get("server_manifest_sha256") == digest(manifest)+ for marker in markers+ ),+ "matching child observer is not installed; preload and verify readiness first",+ )+ plan = {+ "schema": 2,+ "url": args.url,+ "model": args.model,+ "prompt": prompt,+ "cohort": manifest["cohort"],+ "server_manifest_sha256": digest(manifest),+ "prompt_sha256": hashlib.sha256(prompt.encode()).hexdigest(),+ "completion_tokens": args.completion_tokens,+ "warmups": args.warmups,+ "repeats": args.repeats,+ "request_seconds": args.request_seconds,+ "total_seconds": args.total_seconds,+ "child_cleanup_seconds": CHILD_CLEANUP_SECONDS,+ "clock_domain": clock_domain(),+ "concurrency": 1,+ "sampling": {+ "temperature": 0,+ "top_p": 1,+ "top_k": 1,+ "presence_penalty": 0,+ "frequency_penalty": 0,+ "repetition_penalty": 1,+ "seed": 17,+ "min_tokens": args.completion_tokens,+ "max_completion_tokens": args.completion_tokens,+ },+ }+ args.output.mkdir(parents=True)+ save(args.output / "plan.json", plan)+ deadline = time.monotonic() + args.total_seconds+ summary: dict[str, Any] = {"completed": False, "children": []}+ try:+ for index in range(args.warmups + args.repeats):+ require(+ deadline - time.monotonic() > args.request_seconds + CHILD_CLEANUP_SECONDS,+ "insufficient time to admit fixed child",+ )+ destination = args.output / f"trial-{index:04d}.json"+ with (args.output / f"trial-{index:04d}.log").open("wb") as log:+ process = subprocess.Popen( # noqa: S603 - fixed module, no shell+ [+ sys.executable,+ "-m",+ "tools.benchmarks.stream_decode.client",+ "--one",+ str(args.output / "plan.json"),+ "--index",+ str(index),+ "--output",+ str(destination),+ ],+ stdout=log,+ stderr=subprocess.STDOUT,+ )+ child: dict[str, Any] = {"index": index, "pid": process.pid, "timed_out": False}+ summary["children"].append(child)+ try:+ child["returncode"] = process.wait(timeout=args.request_seconds)+ except subprocess.TimeoutExpired:+ child["timed_out"] = True+ finally:+ child["signals"] = stop_child(process)+ child["returncode"] = process.returncode+ save(args.output / "controller.json", summary)+ require(not child["timed_out"] and child["returncode"] == 0, "stream child failed; raw record retained")+ summary["completed"] = True+ finally:+ save(args.output / "controller.json", summary)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--url", default="http://127.0.0.1:8080")+ parser.add_argument("--model")+ parser.add_argument("--prompt", type=Path)+ parser.add_argument("--server-manifest", type=Path)+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--completion-tokens", type=int, default=128)+ parser.add_argument("--warmups", type=int, default=2)+ parser.add_argument("--repeats", type=int, default=6)+ parser.add_argument("--request-seconds", type=float, default=120)+ parser.add_argument("--total-seconds", type=float, default=1200)+ parser.add_argument("--one", type=Path, help=argparse.SUPPRESS)+ parser.add_argument("--index", type=int, help=argparse.SUPPRESS)+ args = parser.parse_args()+ if args.one:+ one(json.loads(args.one.read_text()), args.index, args.output)+ else:+ require(+ args.model is not None and args.prompt is not None and args.server_manifest is not None,+ "--model, --prompt and --server-manifest are required",+ )+ run(args)+++if __name__ == "__main__":+ main()diff --git a/tools/benchmarks/stream_decode/observer.py b/tools/benchmarks/stream_decode/observer.pynew file mode 100644index 000000000..42144a411--- /dev/null+++ b/tools/benchmarks/stream_decode/observer.py@@ -0,0 +1,242 @@+"""Observe the actual child chat stream without changing requests or tensors."""++from __future__ import annotations++import builtins+import contextlib+import contextvars+import copy+import hashlib+import importlib.metadata+import json+import os+import sys+import time+import uuid+from collections.abc import Callable, Mapping, Sequence+from functools import wraps+from pathlib import Path+from types import ModuleType+from typing import Any++MODULE = "sglang.srt.managers.tokenizer_manager"+VERSION = "0.5.20"+SOURCE_SHA256 = "952fdfcf54b13af6851993d4b7599d4b1efeb6aa630a7554584a1a047eda94f2"+SOURCE_FILES = {+ "managers/tokenizer_manager.py": SOURCE_SHA256,+ "entrypoints/openai/serving_chat.py": "047e4391dc87816a62da34392eea9379fcb1f93025e70c3b327de8b596f59b09",+ "sampling/sampling_params.py": "7295f275a1a286ae5a4414bcedd1d48a3a9824a0c2a5c915e091ed06b6f74730",+}+TRACE_ENV = "SIE_STREAM_DECODE_TRACE"+MARKER = "_sie_stream_decode_observer"+MAX_EVENTS = 100_000+SAMPLING_FIELDS = (+ "temperature",+ "top_p",+ "top_k",+ "min_p",+ "presence_penalty",+ "frequency_penalty",+ "repetition_penalty",+ "sampling_seed",+ "min_new_tokens",+ "max_new_tokens",+ "n",+ "ignore_eos",+ "skip_special_tokens",+ "stop_strs",+ "stop_token_ids",+ "stop_regex_strs",+ "json_schema",+ "regex",+ "ebnf",+ "structural_tag",+ "custom_params",+ "logit_bias",+)+++def clock_domain() -> str | None:+ """Bind monotonic timestamps to a Linux boot without publishing the boot ID."""+ path = Path("/proc/sys/kernel/random/boot_id")+ return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None+++def digest(value: Any) -> str:+ return hashlib.sha256(+ json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()+ ).hexdigest()+++def save(path: Path, value: Any) -> None:+ temporary = path.with_suffix(path.suffix + ".tmp")+ temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")+ temporary.replace(path)+++def patch_manager(module: ModuleType, output: Path, manifest: dict[str, Any]) -> Callable[[], None]:+ """Observe input tokenization and output of the same child request.++ Chat bypasses SIE's native generate/parser methods. This boundary is inside+ the SGLang child, before serving_chat formats SSE. Records stay in memory+ until the stream closes. No per-event tokenization or disk writes occur.+ """+ manager = module.TokenizerManager+ if getattr(manager, MARKER, False):+ raise RuntimeError("stream observer already installed")+ generate, tokenize = manager.generate_request, manager._tokenize_one_request+ current: contextvars.ContextVar[dict[str, Any] | None] = contextvars.ContextVar("stream_decode", default=None)++ @wraps(tokenize)+ async def tokenized(self: Any, *args: Any, **kwargs: Any) -> Any:+ result = await tokenize(self, *args, **kwargs)+ record = current.get()+ if record is not None:+ if "tokenized" in record:+ raise RuntimeError("benchmark requires one tokenized input per request")+ sampling = {}+ for name in SAMPLING_FIELDS:+ value = getattr(result.sampling_params, name, None)+ sampling[name] = sorted(value) if isinstance(value, set) else copy.deepcopy(value)+ record["tokenized"] = {+ "input_ids": list(result.input_ids),+ "sampling": sampling,+ "rid": result.rid,+ "has_multimodal_inputs": bool(getattr(result, "mm_inputs", None)),+ }+ return result++ @wraps(generate)+ async def generated(self: Any, obj: Any, request: Any = None) -> Any:+ route = request.url.path if request is not None else None+ if route != "/v1/chat/completions" or obj.stream is not True:+ # SGLang performs native generation during startup and health checks.+ # Preserve those calls, recording only their occupancy so analysis+ # can reject any that overlap the benchmark schedule.+ background = {+ "id": uuid.uuid4().hex,+ "pid": os.getpid(),+ "route": route,+ "started_ns": time.perf_counter_ns(),+ "finished_ns": None,+ "clock_domain": clock_domain(),+ "completed": False,+ }+ path = output / f"background-{background['id']}.json"+ save(path, background)+ try:+ async with contextlib.aclosing(generate(self, obj, request)) as stream:+ async for event in stream:+ yield event+ background["completed"] = True+ finally:+ background["finished_ns"] = time.perf_counter_ns()+ save(path, background)+ return+ record: dict[str, Any] = {+ "id": uuid.uuid4().hex,+ "pid": os.getpid(),+ "started_ns": time.perf_counter_ns(),+ "finished_ns": None,+ "events": [],+ "completed": False,+ "cohort": manifest["cohort"],+ "server_manifest_sha256": digest(manifest),+ "clock_domain": clock_domain(),+ "version": VERSION,+ "source_sha256": SOURCE_SHA256,+ "model_path": self.model_path,+ "served_model_name": self.served_model_name,+ "incremental_streaming_output": self.incremental_streaming_output,+ }+ path = output / f"stream-{record['id']}.json"+ # A second stream can remain open when the measured client finishes.+ # Persist its occupancy once so offline analysis cannot miss it.+ save(path, record)+ try:+ # The ordinary route already parsed this body. Never record headers,+ # credentials, or arbitrary environment values.+ record["chat_body"] = copy.deepcopy(await request.json())+ record["adapted_sampling"] = copy.deepcopy(obj.sampling_params)+ async with contextlib.aclosing(generate(self, obj, request)) as stream:+ while True:+ # Consumers may resume an async generator in another task.+ # Bind only the engine await; never hold a ContextVar token+ # across a yield into the HTTP/SSE consumer.+ token = current.set(record)+ try:+ event = await anext(stream)+ except StopAsyncIteration:+ break+ finally:+ current.reset(token)+ at_ns = time.perf_counter_ns()+ if len(record["events"]) >= MAX_EVENTS:+ raise RuntimeError("benchmark exceeded its fixed event bound")+ record["events"].append({"at_ns": at_ns, "event": copy.deepcopy(event)})+ yield event+ record["completed"] = True+ except BaseException as error:+ record["error"] = {"type": type(error).__name__, "message": str(error)}+ raise+ finally:+ record["finished_ns"] = time.perf_counter_ns()+ save(path, record)++ manager.generate_request, manager._tokenize_one_request = generated, tokenized+ setattr(manager, MARKER, True)++ def restore() -> None:+ manager.generate_request, manager._tokenize_one_request = generate, tokenize+ delattr(manager, MARKER)++ return restore+++def install() -> None:+ """Chain after production sitecustomize; refuse unreviewed engine source."""+ directory = os.environ.get(TRACE_ENV)+ if not directory:+ return+ output = Path(directory)+ manifest = json.loads((output / "server.json").read_text())+ if importlib.metadata.version("sglang") != VERSION:+ raise RuntimeError(f"stream observer requires SGLang {VERSION}")+ previous = builtins.__import__+ installed = False++ def imported(+ name: str,+ globals: Mapping[str, object] | None = None,+ locals: Mapping[str, object] | None = None,+ fromlist: Sequence[str] | None = (),+ level: int = 0,+ ) -> ModuleType:+ nonlocal installed+ result = previous(name, globals, locals, fromlist, level)+ module = sys.modules.get(MODULE)+ if not installed and isinstance(module, ModuleType) and hasattr(module, "TokenizerManager"):+ if module.__file__ is None:+ raise RuntimeError("SGLang tokenizer manager source is absent")+ source_root = Path(module.__file__).parents[1]+ actual = {name: hashlib.sha256((source_root / name).read_bytes()).hexdigest() for name in SOURCE_FILES}+ if actual != SOURCE_FILES:+ raise RuntimeError("unreviewed SGLang stream source")+ installed = True+ patch_manager(module, output, manifest)+ save(+ output / f"installed-{os.getpid()}.json",+ {+ "pid": os.getpid(),+ "version": VERSION,+ "source_sha256": SOURCE_SHA256,+ "source_files": actual,+ "cohort": manifest["cohort"],+ "server_manifest_sha256": digest(manifest),+ },+ )+ if builtins.__import__ is imported:+ setattr(builtins, "__import__", previous) # noqa: B010+ return result++ setattr(builtins, "__import__", imported) # noqa: B010diff --git a/tools/benchmarks/stream_decode/server.py b/tools/benchmarks/stream_decode/server.pynew file mode 100644index 000000000..3a0ae6846--- /dev/null+++ b/tools/benchmarks/stream_decode/server.py@@ -0,0 +1,79 @@+"""Run the ordinary SIE CLI with the dedicated child stream observer."""++from __future__ import annotations++import argparse+import contextlib+import hashlib+import os+import re+import sys+from collections.abc import Iterator+from pathlib import Path+from typing import Any, cast++from sie_server.adapters.sglang import cuda13, generation+from sie_server.api import openai_local+from sie_server.cli import app++from tools.benchmarks.stream_decode.observer import SOURCE_FILES, SOURCE_SHA256, TRACE_ENV, VERSION, clock_domain, save+++def observe(output: Path, cohort: str) -> Iterator[None]:+ if re.fullmatch(r"[a-zA-Z0-9_-]{1,64}", cohort) is None:+ raise ValueError("cohort must contain 1-64 letters, digits, underscores or hyphens")+ output = output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ source = Path(__file__).resolve()+ manifest = {+ "schema": 2,+ "cohort": cohort,+ "clock_domain": clock_domain(),+ "sglang_version": VERSION,+ "tokenizer_manager_sha256": SOURCE_SHA256,+ "engine_sources": SOURCE_FILES,+ "sie_sources": {+ module.__name__: hashlib.sha256(Path(module.__file__).read_bytes()).hexdigest()+ for module in (generation, cuda13, openai_local)+ },+ "observer_sha256": hashlib.sha256(source.with_name("observer.py").read_bytes()).hexdigest(),+ }+ save(output / "server.json", manifest)+ adapter = cast("Any", generation.SGLangGenerationAdapter)+ original = adapter._compat_pythonpath_entries+ previous = os.environ.get(TRACE_ENV)++ def paths(self: generation.SGLangGenerationAdapter) -> tuple[str, ...]:+ return (str(source.parent / "_hooks"), str(source.parents[3]), *original(self))++ adapter._compat_pythonpath_entries = paths+ os.environ[TRACE_ENV] = str(output)+ try:+ yield+ finally:+ adapter._compat_pythonpath_entries = original+ if previous is None:+ os.environ.pop(TRACE_ENV, None)+ else:+ os.environ[TRACE_ENV] = previous+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--trace-directory", type=Path, required=True)+ parser.add_argument("--cohort", required=True)+ parser.add_argument("sie_arguments", nargs=argparse.REMAINDER)+ args = parser.parse_args()+ arguments = args.sie_arguments+ if arguments[:1] == ["--"]:+ arguments = arguments[1:]+ if any(arg.split("=")[0] == "--reload" for arg in arguments):+ raise ValueError("benchmark wrapper does not support server reload")+ sys.argv = ["sie-server", *arguments]+ with observe(args.trace_directory, args.cohort):+ app()+++if __name__ == "__main__":+ main()diff --git a/tools/benchmarks/stream_decode/tests/test_analysis.py b/tools/benchmarks/stream_decode/tests/test_analysis.pynew file mode 100644index 000000000..422da1ce5--- /dev/null+++ b/tools/benchmarks/stream_decode/tests/test_analysis.py@@ -0,0 +1,330 @@+import copy++import pytest++from tools.benchmarks.stream_decode.analysis import analyze, analyze_trial+from tools.benchmarks.stream_decode.observer import SOURCE_FILES, SOURCE_SHA256, VERSION, digest, save+++def records():+ def chunk(at, text=None, finish=None, usage=None):+ return {+ "at_ns": at,+ "chunk": {+ "id": "engine-id",+ "choices": [] if usage else [{"index": 0, "delta": {"content": text}, "finish_reason": finish}],+ "usage": usage,+ },+ }++ client = {+ "completed": True,+ "retry_count": 0,+ "http_requests": 1,+ "clock_domain": "same-boot",+ "index": 0,+ "warmup": False,+ "started_ns": 1_000_000_000,+ "finished_ns": 6_000_000_000,+ "chunks": [+ chunk(2_500_000_000, "a"),+ chunk(4_500_000_000, "bcd"),+ chunk(5_000_000_000, finish="length"),+ chunk(5_500_000_000, usage={"prompt_tokens": 10, "completion_tokens": 4}),+ ],+ }+ backend = {+ "id": "only",+ "completed": True,+ "clock_domain": "same-boot",+ "started_ns": 1_100_000_000,+ "finished_ns": 4_200_000_000,+ "events": [],+ "incremental_streaming_output": False,+ }+ for at, tokens, text, finish in [(2, 1, "a", None), (3, 3, "abc", None), (4, 4, "abcd", "length")]:+ backend["events"].append(+ {+ "at_ns": at * 1_000_000_000,+ "event": {+ "text": text,+ "meta_info": {+ "id": "engine-id",+ "prompt_tokens": 10,+ "completion_tokens": tokens,+ "finish_reason": finish,+ },+ },+ }+ )+ return client, backend+++def test_token_counts_and_distinct_time_windows(records):+ result = analyze_trial(*records, 10, 4)+ assert result["client_ttft_s"] == 1.5+ assert result["client_total_s"] == 5+ assert result["completion_tokens_per_total_s"] == 0.8+ assert result["backend_after_first_token_tokens_per_s"] == 1.5+ assert result["largest_token_advance_group"] == 2+ assert result["backend_token_advance_groups"] == 3+++def test_first_group_coalesced_has_no_exact_first_token_claim(records):+ client, backend = records+ backend["events"][0]["event"]["meta_info"]["completion_tokens"] = 2+ result = analyze_trial(client, backend, 10, 4)+ assert result["backend_after_first_observation_tokens_per_s"] == 1+ assert result["backend_after_first_token_tokens_per_s"] is None+ assert not result["exact_first_token_observed"]+++ "mutation",+ [+ "missing_usage",+ "wrong_length",+ "early_stop",+ "no_finish",+ "retry",+ "requests",+ "clock",+ "missing_tokens",+ "bool_tokens",+ "regress_tokens",+ "text",+ "incomplete",+ "clock_regression",+ "mixed_id",+ "backend_prompt",+ "tool_call",+ "backend_end",+ "backend_end_type",+ "sdk_id",+ "missing_sdk_id",+ ],+)+def test_incomplete_or_inconsistent_stream_is_rejected(records, mutation):+ client, backend = records+ if mutation == "missing_usage":+ client["chunks"][-1]["chunk"]["usage"] = None+ elif mutation == "wrong_length":+ client["chunks"][-1]["chunk"]["usage"]["completion_tokens"] = 3+ elif mutation == "early_stop":+ client["chunks"][-2]["chunk"]["choices"][0]["finish_reason"] = "stop"+ elif mutation == "no_finish":+ backend["events"][-1]["event"]["meta_info"]["finish_reason"] = None+ elif mutation == "retry":+ client["retry_count"] = 1+ elif mutation == "requests":+ client["http_requests"] = 2+ elif mutation == "clock":+ backend["clock_domain"] = "other-boot"+ elif mutation == "missing_tokens":+ del backend["events"][1]["event"]["meta_info"]["completion_tokens"]+ elif mutation == "bool_tokens":+ backend["events"][0]["event"]["meta_info"]["completion_tokens"] = True+ elif mutation == "regress_tokens":+ backend["events"][1]["event"]["meta_info"]["completion_tokens"] = 0+ elif mutation == "text":+ backend["events"][-1]["event"]["text"] = "abcE"+ elif mutation == "incomplete":+ client["completed"] = False+ elif mutation == "clock_regression":+ backend["events"][1]["at_ns"] = 1+ elif mutation == "mixed_id":+ backend["events"][1]["event"]["meta_info"]["id"] = "another"+ elif mutation == "backend_prompt":+ backend["events"][1]["event"]["meta_info"]["prompt_tokens"] = 11+ elif mutation == "tool_call":+ client["chunks"][0]["chunk"]["choices"][0]["delta"]["tool_calls"] = [{"index": 0}]+ elif mutation == "backend_end":+ backend["finished_ns"] = backend["events"][0]["at_ns"]+ elif mutation == "backend_end_type":+ backend["finished_ns"] = True+ elif mutation == "sdk_id":+ client["chunks"][0]["chunk"]["id"] = "wrong-id"+ elif mutation == "missing_sdk_id":+ del client["chunks"][0]["chunk"]["id"]+ with pytest.raises(ValueError, match=r".+"):+ analyze_trial(client, backend, 10, 4)+++def test_terminal_usage_delay_does_not_inflate_decode_interval(records):+ client, backend = records+ duplicate = copy.deepcopy(backend["events"][-1])+ backend["events"][-1]["event"]["meta_info"]["finish_reason"] = None+ duplicate["at_ns"] = 5_000_000_000+ backend["events"].append(duplicate)+ backend["finished_ns"] = 5_100_000_000+ assert analyze_trial(client, backend, 10, 4)["backend_decode_interval_s"] == 2+++def cohort(tmp_path, records):+ clients, servers = tmp_path / "client", tmp_path / "server"+ clients.mkdir()+ servers.mkdir()+ manifest = {"cohort": "fixed", "clock_domain": "same-boot", "source": "frozen"}+ sampling = {+ "temperature": 0,+ "top_p": 1,+ "top_k": 1,+ "presence_penalty": 0,+ "frequency_penalty": 0,+ "repetition_penalty": 1,+ "seed": 17,+ "min_tokens": 4,+ "max_completion_tokens": 4,+ }+ plan = {+ "completion_tokens": 4,+ "warmups": 0,+ "repeats": 1,+ "cohort": "fixed",+ "model": "model",+ "prompt": "public",+ "prompt_sha256": "efa1f375d76194fa51a3556a97e641e61685f914d446979da50a551a4333ffd7",+ "server_manifest_sha256": digest(manifest),+ "sampling": sampling,+ "clock_domain": "same-boot",+ }+ body = {+ "model": "model",+ "messages": [{"role": "user", "content": "public"}],+ "stream": True,+ "stream_options": {"include_usage": True},+ "chat_template_kwargs": {"enable_thinking": False},+ **sampling,+ }+ records[0].update(cohort="fixed", plan_sha256=digest(plan), request_body=copy.deepcopy(body))+ records[1].update(+ cohort="fixed",+ server_manifest_sha256=digest(manifest),+ source_sha256=SOURCE_SHA256,+ version=VERSION,+ model_path="public/checkpoint",+ served_model_name="model",+ pid=1,+ chat_body=copy.deepcopy(body),+ adapted_sampling={"temperature": 0},+ tokenized={+ "input_ids": list(range(10)),+ "rid": "engine-id",+ "has_multimodal_inputs": False,+ "sampling": {+ "temperature": 1,+ "top_p": 1,+ "top_k": 1,+ "min_p": 0,+ "presence_penalty": 0,+ "frequency_penalty": 0,+ "repetition_penalty": 1,+ "sampling_seed": 17,+ "n": 1,+ "min_new_tokens": 4,+ "max_new_tokens": 4,+ },+ },+ )+ save(clients / "plan.json", plan)+ save(+ clients / "controller.json",+ {"completed": True, "children": [{"index": 0, "returncode": 0, "timed_out": False, "signals": []}]},+ )+ save(servers / "server.json", manifest)+ save(+ servers / "installed-1.json",+ {+ "pid": 1,+ "server_manifest_sha256": digest(manifest),+ "source_sha256": SOURCE_SHA256,+ "source_files": SOURCE_FILES,+ "version": VERSION,+ },+ )+ save(clients / "trial-0000.json", records[0])+ save(servers / "stream-one.json", records[1])+ return clients, servers+++def test_fixed_cohort_and_unique_request_join(tmp_path, records):+ clients, servers = cohort(tmp_path, records)+ assert analyze(clients, servers, 10, 4)["measured_trials"] == 1+ other = copy.deepcopy(records[1])+ other["id"] = "extra"+ save(servers / "stream-extra.json", other)+ with pytest.raises(ValueError, match="exactly one"):+ analyze(clients, servers, 10, 4)+++ "mutation", ["prompt", "cohort", "source", "input_ids", "sampling", "request_id", "thinking", "model", "controller"]+)+def test_request_and_source_binding_refuses_mismatched_evidence(tmp_path, records, mutation):+ clients, servers = cohort(tmp_path, records)+ backend = records[1]+ if mutation == "prompt":+ backend["chat_body"]["messages"][0]["content"] = "different"+ elif mutation == "cohort":+ backend["cohort"] = "another"+ elif mutation == "source":+ backend["source_sha256"] = "unreviewed"+ elif mutation == "input_ids":+ backend["tokenized"]["input_ids"].pop()+ elif mutation == "sampling":+ backend["tokenized"]["sampling"]["top_k"] = 2+ elif mutation == "request_id":+ backend["tokenized"]["rid"] = "different"+ elif mutation == "thinking":+ backend["chat_body"]["chat_template_kwargs"]["enable_thinking"] = True+ elif mutation == "model":+ backend["chat_body"]["model"] = "another"+ elif mutation == "controller":+ save(clients / "controller.json", {"completed": False})+ save(servers / "stream-one.json", backend)+ with pytest.raises(ValueError, match=r".+"):+ analyze(clients, servers, 10, 4)+++def test_backend_cleanup_can_finish_after_client_without_changing_decode(records):+ records[1]["finished_ns"] = records[0]["finished_ns"] + 1_000_000_000+ assert analyze_trial(*records, 10, 4)["backend_after_first_token_tokens_per_s"] == 1.5+++def test_incremental_text_mode_uses_cumulative_counts(records):+ records[1]["incremental_streaming_output"] = True+ for row, text in zip(records[1]["events"], ["a", "bc", "d"], strict=True):+ row["event"]["text"] = text+ assert analyze_trial(*records, 10, 4)["backend_after_first_token_tokens_per_s"] == 1.5++[email protected]("end", [None, 1_500_000_000, 6_500_000_000])+def test_background_started_before_schedule_still_invalidates_overlap(tmp_path, records, end):+ clients, servers = cohort(tmp_path, records)+ save(servers / "background-health.json", {"started_ns": 1, "finished_ns": end, "clock_domain": "same-boot"})+ with pytest.raises(ValueError, match="background generation overlaps"):+ analyze(clients, servers, 10, 4)+++def test_finished_startup_generation_before_schedule_is_retained(tmp_path, records):+ clients, servers = cohort(tmp_path, records)+ save(servers / "background-startup.json", {"started_ns": 1, "finished_ns": 2, "clock_domain": "same-boot"})+ assert analyze(clients, servers, 10, 4)["background_calls_outside_schedule"] == 1+++def test_unfinished_unrelated_chat_is_rejected_before_its_first_event(tmp_path, records):+ clients, servers = cohort(tmp_path, records)+ save(+ servers / "stream-open.json",+ {+ "id": "unrelated",+ "started_ns": 1_500_000_000,+ "finished_ns": None,+ "clock_domain": "same-boot",+ "completed": False,+ "events": [],+ },+ )+ with pytest.raises(ValueError, match="unexpected backend stream"):+ analyze(clients, servers, 10, 4)diff --git a/tools/benchmarks/stream_decode/tests/test_client.py b/tools/benchmarks/stream_decode/tests/test_client.pynew file mode 100644index 000000000..0b7ac8879--- /dev/null+++ b/tools/benchmarks/stream_decode/tests/test_client.py@@ -0,0 +1,124 @@+import json+import subprocess+import sys+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++from tools.benchmarks.stream_decode.client import stop_child+from tools.benchmarks.stream_decode.observer import SOURCE_FILES, VERSION, digest+++def test_real_sdk_child_controller_records_serial_streams(tmp_path, monkeypatch):+ monkeypatch.setenv("HTTP_PROXY", "http://invalid-proxy.invalid:9")+ monkeypatch.setenv("ALL_PROXY", "http://invalid-proxy.invalid:9")+ monkeypatch.setenv("NO_PROXY", "")+ bodies = []++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_POST(self):+ assert self.path == "/v1/chat/completions"+ bodies.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))+ chunks = [+ {"choices": [{"index": 0, "delta": {"content": "ab"}, "finish_reason": None}]},+ {"choices": [{"index": 0, "delta": {"content": "cd"}, "finish_reason": "length"}]},+ {"choices": [], "usage": {"prompt_tokens": 10, "completion_tokens": 4}},+ ]+ body = ("".join("data: " + json.dumps(c) + "\n\n" for c in chunks) + "data: [DONE]\n\n").encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ prompt = tmp_path / "prompt.txt"+ prompt.write_text("A fixed test prompt")+ manifest = tmp_path / "server.json"+ manifest.write_text(json.dumps({"cohort": "local-test"}))+ (tmp_path / "installed-1.json").write_text(+ json.dumps(+ {+ "version": VERSION,+ "source_files": SOURCE_FILES,+ "server_manifest_sha256": digest({"cohort": "local-test"}),+ }+ )+ )+ output = tmp_path / "result"+ try:+ run = subprocess.run( # noqa: S603 - fixed test module, no shell+ [+ sys.executable,+ "-m",+ "tools.benchmarks.stream_decode.client",+ "--url",+ f"http://127.0.0.1:{server.server_port}",+ "--model",+ "test/model",+ "--prompt",+ str(prompt),+ "--server-manifest",+ str(manifest),+ "--output",+ str(output),+ "--completion-tokens",+ "4",+ "--warmups",+ "1",+ "--repeats",+ "1",+ "--request-seconds",+ "5",+ "--total-seconds",+ "40",+ ],+ capture_output=True,+ text=True,+ timeout=20,+ check=False,+ )+ assert run.returncode == 0, run.stderr+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)+ assert len(bodies) == 2+ assert all(b["min_tokens"] == b["max_completion_tokens"] == 4 for b in bodies)+ assert all(b["stream"] and b["stream_options"]["include_usage"] for b in bodies)+ records = [json.loads(path.read_text()) for path in sorted(output.glob("trial-*.json"))]+ assert [r["warmup"] for r in records] == [True, False]+ assert all(r["completed"] and r["retry_count"] == 0 and r["http_requests"] == 1 for r in records)+ assert len({r["started_ns"] for r in records}) == 2+ assert records[0]["finished_ns"] < records[1]["started_ns"]+ assert json.loads((output / "controller.json").read_text())["completed"]+++def test_owned_child_is_terminated_and_reaped():+ process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])+ try:+ assert stop_child(process) == ["SIGTERM"]+ assert process.poll() is not None+ finally:+ stop_child(process)+++def test_child_wall_deadline_works_without_controller(tmp_path):+ result = subprocess.run(+ [+ sys.executable,+ "-c",+ "import time\nfrom tools.benchmarks.stream_decode.client import child_deadline\n"+ "with child_deadline(0.1):\n time.sleep(60)\n",+ ],+ capture_output=True,+ text=True,+ timeout=5,+ check=False,+ )+ assert result.returncode != 0+ assert "fixed child wall deadline expired" in result.stderrdiff --git a/tools/benchmarks/stream_decode/tests/test_install.py b/tools/benchmarks/stream_decode/tests/test_install.pynew file mode 100644index 000000000..e43387138--- /dev/null+++ b/tools/benchmarks/stream_decode/tests/test_install.py@@ -0,0 +1,75 @@+import builtins+import hashlib+import json+import os+import sys+from types import ModuleType++import pytest+from sie_server.adapters.sglang.generation import SGLangGenerationAdapter++from tools.benchmarks.stream_decode import observer+from tools.benchmarks.stream_decode.server import observe+from tools.benchmarks.stream_decode.tests.test_observer import manager_type++[email protected]("valid_source", [True, False])+def test_child_hook_checks_source_and_restores_import_hook(monkeypatch, tmp_path, valid_source):+ module = ModuleType(observer.MODULE)+ module.TokenizerManager = manager_type()+ source = tmp_path / "srt/managers/tokenizer_manager.py"+ source.parent.mkdir(parents=True)+ source.write_text("# generated test source\n")+ module.__file__ = str(source)+ monkeypatch.setitem(sys.modules, observer.MODULE, module)+ monkeypatch.setattr(+ observer, "SOURCE_SHA256", hashlib.sha256(source.read_bytes()).hexdigest() if valid_source else "wrong"+ )+ monkeypatch.setattr(observer, "SOURCE_FILES", {"managers/tokenizer_manager.py": observer.SOURCE_SHA256})+ monkeypatch.setattr(observer.importlib.metadata, "version", lambda _: observer.VERSION)+ monkeypatch.setenv(observer.TRACE_ENV, str(tmp_path))+ observer.save(tmp_path / "server.json", {"cohort": "install-test"})+ previous = builtins.__import__+ try:+ observer.install()+ if valid_source:+ builtins.__import__("math")+ assert builtins.__import__ is previous+ assert getattr(module.TokenizerManager, observer.MARKER)+ marker = json.loads((tmp_path / f"installed-{os.getpid()}.json").read_text())+ assert marker["cohort"] == "install-test"+ assert marker["source_sha256"] == observer.SOURCE_SHA256+ else:+ with pytest.raises(RuntimeError, match="unreviewed"):+ builtins.__import__("math")+ assert not hasattr(module.TokenizerManager, observer.MARKER)+ finally:+ builtins.__import__ = previous+++def test_wrong_engine_version_fails_before_installing(monkeypatch, tmp_path):+ monkeypatch.setenv(observer.TRACE_ENV, str(tmp_path))+ monkeypatch.setattr(observer.importlib.metadata, "version", lambda _: "0.5.10.post1")+ observer.save(tmp_path / "server.json", {"cohort": "version-test"})+ previous = builtins.__import__+ with pytest.raises(RuntimeError, match="requires SGLang"):+ observer.install()+ assert builtins.__import__ is previous+++def test_server_wrapper_preserves_production_hooks_and_restores_on_failure(monkeypatch, tmp_path):+ adapter = SGLangGenerationAdapter("public/checkpoint")+ original = SGLangGenerationAdapter._compat_pythonpath_entries+ production = original(adapter)+ monkeypatch.setenv(observer.TRACE_ENV, "previous-value")+ with pytest.raises(RuntimeError, match="stop"):+ with observe(tmp_path / "trace", "cohort"):+ actual = adapter._compat_pythonpath_entries()+ assert actual[2:] == production+ assert actual[0].endswith("stream_decode/_hooks")+ manifest = json.loads((tmp_path / "trace/server.json").read_text())+ assert manifest["sglang_version"] == "0.5.20"+ assert manifest["cohort"] == "cohort"+ raise RuntimeError("stop")+ assert SGLangGenerationAdapter._compat_pythonpath_entries is original+ assert os.environ[observer.TRACE_ENV] == "previous-value"diff --git a/tools/benchmarks/stream_decode/tests/test_observer.py b/tools/benchmarks/stream_decode/tests/test_observer.pynew file mode 100644index 000000000..fea55371c--- /dev/null+++ b/tools/benchmarks/stream_decode/tests/test_observer.py@@ -0,0 +1,256 @@+import asyncio+import contextlib+import json+import time+from types import SimpleNamespace+from unittest.mock import MagicMock++import httpx+import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from sie_sdk import SIEClient+from sie_server.adapters.sglang.generation import SGLangGenerationAdapter+from sie_server.api import openai_local++from tools.benchmarks.stream_decode import observer+from tools.benchmarks.stream_decode.analysis import analyze_trial+++def manager_type():+ class Manager:+ model_path = "public/checkpoint"+ served_model_name = "engine-model"+ incremental_streaming_output = False++ def __init__(self):+ self.closed = []+ self.received = []++ async def _tokenize_one_request(self, obj):+ return SimpleNamespace(+ input_ids=list(range(10)), sampling_params=SimpleNamespace(top_k=1), rid=obj.rid, mm_inputs=None+ )++ async def generate_request(self, obj, request=None):+ self.received.append((obj, request))+ try:+ await self._tokenize_one_request(obj)+ for tokens, text in ((1, "a"), (3, "abc"), (4, "abcd")):+ yield {+ "text": text,+ "meta_info": {+ "id": obj.rid,+ "prompt_tokens": 10,+ "completion_tokens": tokens,+ "finish_reason": {"type": "length"} if tokens == 4 else None,+ },+ }+ await asyncio.sleep(0)+ finally:+ self.closed.append(obj.rid)++ return Manager+++def request(body):+ async def as_json():+ return body++ return SimpleNamespace(url=SimpleNamespace(path="/v1/chat/completions"), json=as_json)+++ ("route", "streaming", "early"),+ [("/generate", False, False), (None, False, False), ("/health_generate", True, True)],+)+async def test_startup_and_health_generation_pass_through_without_payload_capture(tmp_path, route, streaming, early):+ cls = manager_type()+ restore = observer.patch_manager(SimpleNamespace(TokenizerManager=cls), tmp_path, {"cohort": "startup"})+ manager = cls()+ obj = SimpleNamespace(rid="warmup", stream=streaming, sampling_params={})+ raw = SimpleNamespace(url=SimpleNamespace(path=route)) if route is not None else None+ values = []+ try:+ async with contextlib.aclosing(manager.generate_request(obj, raw)) as generated:+ async for event in generated:+ values.append(event)+ if early:+ break+ finally:+ restore()+ assert len(values) == (1 if early else 3)+ assert manager.closed == ["warmup"]+ assert manager.received == [(obj, raw)]+ assert not list(tmp_path.glob("stream-*.json"))+ paths = list(tmp_path.glob("background-*.json"))+ assert len(paths) == 1+ record = json.loads(paths[0].read_text())+ assert record["completed"] is (not early)+ assert record["route"] == route+ assert record["finished_ns"] > record["started_ns"]+ assert not {"chat_body", "tokenized", "events"} & record.keys()+++async def test_concurrent_stream_records_and_early_close_preserve_original_generator(tmp_path):+ cls = manager_type()+ original = (cls.generate_request, cls._tokenize_one_request)+ restore = observer.patch_manager(SimpleNamespace(TokenizerManager=cls), tmp_path, {"cohort": "test"})+ manager = cls()++ async def consume(rid, early):+ obj = SimpleNamespace(rid=rid, stream=True, sampling_params={"top_k": 1})+ raw = request({"model": "engine-model", "messages": [{"role": "user", "content": rid}]})+ values = []+ async with contextlib.aclosing(manager.generate_request(obj, raw)) as stream:+ async for value in stream:+ values.append(value)+ if early:+ break+ assert (obj, raw) in manager.received+ return values++ try:+ complete, cancelled = await asyncio.gather(consume("full", False), consume("early", True))+ finally:+ restore()+ assert len(complete) == 3+ assert len(cancelled) == 1+ records = {+ row["tokenized"]["rid"]: row for row in (json.loads(p.read_text()) for p in tmp_path.glob("stream-*.json"))+ }+ assert records["full"]["completed"] is True+ assert records["early"]["completed"] is False+ assert records["early"]["error"]["type"] == "GeneratorExit"+ assert sorted(manager.closed) == ["early", "full"]+ assert (cls.generate_request, cls._tokenize_one_request) == original+ assert not hasattr(cls, observer.MARKER)+++async def test_chat_occupancy_is_visible_while_stream_is_open(tmp_path):+ cls = manager_type()+ restore = observer.patch_manager(SimpleNamespace(TokenizerManager=cls), tmp_path, {"cohort": "active"})+ obj = SimpleNamespace(rid="active-chat", stream=True, sampling_params={})+ manager = cls()+ try:+ async with contextlib.aclosing(manager.generate_request(obj, request({}))) as stream:+ await anext(stream)+ paths = list(tmp_path.glob("stream-*.json"))+ assert len(paths) == 1+ active = json.loads(paths[0].read_text())+ assert active["completed"] is False+ assert active["finished_ns"] is None+ assert active["events"] == []+ closed = json.loads(paths[0].read_text())+ assert closed["id"] == active["id"]+ assert closed["finished_ns"] > active["started_ns"]+ assert len(closed["events"]) == 1+ assert closed["error"]["type"] == "GeneratorExit"+ finally:+ restore()+++def test_real_sie_cuda_chat_route_and_sdk_reach_child_observer(monkeypatch, tmp_path):+ """A native adapter.generate hook cannot make this integration pass."""+ monkeypatch.setattr(observer, "clock_domain", lambda: "test-boot")+ cls = manager_type()+ restore = observer.patch_manager(SimpleNamespace(TokenizerManager=cls), tmp_path, {"cohort": "route"})+ manager = cls()+ adapter = SGLangGenerationAdapter("public/checkpoint", served_model_name="engine-model")+ adapter._server_url = "http://127.0.0.1:30400"+ adapter.generate = MagicMock(side_effect=AssertionError("native route must not be used"))+ config = SimpleNamespace(+ tasks=SimpleNamespace(+ generate=SimpleNamespace(max_output_tokens=64, chat_template_kwargs={"enable_thinking": False}), score=None+ ),+ resolve_profile=MagicMock(+ return_value=SimpleNamespace(runtime={"default_sampling": {}, "stop_tokens": []}, loadtime={})+ ),+ inputs=SimpleNamespace(video=False),+ profiles={},+ routing=None,+ )+ registry = MagicMock()+ registry.device = "cuda:0"+ registry.has_model.return_value = registry.is_loaded.return_value = True+ registry.is_loading.return_value = registry.is_unloading.return_value = registry.is_failed.return_value = False+ registry.get_config.return_value = config+ registry.get.return_value = adapter++ class Stream(httpx.AsyncByteStream):+ def __init__(self, body):+ self.body = body++ async def __aiter__(self):+ obj = SimpleNamespace(rid="engine-request", stream=True, sampling_params={"top_k": 1})+ prior = ""+ async with contextlib.aclosing(manager.generate_request(obj, request(self.body))) as events:+ async for event in events:+ meta = event["meta_info"]+ finish = meta["finish_reason"]+ chunk = {+ "id": meta["id"],+ "model": "engine-model",+ "choices": [+ {+ "index": 0,+ "delta": {"content": event["text"][len(prior) :]},+ "finish_reason": finish["type"] if finish else None,+ }+ ],+ }+ prior = event["text"]+ yield ("data: " + json.dumps(chunk) + "\n\n").encode()+ usage = {+ "id": "engine-request",+ "model": "engine-model",+ "choices": [],+ "usage": {"prompt_tokens": 10, "completion_tokens": 4, "total_tokens": 14},+ }+ yield ("data: " + json.dumps(usage) + "\n\ndata: [DONE]\n\n").encode()++ async def child(req):+ assert req.url.path == "/v1/chat/completions"+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=Stream(json.loads(req.content))+ )++ monkeypatch.setattr(+ openai_local,+ "_new_proxy_client",+ lambda: httpx.AsyncClient(transport=httpx.MockTransport(child), trust_env=False),+ )+ app = FastAPI()+ app.include_router(openai_local.router)+ app.state.registry = registry+ record = {"completed": False, "clock_domain": "test-boot", "http_requests": 1, "chunks": []}+ try:+ with (+ TestClient(app, base_url="http://127.0.0.1", follow_redirects=False) as http,+ SIEClient("http://127.0.0.1", remote="forbid", http_client=http) as sdk,+ ):+ record["started_ns"] = time.perf_counter_ns()+ for chunk in sdk.stream_chat_completions(+ "sie-model",+ [{"role": "user", "content": "public fixed prompt"}],+ max_completion_tokens=4,+ stream_options={"include_usage": True},+ wait_for_capacity=False,+ max_oom_retries=0,+ ):+ record["chunks"].append({"at_ns": time.perf_counter_ns(), "chunk": chunk})+ record.update(finished_ns=time.perf_counter_ns(), completed=True, retry_count=sdk.last_retry_count)+ finally:+ restore()+ traces = list(tmp_path.glob("stream-*.json"))+ assert len(traces) == 1+ backend = json.loads(traces[0].read_text())+ assert backend["chat_body"]["model"] == "engine-model"+ assert backend["chat_body"]["chat_template_kwargs"]["enable_thinking"] is False+ assert backend["tokenized"]["input_ids"] == list(range(10))+ assert analyze_trial(record, backend, 10, 4)["exact_first_token_observed"] is True+ adapter.generate.assert_not_called()+ assert manager.closed == ["engine-request"]