Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: a sampling field of the wrong type is a 400 that names it

midagedev1f6958c13b37
diff --git a/serve/server.py b/serve/server.py
index 19811fc11..b6e926fa2 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -5157,6 +5157,7 @@ def make_handler(svc: Service):
raise ValueError("a forced tool_choice with MCP tools is not supported")
svc.reasoning_budget(req) # a bad value is a 400 before anything is sent
stop_strings(req) # ... and so is a bad stop / stop_sequences
+ check_request_sampling(req) # ... and a sampling field of the wrong type
ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req)
_debug_req("openai", req, messages, tools, max_new, thinking, len(ids))
cancel = threading.Event()
@@ -5326,6 +5327,10 @@ def make_handler(svc: Service):
stop_strings(req)
except ValueError as e:
raise ResponsesError(str(e), "stop") from None
+ try:
+ check_request_sampling(req) # the request is also the sampling dict (see below)
+ except ValueError as e: # its message starts with the field's name: the param
+ raise ResponsesError(str(e), str(e).partition(":")[0]) from None
svc.load()
# #924 (opt-in): a Codex compaction request is rendered with its conversation's tools, so its prompt
# starts as the cached one did; the parser and the response keep the request's own tools
@@ -5358,6 +5363,7 @@ def make_handler(svc: Service):
req = svc.with_shared(req, "anthropic")
messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked)
stop_strings(req) # the same 400 as the request itself would get
+ check_request_sampling(req) # ... likewise a sampling field of the wrong type
self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw))})
def _anthropic(self, req):
@@ -5371,6 +5377,7 @@ def make_handler(svc: Service):
max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context
svc.reasoning_budget(req) # a bad value is a 400 before anything is sent
stop_strings(req) # ... and so is a bad stop / stop_sequences
+ check_request_sampling(req) # ... and a sampling field of the wrong type
ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req)
_debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids))
cancel = threading.Event()
@@ -5846,6 +5853,23 @@ def start_replicas(cfg: dict, groups: list[list[int]], exe: str, effort_end: lis
return rp.ReplicaEngine(engines, load_tokens=load)
+def check_request_sampling(req) -> None:
+ """A request's sampling field of the wrong JSON type ("temperature": "0.7", "top_k": 40.0, "seed": true) is a 400
+ that names the field, as the same value is through POST /settings or the run config. Unchecked, the value
+ replaced the configured default in run()'s merge and sampling_keys dropped it, so the reply was greedy. Only
+ types are checked: a number (int or float, never bool) for temperature, top_p, min_p and the three penalties; an
+ integer (never bool or float) for top_k, penalty_last_n and seed. Ranges behave as before (a temperature <= 0 is
+ greedy, top_k 0 or above 64 is clamped, a seed <= 0 is unset), and an absent or null field is not checked."""
+ for key, integer in (("temperature", False), ("top_p", False), ("min_p", False), ("presence_penalty", False),
+ ("frequency_penalty", False), ("repetition_penalty", False), ("top_k", True),
+ ("penalty_last_n", True), ("seed", True)):
+ value = (req or {}).get(key)
+ if value is None:
+ continue
+ if isinstance(value, bool) or not isinstance(value, int if integer else (int, float)):
+ raise ValueError(f"{key}: {'an integer' if integer else 'a number'}")
+
+
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--engine", choices=["mock", "strata"], default="mock")
diff --git a/serve/test_request_hardening.py b/serve/test_request_hardening.py
index 932780347..b7dcba40f 100644
--- a/serve/test_request_hardening.py
+++ b/serve/test_request_hardening.py
@@ -1,5 +1,5 @@
"""0.1.41 server hardening: a JSON body of the wrong shape is a 400 (not a dropped connection), an oversized body is a
-413 before it is read, a bad Content-Length is a 400.
+413 before it is read, a bad Content-Length is a 400, and a sampling field of the wrong type is a 400 that names it.
python -m unittest serve.test_request_hardening -v
"""
@@ -92,6 +92,44 @@ class Hardening(unittest.TestCase):
with mock.patch.dict(os.environ, {"STRATA_MAX_BODY_MIB": "junk"}):
self.assertEqual(body_limit(), 256 << 20)
+ # A request whose sampling field has the wrong JSON type is a 400 that names the field, not a greedy reply.
+ # Only types are checked: in-type values of any range, and null fields, answer as before.
+ def test_a_wrong_type_is_a_400_that_names_the_field(self):
+ chat = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8}
+ responses = {"model": "m", "input": "hi", "store": False, "max_output_tokens": 8}
+ for path, body, field in (
+ ("/v1/chat/completions", {**chat, "temperature": "0.7"}, "temperature"),
+ ("/v1/chat/completions", {**chat, "top_k": 40.0}, "top_k"),
+ ("/v1/chat/completions", {**chat, "seed": "7"}, "seed"),
+ ("/v1/messages", {**chat, "top_k": "40"}, "top_k"),
+ ("/v1/messages", {**chat, "repetition_penalty": "1.1"}, "repetition_penalty"),
+ ("/v1/messages", {**chat, "presence_penalty": True}, "presence_penalty"),
+ ("/v1/responses", {**responses, "top_p": True}, "top_p"),
+ ("/v1/responses", {**responses, "temperature": "0.7"}, "temperature"),
+ ("/v1/responses", {**responses, "seed": 7.5}, "seed"),
+ ("/v1/messages/count_tokens", {"messages": chat["messages"], "temperature": "0.7"},
+ "temperature")):
+ with self.subTest(path=path, field=field):
+ with mock.patch("builtins.print"):
+ code, out = self.post(path, body)
+ self.assertEqual(code, 400, (path, body, out))
+ self.assertIn(field, json.dumps(out))
+
+ def test_in_type_values_and_nulls_still_answer(self):
+ chat = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8, "temperature": 0, "top_k": 0,
+ "seed": 7}
+ code, out = self.post("/v1/chat/completions", chat)
+ self.assertEqual(code, 200, out)
+ code, out = self.post("/v1/messages", {**chat, "temperature": -1, "top_k": 100, "presence_penalty": 0.5,
+ "penalty_last_n": 64})
+ self.assertEqual(code, 200, out)
+ code, out = self.post("/v1/responses", {"model": "m", "input": "hi", "store": False, "max_output_tokens": 8,
+ "temperature": None, "top_p": None, "seed": None})
+ self.assertEqual(code, 200, out)
+ code, out = self.post("/v1/messages/count_tokens", {"messages": [{"role": "user", "content": "hi"}],
+ "temperature": 0.7})
+ self.assertEqual(code, 200, out)
+
if __name__ == "__main__":
unittest.main()