Skip to content

Commit 2bc35c4

Browse files
nood-co1ashhart
authored andcommitted
fix: the CUDA server answers malformed requests with 400 and failed ones with 500 or a stream error event
The CUDA server caught only RequestError. A request the checkpoint's chat template refused (raise_exception), a chat_template_kwargs that dict() could not convert, or a temperature, top_p, top_k or seed that did not convert closed the connection with no response. Sampling was resolved after a stream's headers and role chunk, so a streamed request with a bad temperature or seed ended after the role chunk. An engine failure closed the connection too: no response for a non-streamed request, no error event and no [DONE] for a streamed one. - Preparing a request now checks what it reads: chat_template_kwargs must be an object or null (null is read as absent; every other value, [], "", false and 0 included, is refused), a template refusal becomes "the chat template rejected the request: ...", and temperature, top_p, top_k and seed go through parse_numbers, as on the Mac. The Sampling is built there and carried on PreparedRequest, so check(), prepare() and GlmApp.check refuse the same requests, and a streamed one is refused with HTTP 400 before its headers. - Any other failure while preparing gets HTTP 400 with its message, as on the Mac, and is logged with its traceback. A body that is not UTF-8 gets the existing "not JSON" 400. - A failure during generation is logged with its traceback and answered as the Mac server answers it: HTTP 500 {"error": {"message"}} for a non-streamed request, an error event of type server_error then [DONE] for a streamed one. - Valid requests make the same engine calls with the same Sampling; it is built before the stream opens instead of after. Accepted before, refused now: a boolean in any of the four sampling fields (read as 1 or 0), a non-finite temperature or top_p, a non-integral top_k or seed (truncated before), a malformed top_p, top_k or seed on a greedy request (not read before), chat_template_kwargs as [], "", false or 0 (read as absent before), and chat_template_kwargs as a list of key/value pairs. Tests: tests/test_cuda_server_errors.py (202 cases; 140 fail without the fix; the 60 that check valid requests reach the engine with the same Sampling, and the 2 that check a null or empty chat_template_kwargs is read as absent, pass with and without it), and tests/cuda/test_qwen27_server_errors.py for the 27B checkpoint and engine on a GPU. (cherry picked from commit 4236863)
1 parent 5fd5bf7 commit 2bc35c4

3 files changed

Lines changed: 508 additions & 18 deletions

File tree

‎src/tensorfold/cuda/server.py‎

Lines changed: 61 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import json
66
import threading
77
import time
8+
import traceback
89
import uuid
910
from datetime import datetime
1011
from contextlib import nullcontext
@@ -18,6 +19,7 @@
1819
from tensorfold.server.http import Server
1920
from tensorfold.server.messages import (_normalize_tool_call_arguments, late_system_role, normalize_messages,
2021
validate_modalities)
22+
from tensorfold.server.request_options import parse_numbers
2123
from tensorfold.server.tool_policy import ToolCallPolicy
2224
from tensorfold.engine.call_gate import CallGate, call_format, generate_gated
2325
from tensorfold.server.tools import active_tool_specs, tool_choice_requires_call
@@ -66,12 +68,16 @@ def render(self, messages: list[dict[str, Any]], *, tools: list[dict[str, Any]]
6668

6769
# -- HTTP ------------------------------------------------------------------------------------
6870

71+
_SAMPLING_FIELDS = ("temperature", "top_p", "top_k", "seed")
72+
73+
6974
@dataclass(slots=True)
7075
class PreparedRequest:
7176
prompt: list[int]
7277
max_tokens: int
7378
tools: list[dict[str, Any]]
7479
thinking: bool
80+
sampling: Any # the engine's ``Sampling``, or None for greedy decoding
7581

7682

7783
def _native_context(model_dir: Path) -> int:
@@ -156,27 +162,38 @@ def _requested_tokens(self, body: dict[str, Any]) -> int:
156162
return max(1, int(body.get("max_tokens") or body.get("max_completion_tokens") or self.max_tokens))
157163

158164
def _prepare(self, body: dict[str, Any], chat: bool) -> PreparedRequest:
165+
from jinja2.exceptions import TemplateError
166+
159167
validate_modalities(body)
160168
ToolCallPolicy(body)
161169
max_tokens = self._requested_tokens(body)
162170
try:
163171
tools = active_tool_specs(body.get("tools"), body.get("tool_choice"))
164172
except ValueError as exc:
165173
raise RequestError(str(exc)) from None
166-
kwargs = dict(body.get("chat_template_kwargs") or {})
174+
kwargs = body.get("chat_template_kwargs")
175+
if kwargs is None: # absent or null: the server's defaults
176+
kwargs = {}
177+
elif not isinstance(kwargs, dict): # [], "", false and 0 included
178+
raise RequestError("chat_template_kwargs must be a JSON object or null")
179+
kwargs = dict(kwargs)
167180
thinking = bool(kwargs.pop("enable_thinking", self.default_thinking))
168181
if chat:
169182
if not isinstance(body.get("messages"), list):
170183
raise RequestError("messages must be a list")
171-
text = self.template.render(body["messages"], tools=tools, enable_thinking=thinking, extra=kwargs)
184+
try:
185+
text = self.template.render(body["messages"], tools=tools, enable_thinking=thinking, extra=kwargs)
186+
except TemplateError as exc: # the checkpoint's template refuses the request (``raise_exception``)
187+
raise RequestError(f"the chat template rejected the request: {exc}") from exc
172188
else:
173189
text = body.get("prompt")
174190
if not isinstance(text, str):
175191
raise RequestError("prompt must be a string")
176192
prompt = self.tok.encode(text, add_special_tokens=False).ids
177193
if not prompt:
178194
raise RequestError("rendered prompt is empty")
179-
return PreparedRequest(prompt, max_tokens, tools, thinking)
195+
# sampling is resolved here, so a malformed control is refused before a stream opens
196+
return PreparedRequest(prompt, max_tokens, tools, thinking, self.sampling_for(body, prompt))
180197

181198
def check(self, body: dict[str, Any], *, prepared: PreparedRequest | None = None) -> str | None:
182199
"""Why the request cannot run, or None; rendered before a stream's headers are sent."""
@@ -218,16 +235,17 @@ def prepare(self, body: dict[str, Any], chat: bool) -> PreparedRequest:
218235
return prepared
219236

220237
def sampling_for(self, body: dict[str, Any], prompt: list[int]):
221-
"""Keyed sampling (the seed, else one drawn from the prompt), or None for greedy decoding."""
238+
"""Keyed sampling (the seed, else one drawn from the prompt), or None for greedy; RequestError if malformed."""
222239

223240
from tensorfold.engine.exact_sampling import Sampling, seed_for
224241

225-
temp = float(body["temperature"] if body.get("temperature") is not None else self.sampling["temperature"])
242+
fields = parse_numbers({k: body[k] for k in _SAMPLING_FIELDS if body.get(k) is not None})
243+
temp = float(fields.get("temperature", self.sampling["temperature"]))
226244
if temp <= 0:
227245
return None
228-
seed = body.get("seed")
229-
top_k = body["top_k"] if body.get("top_k") is not None else self.sampling["top_k"]
230-
top_p = body["top_p"] if body.get("top_p") is not None else self.sampling["top_p"]
246+
seed = fields.get("seed")
247+
top_k = fields.get("top_k", self.sampling["top_k"])
248+
top_p = fields.get("top_p", self.sampling["top_p"])
231249
return Sampling(int(seed) if seed is not None else seed_for(prompt), temp, int(top_k), float(top_p))
232250

233251
def run(self, body: dict[str, Any], chat: bool, emit: Callable[[dict[str, Any]], bool], *,
@@ -238,7 +256,7 @@ def run(self, body: dict[str, Any], chat: bool, emit: Callable[[dict[str, Any]],
238256
prompt, max_tokens = prepared.prompt, prepared.max_tokens
239257
tools, thinking = prepared.tools, prepared.thinking
240258
policy = ToolCallPolicy(body)
241-
sampling = self.sampling_for(body, prompt)
259+
sampling = prepared.sampling
242260
out: list[int] = []
243261
sent = {"reasoning": 0, "content": 0}
244262
stopped = {"client": False}
@@ -352,6 +370,15 @@ def token_sha(tokens: list[int]) -> str:
352370
return hashlib.sha256(",".join(str(int(t)) for t in tokens).encode()).hexdigest()[:12]
353371

354372

373+
def _error_message(exc: BaseException) -> str:
374+
return str(exc) or type(exc).__name__
375+
376+
377+
def _log_error(exc: BaseException) -> None:
378+
print(f"[tensorfold] request error: {type(exc).__name__}: {exc}", flush=True)
379+
traceback.print_exception(exc)
380+
381+
355382
def make_handler(app: App):
356383
class Handler(BaseHTTPRequestHandler):
357384
protocol_version = "HTTP/1.1"
@@ -370,6 +397,16 @@ def _json(self, code: int, payload: dict[str, Any]) -> None:
370397
except (BrokenPipeError, ConnectionResetError): # the client has gone
371398
self.close_connection = True
372399

400+
def _stream_error(self, error: dict[str, Any]) -> None:
401+
"""End an open stream with an error event and ``[DONE]``, as the MLX server does."""
402+
403+
try:
404+
self.wfile.write(f"data: {json.dumps({'error': error})}\n\ndata: [DONE]\n\n".encode())
405+
self.wfile.flush()
406+
except OSError:
407+
pass
408+
self.close_connection = True
409+
373410
def do_GET(self):
374411
if self.path.rstrip("/") in ("/v1/models", "/models"):
375412
self._json(200, {"object": "list", "data": [{"id": app.served, "object": "model", "owned_by": "tensorfold"}]})
@@ -384,12 +421,15 @@ def do_POST(self):
384421
return self._json(404, {"error": "not found"})
385422
try:
386423
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
387-
except json.JSONDecodeError:
424+
except (json.JSONDecodeError, UnicodeDecodeError):
388425
return self._json(400, {"error": {"message": "the request body is not JSON", "type": "invalid_request_error"}})
389426
try:
390427
prepared = app.prepare(body, chat)
391428
except RequestError as exc:
392429
return self._json(400, {"error": {"message": str(exc), "type": "invalid_request_error"}})
430+
except Exception as exc: # any other failure to read the request is refused too, as on MLX
431+
_log_error(exc)
432+
return self._json(400, {"error": {"message": _error_message(exc)}})
393433
rid = f"chatcmpl-{uuid.uuid4().hex[:24]}" if chat else f"cmpl-{uuid.uuid4().hex[:24]}"
394434
created = int(time.time())
395435
stream = bool(body.get("stream"))
@@ -427,14 +467,10 @@ def emit(delta: dict[str, Any]) -> bool:
427467
self.close_connection = True
428468
return
429469
except RequestError as exc:
430-
error = {"error": {"message": str(exc), "type": "invalid_request_error"}}
431-
try:
432-
self.wfile.write(f"data: {json.dumps(error)}\n\ndata: [DONE]\n\n".encode())
433-
self.wfile.flush()
434-
except (BrokenPipeError, ConnectionResetError):
435-
pass
436-
self.close_connection = True
437-
return
470+
return self._stream_error({"message": str(exc), "type": "invalid_request_error"})
471+
except Exception as exc:
472+
_log_error(exc)
473+
return self._stream_error({"message": _error_message(exc), "type": "server_error"})
438474
if result["final"]:
439475
emit(result["final"])
440476
if result["calls"]:
@@ -462,6 +498,13 @@ def emit(delta: dict[str, Any]) -> bool:
462498
return
463499
except RequestError as exc:
464500
return self._json(400, {"error": {"message": str(exc), "type": "invalid_request_error"}})
501+
except Exception as exc:
502+
_log_error(exc)
503+
try:
504+
self._json(500, {"error": {"message": _error_message(exc)}})
505+
except OSError:
506+
pass
507+
return
465508
usage = {"prompt_tokens": result["prompt_tokens"], "completion_tokens": result["completion_tokens"],
466509
"total_tokens": result["prompt_tokens"] + result["completion_tokens"]}
467510
if chat:
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
"""The CUDA server on the real Qwen3.8-27B engine and checkpoint template: refused and failed requests get an answer,
2+
and the next reply is the same as before them."""
3+
4+
import http.client
5+
import json
6+
import os
7+
import threading
8+
from contextlib import contextmanager
9+
from http.server import ThreadingHTTPServer
10+
from pathlib import Path
11+
12+
import pytest
13+
import torch
14+
15+
if not torch.cuda.is_available():
16+
pytest.skip("CUDA only", allow_module_level=True)
17+
18+
MODEL = Path(os.environ.get("TF_QWEN27_MODEL", "/models/Qwen3.8-27B-MLX-4bit"))
19+
DRAFTER = os.environ.get("TF_QWEN27_DRAFTER", "") # the DFlash2 directory; unset serves --no-drafts
20+
pytestmark = pytest.mark.skipif(not (MODEL / "config.json").is_file(), reason="real checkpoint not mounted")
21+
22+
HI = [{"role": "user", "content": "Name three prime numbers."}]
23+
VALID = {"messages": HI, "max_tokens": 24, "temperature": 0.7, "seed": 7,
24+
"chat_template_kwargs": {"enable_thinking": False}}
25+
REFUSED = [ # (body, the start of the error message)
26+
({"messages": [{"role": "tool", "content": "x"}]},
27+
"the chat template rejected the request: No user query found in messages."),
28+
({"messages": HI, "chat_template_kwargs": {"reasoning_effort": "high"}},
29+
"the chat template rejected the request: Unexpected reasoning effort high."),
30+
({"messages": HI, "chat_template_kwargs": "x"}, "chat_template_kwargs must be a JSON object or null"),
31+
({"messages": HI, "temperature": "hot"}, "temperature must be a finite number or null"),
32+
({"messages": HI, "temperature": 0.7, "seed": "abc"}, "seed must be an integer or null"),
33+
]
34+
35+
36+
@pytest.fixture(scope="module")
37+
def app():
38+
from tensorfold.cuda.server import App
39+
from tensorfold.families.qwen3_5 import cuda_engine
40+
41+
engine = cuda_engine(MODEL, drafter=DRAFTER, no_drafts=not DRAFTER, context=2048, context_explicit=True)
42+
return App(engine, MODEL, "qwen27-cuda")
43+
44+
45+
@contextmanager
46+
def serving(app):
47+
from tensorfold.cuda.server import make_handler
48+
49+
httpd = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(app))
50+
worker = threading.Thread(target=httpd.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
51+
worker.start()
52+
try:
53+
yield httpd.server_port
54+
finally:
55+
httpd.shutdown()
56+
httpd.server_close()
57+
worker.join()
58+
59+
60+
def post(port, body):
61+
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=300)
62+
try:
63+
connection.request("POST", "/v1/chat/completions", json.dumps(body).encode(),
64+
{"Content-Type": "application/json"})
65+
response = connection.getresponse()
66+
return response.status, response.getheader("Content-Type"), response.read().decode()
67+
finally:
68+
connection.close()
69+
70+
71+
def events(text):
72+
return [line[6:] if line == "data: [DONE]" else json.loads(line[6:])
73+
for line in text.splitlines() if line.startswith("data: ")]
74+
75+
76+
def token_sha(port, stream):
77+
status, _, text = post(port, {**VALID, "stream": stream})
78+
assert status == 200
79+
if stream:
80+
return events(text)[-2]["tensorfold"]["token_sha"]
81+
return json.loads(text)["tensorfold"]["token_sha"]
82+
83+
84+
def test_refused_and_failed_requests_leave_the_next_reply_unchanged(app):
85+
with serving(app) as port:
86+
reference = token_sha(port, False)
87+
assert token_sha(port, True) == reference
88+
89+
for body, message in REFUSED:
90+
for stream in (False, True):
91+
status, kind, text = post(port, {**body, "stream": stream})
92+
assert (status, kind) == (400, "application/json")
93+
error = json.loads(text)["error"]
94+
assert error["type"] == "invalid_request_error" and error["message"].startswith(message)
95+
assert token_sha(port, False) == reference
96+
97+
# a failure part-way through a reply, raised through the engine's generate from its token callback: at the
98+
# first decode round, after the prefill's token (a drafted round can finish a short reply, so no later one)
99+
real = app.engine.generate
100+
101+
def failing(prompt, max_tokens, sampling, on_tokens, **kwargs):
102+
calls = [0]
103+
104+
def callback(new):
105+
calls[0] += 1
106+
if calls[0] == 2:
107+
raise RuntimeError("injected failure")
108+
return on_tokens(new)
109+
110+
return real(prompt, max_tokens, sampling, callback, **kwargs)
111+
112+
app.engine.generate = failing
113+
try:
114+
status, kind, text = post(port, VALID)
115+
assert (status, kind) == (500, "application/json")
116+
assert json.loads(text) == {"error": {"message": "injected failure"}}
117+
status, _, text = post(port, {**VALID, "stream": True})
118+
assert status == 200
119+
assert events(text)[-2:] == [{"error": {"message": "injected failure", "type": "server_error"}}, "[DONE]"]
120+
finally:
121+
del app.engine.generate
122+
assert token_sha(port, False) == reference
123+
assert token_sha(port, True) == reference

0 commit comments

Comments
 (0)