Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

test(sglang): measure warm LoRA restoration baselines

svonava1d89d743402f
diff --git a/tools/benchmarks/runtime_lora/README.md b/tools/benchmarks/runtime_lora/README.md
index ec72bbef1..574ff62c4 100644
--- a/tools/benchmarks/runtime_lora/README.md
+++ b/tools/benchmarks/runtime_lora/README.md
@@ -32,10 +32,21 @@ The acceptance run checks:
Encode retries automatically. The current generation SDK surfaces this
refusal, so the probe records and makes bounded fresh SDK calls only for
pre-execution `503 LORA_LOADING`; it never retries a failed open stream.
-- Adapter effects in chat token log probabilities and embedding vectors; base
- restoration after switching and after eviction. Pairwise effects must exceed
- the fixed minimum and five times measured base-repeat drift. These untrained
- fixtures provide selection evidence, not model-quality evidence.
+- Adapter effects in native/chat token log probabilities and embedding vectors;
+ base restoration after switching and after eviction. Generation records a
+ first response and two warm baseline repeats before any runtime selection.
+ Restored warm text must match exactly. At every matching token context, chosen
+ and shared top-token probability drift must stay below the fixed `1e-3` bound.
+ Top-k support changes are recorded: absent tokens have probability bounded by
+ the other top-k cutoff, and conservative difference lower bounds also must stay
+ below `1e-3`. Unreported tail probabilities remain unmeasured; small lower bounds
+ do not establish upper bounds on their drift. First-token
+ pairwise selection effects must exceed `1e-4` and five times baseline/reset
+ first-token drift. Embeddings retain fixed `1e-5` effect and `5e-5` reset bounds.
+ All full text and token probabilities are retained, including cold/warm
+ differences. Native streaming also probes one token after a fixed common
+ prefix where an earlier run diverged; this holds context constant when
+ comparing base/A/B/reset. These fixtures establish selection, not quality.
- Stable engine PID, rejection of undeclared adapters, ready-name listing,
preservation of one pinned adapter, and churn across four dynamic adapters.
- Overlapping A/B streams **and a successful engine forward containing both**.
@@ -46,7 +57,9 @@ The acceptance run checks:
distinct valid slots, with consistent inverse mappings. Completed SDK streams
establish completion; the hook timestamp is not a GPU timing measurement.
It also requires SIE's slot-release compatibility hook to be present.
- Observation does not alter scheduling or model tensors.
+ Cache-prefix/input/output lengths are captured before the forward, using
+ scalar fields and tensor shape metadata only. Observation does not alter
+ scheduling, cache settings, or model tensors.
`evidence.json` contains the final verdict. `events.jsonl`, `batches.jsonl`,
fixture hashes, generated model configurations, and `source-manifest.json`
@@ -54,6 +67,9 @@ provide the supporting record. Use a fresh output directory. The run has a
780-second default deadline and unloads each owned engine before starting the
next; any external compute allocation must have its own finite lifetime and
be stopped and verified separately by its owner.
+Numeric/restoration assertion failures are recorded while independent phases
+continue on a healthy engine; the final verdict remains failed and the process
+exits unsuccessfully. Transport, observer, or lifecycle failures stop the run.
Pinned primary sources: [generation config](https://huggingface.co/Qwen/Qwen3-0.6B/blob/c1899de289a04d12100db370d81485cdf75e47ca/config.json),
[embedding config](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B/blob/97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3/config.json),
diff --git a/tools/benchmarks/runtime_lora/observer.py b/tools/benchmarks/runtime_lora/observer.py
index 545196f26..fc8a76dbf 100644
--- a/tools/benchmarks/runtime_lora/observer.py
+++ b/tools/benchmarks/runtime_lora/observer.py
@@ -58,7 +58,20 @@ def patch_scheduler(module: ModuleType, path: str) -> None:
"pid": os.getpid(),
"start_ns": time.time_ns(),
"mode": str(batch.forward_mode),
- "requests": [{"rid": req.rid, "uid": req.lora_id, "lora": alias(req.lora_id)} for req in batch.reqs],
+ "requests": [
+ {
+ "rid": req.rid,
+ "uid": req.lora_id,
+ "lora": alias(req.lora_id),
+ "cache_key": req.extra_key,
+ "cached_tokens": req.cached_tokens,
+ "prefix_length": len(req.prefix_indices),
+ "extend_input_length": req.extend_input_len,
+ "input_length": len(req.origin_input_ids),
+ "output_length": len(req.output_ids),
+ }
+ for req in batch.reqs
+ ],
}
result = original(self, batch, *args, **kwargs)
row["end_ns"] = time.time_ns()
diff --git a/tools/benchmarks/runtime_lora/probe.py b/tools/benchmarks/runtime_lora/probe.py
index c2d5f0882..945c4bb3e 100644
--- a/tools/benchmarks/runtime_lora/probe.py
+++ b/tools/benchmarks/runtime_lora/probe.py
@@ -13,6 +13,7 @@ import os
import socket
import threading
import time
+from collections.abc import Callable
from http import HTTPStatus
from pathlib import Path
from typing import Any, cast
@@ -38,6 +39,7 @@ from tools.benchmarks.runtime_lora.observer import TRACE_ENV
ROOT = Path(__file__).resolve().parents[3]
MESSAGES: list[ChatMessage] = [{"role": "user", "content": "Explain why the sky is blue in two short sentences."}]
PROMPT = "The sky appears blue because"
+BOUNDARY_PROMPT = PROMPT + " of the reflection of light. This is an example of"
TEXTS = ["A red fox walks through the forest.", "Neural networks encode text as vectors."]
MAX_RESIDENT = 3
MIN_EMBEDDING_EFFECT = 1e-5
@@ -107,6 +109,7 @@ class Client:
def call(self, kind: str, model: str, selection: str | None, route: str = "chat") -> dict[str, Any]:
for attempt in range(MAX_GENERATION_RETRIES + 1):
+ response_start = len(self.responses)
try:
return self._call(kind, model, selection, route)
except ServerError as error:
@@ -114,6 +117,9 @@ class Client:
kind != "generation"
or error.status_code != HTTPStatus.SERVICE_UNAVAILABLE
or error.code != "LORA_LOADING"
+ or len(self.responses) == response_start
+ or self.responses[-1]["status"] != HTTPStatus.SERVICE_UNAVAILABLE
+ or self.responses[-1]["code"] != "LORA_LOADING"
or attempt == MAX_GENERATION_RETRIES
):
raise
@@ -145,7 +151,36 @@ class Client:
lora_adapter=selection,
max_oom_retries=0,
)
- return {"text": result["text"]}
+ return {"text": result["text"], "usage": result.get("usage")}
+ if route in {"native_stream", "native_boundary"}:
+ boundary = route == "native_boundary"
+ chunks = list(
+ self.sdk.stream_generate(
+ model,
+ BOUNDARY_PROMPT if boundary else PROMPT,
+ max_new_tokens=1 if boundary else 24,
+ temperature=0.0,
+ seed=17,
+ logprobs=True,
+ top_logprobs=20,
+ lora_adapter=selection,
+ max_oom_retries=0,
+ )
+ )
+ require(chunks and chunks[-1].get("done"), "native stream had no successful terminal event")
+ require(chunks[-1].get("finish_reason") in {"stop", "length"}, "native stream did not finish successfully")
+ content = [item for chunk in chunks for item in chunk.get("logprobs", [])]
+ require(content, "native stream did not return token probabilities")
+ require(
+ len(content) == (chunks[-1].get("usage") or {}).get("completion_tokens"),
+ "native stream omitted token probabilities",
+ )
+ return {
+ "text": "".join(chunk.get("text_delta", "") for chunk in chunks),
+ "logprobs": {"content": content},
+ "usage": chunks[-1].get("usage"),
+ "chunk_count": len(chunks),
+ }
result = self.sdk.chat_completions(
model,
MESSAGES,
@@ -186,22 +221,89 @@ class Client:
self.sdk.close()
-def first_distribution(result: dict[str, Any]) -> dict[str, float]:
+def token_content(result: dict[str, Any]) -> list[dict[str, Any]]:
content = (result.get("logprobs") or {}).get("content") or []
- require(content, "chat must return token logprobs")
- first = content[0]
- return {item["token"]: float(item["logprob"]) for item in first.get("top_logprobs", [first])}
+ require(content, "generation must return token logprobs")
+ return content
+
+
+def probability(value: Any) -> float:
+ logprob = float(value)
+ require(not math.isnan(logprob) and logprob <= 0, "invalid token log probability")
+ return math.exp(logprob)
+
+
+def token_distribution_comparison(left: dict[str, Any], right: dict[str, Any]) -> dict[str, Any]:
+ def observed(value: dict[str, Any]) -> tuple[dict[str, float], float]:
+ top = {item["token"]: probability(item["logprob"]) for item in value.get("top_logprobs") or []}
+ cutoff = min(top.values()) if top else 1.0
+ return {**top, value["token"]: probability(value["logprob"])}, cutoff
+
+ a, cutoff_a = observed(left)
+ b, cutoff_b = observed(right)
+ shared_delta = max((abs(a[token] - b[token]) for token in a.keys() & b.keys()), default=0.0)
+ changes: list[dict[str, Any]] = [
+ {"token": token, "observed_in": side, "probability": known[token], "other_upper_bound": cutoff}
+ for known, missing, side, cutoff in ((a, b, "left", cutoff_b), (b, a, "right", cutoff_a))
+ for token in sorted(known.keys() - missing.keys())
+ ]
+ # An absent token is below the other top-k cutoff, not probability zero.
+ lower_bound = max([shared_delta, *(max(0.0, item["probability"] - item["other_upper_bound"]) for item in changes)])
+ return {
+ "shared_probability_delta": shared_delta,
+ "probability_delta_lower_bound": lower_bound,
+ "support_changes": changes,
+ }
def distribution_delta(left: dict[str, Any], right: dict[str, Any]) -> float:
- a, b = first_distribution(left), first_distribution(right)
- probabilities_a = {token: math.exp(value) for token, value in a.items()}
- probabilities_b = {token: math.exp(value) for token, value in b.items()}
- return max(abs(probabilities_a.get(token, 0.0) - probabilities_b.get(token, 0.0)) for token in a.keys() | b.keys())
+ return token_distribution_comparison(token_content(left)[0], token_content(right)[0])[
+ "probability_delta_lower_bound"
+ ]
+
+
+def sequence_comparison(left: dict[str, Any], right: dict[str, Any]) -> dict[str, Any]:
+ """Compare probabilities only while the preceding token contexts match."""
+ a, b = token_content(left), token_content(right)
+ deltas = []
+ for index, (x, y) in enumerate(zip(a, b, strict=False)):
+ same_token = x["token"] == y["token"]
+ comparison = token_distribution_comparison(x, y)
+ deltas.append(
+ {
+ "index": index,
+ "same_token": same_token,
+ "chosen_probability_delta": abs(probability(x["logprob"]) - probability(y["logprob"]))
+ if same_token
+ else None,
+ **comparison,
+ }
+ )
+ if not same_token:
+ break
+ return {
+ "text_equal": left["text"] == right["text"],
+ "same_token_sequence": len(a) == len(b) == len(deltas) and all(row["same_token"] for row in deltas),
+ "max_aligned_chosen_probability_delta": max(
+ (row["chosen_probability_delta"] or 0.0 for row in deltas), default=0.0
+ ),
+ "max_aligned_shared_top_probability_delta": max(
+ (row["shared_probability_delta"] for row in deltas), default=0.0
+ ),
+ "max_aligned_probability_delta_lower_bound": max(
+ (row["probability_delta_lower_bound"] for row in deltas), default=0.0
+ ),
+ "matching_context_positions": deltas,
+ }
def check_effect(
- kind: str, base: dict[str, Any], a: dict[str, Any], b: dict[str, Any], restored: dict[str, Any]
+ kind: str,
+ base: dict[str, Any],
+ a: dict[str, Any],
+ b: dict[str, Any],
+ restored: dict[str, Any],
+ baseline_repeat: dict[str, Any] | None = None,
) -> dict[str, Any]:
if kind == "embedding":
vectors = [np.asarray(value["vectors"], dtype=np.float64) for value in (base, a, b, restored)]
@@ -223,22 +325,64 @@ def check_effect(
}
aa, bb, ab = (distribution_delta(x, y) for x, y in ((base, a), (base, b), (a, b)))
reset = distribution_delta(base, restored)
- minimum = max(MIN_PROBABILITY_EFFECT, EFFECT_DRIFT_MULTIPLIER * reset)
+ baseline = baseline_repeat if baseline_repeat is not None else base
+ baseline_drift = distribution_delta(base, baseline)
+ repeat_comparison = sequence_comparison(base, baseline)
+ reset_comparison = sequence_comparison(base, restored)
+ minimum = max(MIN_PROBABILITY_EFFECT, EFFECT_DRIFT_MULTIPLIER * max(reset, baseline_drift))
require(
- base["text"] == restored["text"] and reset < MAX_PROBABILITY_RESET_ERROR,
+ repeat_comparison["text_equal"]
+ and repeat_comparison["same_token_sequence"]
+ and repeat_comparison["max_aligned_chosen_probability_delta"] < MAX_PROBABILITY_RESET_ERROR
+ and repeat_comparison["max_aligned_probability_delta_lower_bound"] < MAX_PROBABILITY_RESET_ERROR,
+ "warm generation baseline was not stable",
+ )
+ require(
+ reset_comparison["text_equal"]
+ and reset_comparison["same_token_sequence"]
+ and reset_comparison["max_aligned_chosen_probability_delta"] < MAX_PROBABILITY_RESET_ERROR
+ and reset_comparison["max_aligned_probability_delta_lower_bound"] < MAX_PROBABILITY_RESET_ERROR
+ and reset < MAX_PROBABILITY_RESET_ERROR,
"base generation was not restored",
)
require(min(aa, bb, ab) > minimum, "LoRA generation had no observable effect beyond base drift")
return {
- "a_vs_base_first_token_probability_delta": aa,
- "b_vs_base_first_token_probability_delta": bb,
- "a_vs_b_first_token_probability_delta": ab,
- "base_reset_first_token_probability_delta": reset,
+ "a_vs_base_first_token_probability_delta_lower_bound": aa,
+ "b_vs_base_first_token_probability_delta_lower_bound": bb,
+ "a_vs_b_first_token_probability_delta_lower_bound": ab,
+ "base_reset_first_token_probability_delta_lower_bound": reset,
+ "baseline_first_token_probability_delta_lower_bound": baseline_drift,
+ "baseline_comparison": repeat_comparison,
+ "reset_comparison": reset_comparison,
"required_effect_minimum": minimum,
"base_text_restored": True,
}
+def record_check(
+ evidence: Evidence, failures: list[dict[str, str]], phase: str, check: Callable[[], dict[str, Any]]
+) -> dict[str, Any]:
+ """Continue independent proof phases after numeric assertions, never runtime errors."""
+ try:
+ result = check()
+ except AssertionError as error:
+ failure = {"phase": phase, "message": str(error)}
+ failures.append(failure)
+ evidence.emit("assertion_failed", **failure)
+ return {"passed": False, **failure}
+ evidence.emit("assertion_pass", phase=phase, **result)
+ return {"passed": True, **result}
+
+
+def check_buffered_native(results: dict[str, dict[str, Any]]) -> dict[str, Any]:
+ require(results["warm_1"]["text"] == results["warm_2"]["text"], "native buffered warm baseline text was not stable")
+ require(results["warm_2"]["text"] == results["reset"]["text"], "native buffered base text did not restore")
+ return {
+ "first_vs_warm_text_equal": results["first"]["text"] == results["warm_2"]["text"],
+ "warm_text_restored": True,
+ }
+
+
def configs(directory: Path, fixtures: Path) -> dict[str, Any]:
directory.mkdir(parents=True, exist_ok=True)
result = {}
@@ -320,6 +464,7 @@ async def run_model(kind: str, registry: Any, url: str, evidence: Evidence, trac
client = Client(url, evidence)
others = []
pid = None
+ failures: list[dict[str, str]] = []
async def call(selection: str | None, phase: str, route: str = "chat") -> dict[str, Any]:
start = time.time_ns()
@@ -362,21 +507,64 @@ async def run_model(kind: str, registry: Any, url: str, evidence: Evidence, trac
evidence.emit("undeclared_denied", kind=kind, status=error.status_code, code=error.code)
else:
raise AssertionError("undeclared adapter was accepted")
- native_base = None
+ native: dict[str, dict[str, dict[str, Any]]] = {}
+ baseline_repeat = None
if kind == "generation":
- native_base = await call(None, "native_base", "generate")
- await call("a", "native_cold_a", "generate")
+ baseline_repeat = await call(None, "chat_base_warm_1")
+ warm = await call(None, "chat_base_warm_2")
+ evidence.emit(
+ "baseline_comparison",
+ route="chat",
+ first_vs_warm=sequence_comparison(base, warm),
+ warm_repeat=sequence_comparison(baseline_repeat, warm),
+ )
+ base = warm
+ for route in ("generate", "native_stream", "native_boundary"):
+ native[route] = {
+ phase: await call(None, f"{route}_base_{phase}", route) for phase in ("first", "warm_1", "warm_2")
+ }
+ if route != "generate":
+ evidence.emit(
+ "baseline_comparison",
+ route=route,
+ first_vs_warm=sequence_comparison(native[route]["first"], native[route]["warm_2"]),
+ warm_repeat=sequence_comparison(native[route]["warm_1"], native[route]["warm_2"]),
+ )
+ for route, values in native.items():
+ values["a"] = await call("a", f"{route}_a", route)
a = await call("a", "a")
b = await call("b", "cold_b")
require(await listing("a_b_ready") == {"pin", "a", "b"}, "ready listing omitted a selected adapter")
reset = await call(None, "base_after_a_b")
- effects = check_effect(kind, base, a, b, reset)
- evidence.emit("effect_pass", kind=kind, **effects)
+ if kind == "generation":
+ evidence.emit("restoration_comparison", route="chat", comparison=sequence_comparison(base, reset))
+ effects = record_check(
+ evidence, failures, f"{kind}_effects", lambda: check_effect(kind, base, a, b, reset, baseline_repeat)
+ )
+ native_effects = {}
if kind == "generation":
- await call("b", "native_b", "generate")
- native_reset = await call(None, "native_reset", "generate")
- require(native_base == native_reset, "native generation base did not restore")
+ for route, values in native.items():
+ values["b"] = await call("b", f"{route}_b", route)
+ values["reset"] = await call(None, f"{route}_reset", route)
+ if route == "generate":
+ native_effects[route] = record_check(
+ evidence, failures, route, lambda: check_buffered_native(values)
+ )
+ else:
+ evidence.emit(
+ "restoration_comparison",
+ route=route,
+ comparison=sequence_comparison(values["warm_2"], values["reset"]),
+ )
+ native_effects[route] = record_check(
+ evidence,
+ failures,
+ route,
+ lambda: check_effect(
+ "generation", values["warm_2"], values["a"], values["b"], values["reset"], values["warm_1"]
+ ),
+ )
barrier = threading.Barrier(2)
others = [Client(url, evidence), Client(url, evidence)]
streams = await asyncio.gather(
@@ -403,8 +591,16 @@ async def run_model(kind: str, registry: Any, url: str, evidence: Evidence, trac
previous = ready
require(evicted and "pin" not in evicted, "churn did not evict dynamic adapters while preserving pin")
restored = await call(None, "base_after_churn")
- post_churn_effects = check_effect(kind, base, a, b, restored)
- evidence.emit("post_churn_effect_pass", kind=kind, **post_churn_effects)
+ if kind == "generation":
+ evidence.emit(
+ "restoration_comparison", route="chat_after_churn", comparison=sequence_comparison(base, restored)
+ )
+ post_churn_effects = record_check(
+ evidence,
+ failures,
+ f"{kind}_post_churn_effects",
+ lambda: check_effect(kind, base, a, b, restored, baseline_repeat),
+ )
cold = {
row["selection"]
for row in client.responses
@@ -422,6 +618,8 @@ async def run_model(kind: str, registry: Any, url: str, evidence: Evidence, trac
"cold_retried": sorted(cold),
"evicted": sorted(evicted),
"pin_preserved": True,
+ "assertion_failures": failures,
+ "passed": not failures,
}
if kind == "generation":
forwards = [row for row in batch_rows(trace) if row.get("event") == "forward"]
@@ -431,8 +629,14 @@ async def run_model(kind: str, registry: Any, url: str, evidence: Evidence, trac
set(ALIASES).issubset(seen) and len(seen) > capacity,
"successful churn did not exceed actual GPU slot count",
)
- result.update({"gpu_slot_count": capacity, "distinct_forward_adapters": sorted(seen)})
- evidence.emit("model_pass", kind=kind, **result)
+ result.update(
+ {
+ "gpu_slot_count": capacity,
+ "distinct_forward_adapters": sorted(seen),
+ "native_effects": native_effects,
+ }
+ )
+ evidence.emit("model_result", kind=kind, **result)
await registry.unload_async(model)
require(process.poll() is not None, "owned engine still running after sequential unload")
evidence.emit("engine_stopped", kind=kind, pid=pid, returncode=process.poll())
@@ -504,6 +708,10 @@ async def run(args: argparse.Namespace) -> None:
summary["models"][kind] = await run_model(
kind, app.state.registry, url, evidence, output / "batches.jsonl"
)
+ require(
+ all(result["passed"] for result in summary["models"].values()),
+ "required acceptance assertions failed; see model results and events",
+ )
summary["passed"] = True
except BaseException as error:
summary["error"] = {"type": type(error).__name__, "message": str(error)}
diff --git a/tools/benchmarks/runtime_lora/tests/test_probe.py b/tools/benchmarks/runtime_lora/tests/test_probe.py
index d56a6d9b2..706bf9df7 100644
--- a/tools/benchmarks/runtime_lora/tests/test_probe.py
+++ b/tools/benchmarks/runtime_lora/tests/test_probe.py
@@ -17,6 +17,7 @@ import torch
from peft import PeftModel
from safetensors.torch import load_file
from sie_sdk._msgpack import packb as pack_msgpack
+from sie_sdk.client.errors import ServerError
from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter
from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
from sie_server.config.model import ModelConfig
@@ -26,7 +27,20 @@ from transformers import Qwen3Config, Qwen3ForCausalLM
from tools.benchmarks.runtime_lora.adapters import ObservedGenerationAdapter
from tools.benchmarks.runtime_lora.fixtures import MODELS, digest, write_adapter
from tools.benchmarks.runtime_lora.observer import patch_scheduler
-from tools.benchmarks.runtime_lora.probe import Client, Evidence, batch_rows, check_effect, configs, mixed_batches
+from tools.benchmarks.runtime_lora.probe import (
+ BOUNDARY_PROMPT,
+ Client,
+ Evidence,
+ batch_rows,
+ check_buffered_native,
+ check_effect,
+ configs,
+ mixed_batches,
+ probability,
+ record_check,
+ sequence_comparison,
+ token_distribution_comparison,
+)
def tiny_config() -> Qwen3Config:
@@ -121,7 +135,7 @@ def test_sdk_observer_captures_cold_503_and_native_retry(tmp_path: Path) -> None
client = Client("http://localhost", Evidence(tmp_path), transport=httpx.MockTransport(respond))
try:
- assert client.call("generation", MODELS["generation"][0], "a", "generate") == {"text": "ok"}
+ assert client.call("generation", MODELS["generation"][0], "a", "generate") == {"text": "ok", "usage": None}
assert [row["status"] for row in client.responses] == [503, 200]
assert all(request["lora_adapter"] == "a" for request in calls)
assert client.responses[0]["code"] == "LORA_LOADING"
@@ -129,6 +143,74 @@ def test_sdk_observer_captures_cold_503_and_native_retry(tmp_path: Path) -> None
client.close()
[email protected]("route", ["native_stream", "native_boundary"])
+def test_native_stream_sdk_retains_terminal_logprobs_and_retries_only_http_cold_refusal(
+ tmp_path: Path, route: str
+) -> None:
+ calls = []
+ first = {"token": "one", "logprob": -0.1}
+ last = {"token": "two", "logprob": -0.2}
+
+ def respond(request: httpx.Request) -> httpx.Response:
+ calls.append(json.loads(request.content))
+ if len(calls) == 1:
+ return httpx.Response(
+ 503, json={"error": {"code": "LORA_LOADING", "message": "loading"}}, headers={"Retry-After": "0"}
+ )
+ chunks = [
+ {"text_delta": "one", "logprobs": [first], "done": False},
+ {
+ "text_delta": "two",
+ "logprobs": [last],
+ "done": True,
+ "finish_reason": "length",
+ "usage": {"completion_tokens": 2},
+ },
+ ]
+ return httpx.Response(
+ 200,
+ text="".join(f"data: {json.dumps(chunk)}\n\n" for chunk in chunks) + "data: [DONE]\n\n",
+ headers={"Content-Type": "text/event-stream"},
+ )
+
+ client = Client("http://localhost", Evidence(tmp_path), transport=httpx.MockTransport(respond))
+ try:
+ result = client.call("generation", MODELS["generation"][0], "a", route)
+ assert result["text"] == "onetwo"
+ assert result["logprobs"]["content"] == [first, last]
+ assert [row["status"] for row in client.responses] == [503, 200]
+ assert all(request["stream"] and request["logprobs"] and request["top_logprobs"] == 20 for request in calls)
+ assert all(
+ request["lora_adapter"] == "a" and request["temperature"] == 0 and request["seed"] == 17
+ for request in calls
+ )
+ assert calls[-1]["max_new_tokens"] == (1 if route == "native_boundary" else 24)
+ if route == "native_boundary":
+ assert calls[-1]["prompt"] == BOUNDARY_PROMPT
+ finally:
+ client.close()
+
+
+def test_native_stream_does_not_retry_an_error_after_http_success(tmp_path: Path) -> None:
+ calls = []
+
+ def respond(request: httpx.Request) -> httpx.Response:
+ calls.append(request)
+ error = {"done": True, "finish_reason": "error", "error": {"code": "LORA_LOADING", "message": "late failure"}}
+ return httpx.Response(
+ 200, text=f"data: {json.dumps(error)}\n\ndata: [DONE]\n\n", headers={"Content-Type": "text/event-stream"}
+ )
+
+ client = Client("http://localhost", Evidence(tmp_path), transport=httpx.MockTransport(respond))
+ try:
+ with pytest.raises(ServerError):
+ client.call("generation", MODELS["generation"][0], "a", "native_stream")
+ assert len(calls) == 1
+ assert "fresh_sdk_generation_retry" not in (tmp_path / "events.jsonl").read_text()
+ finally:
+ client.close()
+
+
@pytest.mark.parametrize("error_content_type", ["application/json", "application/msgpack"])
def test_sdk_observer_captures_msgpack_selection_and_automatic_encode_retry(
tmp_path: Path, error_content_type: str
@@ -188,9 +270,20 @@ def test_observer_records_actual_successful_batch_and_does_not_change_result(
)
)
)
- batch = SimpleNamespace(
- forward_mode="DECODE", reqs=[SimpleNamespace(rid="1", lora_id=uid_a), SimpleNamespace(rid="2", lora_id=uid_b)]
- )
+
+ def req(rid, uid):
+ return SimpleNamespace(
+ rid=rid,
+ lora_id=uid,
+ extra_key=uid,
+ cached_tokens=3,
+ prefix_indices=[0, 1, 2],
+ extend_input_len=2,
+ origin_input_ids=[1, 2, 3, 4, 5],
+ output_ids=[],
+ )
+
+ batch = SimpleNamespace(forward_mode="DECODE", reqs=[req("1", uid_a), req("2", uid_b)])
assert scheduler.run_batch(batch, extra=3) is result
assert seen == [(batch, 3)]
with pytest.raises(ValueError, match="forward failed"):
@@ -198,7 +291,17 @@ def test_observer_records_actual_successful_batch_and_does_not_change_result(
rows = batch_rows(trace)
assert len(rows) == 1
assert rows[0]["gpu_slot_count"] == 2
- assert rows[0]["requests"][0] == {"rid": "1", "uid": uid_a, "lora": "a"}
+ assert rows[0]["requests"][0] == {
+ "rid": "1",
+ "uid": uid_a,
+ "lora": "a",
+ "cache_key": uid_a,
+ "cached_tokens": 3,
+ "prefix_length": 3,
+ "extend_input_length": 2,
+ "input_length": 5,
+ "output_length": 0,
+ }
assert rows[0]["gpu_slots"] == [{"uid": uid_a, "lora": "a", "slot": 0}, {"uid": uid_b, "lora": "b", "slot": 1}]
assert mixed_batches(rows, 0, 2**64) == rows
rows[0]["gpu_slot_uids"][1] = uid_a
@@ -215,7 +318,7 @@ def test_observer_records_actual_successful_batch_and_does_not_change_result(
pool = scheduler.tp_worker.model_runner.lora_manager.memory_pool
pool.buffer_id_to_uid = [None, pool_module.EMPTY_SLOT]
pool.uid_to_buffer_id = {None: 0}
- batch.reqs = [SimpleNamespace(rid="base", lora_id=None)]
+ batch.reqs = [req("base", None)]
assert scheduler.run_batch(batch) is result
base_row = batch_rows(trace)[-1]
assert base_row["gpu_slot_uids"] == [None, {"empty_slot": True}]
@@ -262,7 +365,9 @@ def test_child_observer_defers_import_and_preserves_production_hook(
"scheduler = Scheduler()\n"
"scheduler.tp_worker = S(model_runner=S(lora_manager=S(lora_refs={}, "
"memory_pool=S(buffer_id_to_uid=[None], uid_to_buffer_id={None: 0}))))\n"
- "assert scheduler.run_batch(S(forward_mode='DECODE', reqs=[S(rid='r', lora_id=None)])) == 47\n"
+ "req = S(rid='r', lora_id=None, extra_key=None, cached_tokens=0, prefix_indices=[], "
+ "extend_input_len=1, origin_input_ids=[1], output_ids=[])\n"
+ "assert scheduler.run_batch(S(forward_mode='DECODE', reqs=[req])) == 47\n"
)
result = subprocess.run( # noqa: S603 — fixed synthetic package and script, no external input
[sys.executable, "-c", script], cwd=tmp_path, env=environment, capture_output=True, text=True, check=False
@@ -271,7 +376,8 @@ def test_child_observer_defers_import_and_preserves_production_hook(
rows = batch_rows(trace)
assert [row["event"] for row in rows] == ["observer_installed", "forward"]
assert rows[0]["slot_release_compat"] is True
- assert rows[1]["requests"] == [{"rid": "r", "uid": None, "lora": None}]
+ assert rows[1]["requests"][0]["uid"] is None
+ assert rows[1]["requests"][0]["prefix_length"] == 0
def test_effect_checks_fail_for_ignored_adapters_and_contaminated_base() -> None:
@@ -301,3 +407,109 @@ def test_effect_checks_require_delta_beyond_observed_numeric_drift() -> None:
assert check_effect(kind, base, build(0.5 + a), build(0.5 + b), base)
with pytest.raises(AssertionError, match="beyond base drift"):
check_effect(kind, base, build(0.5 + a), build(0.5 + b), build(0.5 + reset))
+
+
+def test_generation_restoration_checks_later_tokens_and_pre_adapter_baseline() -> None:
+ def result(first: float, second: float = 0.6, text: str = "same") -> dict:
+ return {
+ "text": text,
+ "logprobs": {
+ "content": [
+ {"token": "first", "logprob": math.log(first)},
+ {"token": "second", "logprob": math.log(second)},
+ ]
+ },
+ }
+
+ base, a, b = result(0.5), result(0.6), result(0.7)
+ assert check_effect("generation", base, a, b, base, base)
+ with pytest.raises(AssertionError, match="not restored"):
+ check_effect("generation", base, a, b, result(0.5, second=0.55), base)
+ with pytest.raises(AssertionError, match="not restored"):
+ check_effect("generation", base, a, b, result(0.5, text="different later text"), base)
+ with pytest.raises(AssertionError, match="baseline was not stable"):
+ check_effect("generation", base, a, b, base, result(0.5, second=0.55))
+ with pytest.raises(AssertionError, match="beyond base drift"):
+ check_effect("generation", base, result(0.501), result(0.502), base, result(0.5003))
+ shifted_alternate = result(0.5)
+ base["logprobs"]["content"][1]["top_logprobs"] = [
+ {"token": "second", "logprob": math.log(0.6)},
+ {"token": "alternate", "logprob": math.log(0.2)},
+ ]
+ shifted_alternate["logprobs"]["content"][1]["top_logprobs"] = [
+ {"token": "second", "logprob": math.log(0.6)},
+ {"token": "alternate", "logprob": math.log(0.3)},
+ ]
+ with pytest.raises(AssertionError, match="not restored"):
+ check_effect("generation", base, a, b, shifted_alternate, base)
+ with pytest.raises(AssertionError, match="baseline was not stable"):
+ check_effect("generation", base, a, b, base, shifted_alternate)
+
+
+def test_sequence_comparison_stops_after_context_diverges() -> None:
+ def result(tokens: list[str]) -> dict:
+ return {
+ "text": "".join(tokens),
+ "logprobs": {"content": [{"token": token, "logprob": -0.2} for token in tokens]},
+ }
+
+ comparison = sequence_comparison(result(["same", "a", "suffix"]), result(["same", "b", "suffix"]))
+ assert comparison["same_token_sequence"] is False
+ assert len(comparison["matching_context_positions"]) == 2
+ assert comparison["matching_context_positions"][-1]["chosen_probability_delta"] is None
+
+
+def test_top_k_boundary_changes_do_not_imply_zero_probability() -> None:
+ def token(alternate: str, value: float) -> dict:
+ return {
+ "token": "chosen",
+ "logprob": math.log(0.6),
+ "top_logprobs": [
+ {"token": "chosen", "logprob": math.log(0.6)},
+ {"token": alternate, "logprob": math.log(value)},
+ ],
+ }
+
+ comparison = token_distribution_comparison(token("a", 0.01), token("b", 0.01001))
+ assert comparison["shared_probability_delta"] == 0
+ assert comparison["probability_delta_lower_bound"] == pytest.approx(0.00001)
+ assert len(comparison["support_changes"]) == 2
+ assert token_distribution_comparison(token("a", 0.01), token("b", 0.2))[
+ "probability_delta_lower_bound"
+ ] == pytest.approx(0.19)
+
+
[email protected]("invalid", [float("nan"), float("inf"), 0.1])
+def test_later_invalid_logprobs_cannot_disappear_from_comparison(invalid: float) -> None:
+ base = {"text": "same", "logprobs": {"content": [{"token": "a", "logprob": -0.1}, {"token": "b", "logprob": -0.2}]}}
+ invalid_result = {
+ "text": "same",
+ "logprobs": {"content": [{"token": "a", "logprob": -0.1}, {"token": "b", "logprob": invalid}]},
+ }
+ with pytest.raises(AssertionError, match="invalid token log probability"):
+ sequence_comparison(base, invalid_result)
+ assert probability(float("-inf")) == 0
+
+
+def test_native_failure_survives_later_independent_success_and_runtime_errors_abort(tmp_path: Path) -> None:
+ evidence, failures = Evidence(tmp_path), []
+ values = {
+ name: {"text": text}
+ for name, text in (("first", "cold"), ("warm_1", "warm"), ("warm_2", "warm"), ("reset", "wrong"))
+ }
+ native = record_check(evidence, failures, "native", lambda: check_buffered_native(values))
+ assert native["passed"] is False
+ for phase in ("mixed", "churn", "embedding"):
+ assert record_check(evidence, failures, phase, lambda: {"independent_evidence": True})["passed"] is True
+ assert failures == [{"phase": "native", "message": "native buffered base text did not restore"}]
+ values["reset"]["text"] = "warm"
+ assert check_buffered_native(values)["first_vs_warm_text_equal"] is False
+ values["warm_1"]["text"] = "unstable"
+ with pytest.raises(AssertionError, match="warm baseline"):
+ check_buffered_native(values)
+
+ def runtime_failure() -> dict:
+ raise RuntimeError("engine stopped")
+
+ with pytest.raises(RuntimeError, match="engine stopped"):
+ record_check(evidence, failures, "runtime", runtime_failure)