Skip to content

fix: the CUDA server answers malformed requests with 400 and failed ones with 500 or a stream error event - #61

Closed
nood-co1 wants to merge 1 commit into
ashhart:mainfrom
blockbrain-ai:contrib/cuda-server-error-responses
Closed

nood-co1 wants to merge 1 commit into
ashhart:mainfrom
blockbrain-ai:contrib/cuda-server-error-responses

Conversation

@nood-co1

@nood-co1 nood-co1 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The CUDA server catches only RequestError and, since 0.3.6.2, RequestCancelled (a client that has gone). Any other exception while a request is prepared or generated closes the connection without an error response. This PR makes the CUDA server answer these requests, with the Mac server's error responses:

  • A malformed request gets HTTP 400 with a message, before any stream opens. This covers a chat-template refusal, a chat_template_kwargs that is neither an object nor null ([], "", false and 0 included), a malformed temperature, top_p, top_k or seed, and a body that is not UTF-8.
  • A failure during generation gets HTTP 500 {"error": {"message": ...}} for a non-streamed request. A streamed request gets an error event of type server_error, then data: [DONE]. This includes a per-token failure that run re-raises after generate (fix: the CUDA server stops a request when its client has gone or its per-token work fails #57, in main since 0.3.6.2).
  • Any exception other than RequestError is logged as [tensorfold] request error: ... with its traceback.

0.3.6's fix for #51 is in the Mac server's tool-call parser (server/tools.py) and changes none of these cases (see Evidence and Overlaps).

Why

References are at main (71377a5, 0.3.6.2). In src/tensorfold/cuda/server.py:

  • do_POST catches only RequestError and RequestCancelled: in prepare (:389-392), in the streamed run (:424-437) and in the non-streamed run (:458-464). Anything else goes to socketserver's handle_error, and the socket is closed.
  • These escape today:
    • the checkpoint template's own refusals: raise_exception raises jinja2.exceptions.TemplateError (:44-45), and the render at :171 does not catch it;
    • dict(body.get("chat_template_kwargs") or {}) on a value it cannot convert, such as a non-empty string or a non-zero number (:166);
    • float(...) and int(...) on the sampling fields in sampling_for (:225-231).
  • sampling_for runs inside run (:241), after a stream's headers and role chunk are sent (:407-423). A streamed request with a bad temperature gets HTTP 200, the role chunk, then EOF.
  • An engine exception in run escapes the same way, as does a per-token failure that run re-raises after generate (:294-295). A non-streamed client gets no response. A streamed client gets the chunks sent so far, then EOF, with no error event and no [DONE].

The Mac server (src/tensorfold/server/http.py) answers setup errors with 400 (:194-199), ends an open stream with a server_error event then [DONE] (finish_stream, :281-295, used at :365-375), answers other failures with 500 (:444-450), and parses the numeric fields with parse_numbers (:148). docs/api.md says only MLX rejects malformed numeric controls with 400 (:39) and only MLX returns generation errors in the stream (:108).

Change

src/tensorfold/cuda/server.py:

  • App._prepare, so prepare(), check() and GlmApp.check refuse the same requests:
    • chat_template_kwargs must be a JSON object or null. Null is read as absent, as docs/api.md reads null sampling fields ("null sampling fields retain server defaults", :40) and as the Mac server reads it (server/http.py:174). The Mac server reads only enable_thinking and reasoning_effort from it and ignores a value that is not an object (:174-187). CUDA passes every key to the template, so every other value is refused, the falsy ones ([], "", false, 0) included;
    • the render catches jinja2.exceptions.TemplateError and raises RequestError("the chat template rejected the request: <the template's message>");
    • the Sampling is built here and carried on PreparedRequest in a new field, sampling. run() uses prepared.sampling, so a bad value is refused before any stream opens.
  • sampling_for: temperature, top_p, top_k and seed, when present and not null, go through server/request_options.parse_numbers, the Mac server's parser. Server defaults are read as before. stop and ignore_eos are left to the stop-string change in feat(cuda): stop strings on every CUDA engine, and ignore_eos on the 27B's CUDA engine #63.
  • do_POST, while preparing: any other exception gets HTTP 400 {"error": {"message": str(exc)}}, as on the Mac, and is logged with its traceback. A body that is not UTF-8 gets the existing "the request body is not JSON" 400 (json.loads on bytes raises UnicodeDecodeError there, not JSONDecodeError).
  • Non-streamed run: any other exception is logged and answered with HTTP 500. The write is guarded against a closed socket.
  • Streamed run: any other exception is logged. The stream ends with data: {"error": {"message": ..., "type": "server_error"}} and data: [DONE], and the connection closes. The existing invalid_request_error event uses the same guarded helper.
  • In both runs the new except Exception comes after except RequestCancelled, so a client that has gone still gets nothing more written.
  • An exception with an empty message is reported by its type name, for example AssertionError.

tests/cuda/test_qwen27_client_gone.py builds a PreparedRequest directly. It now passes app.sampling_for(body, prompt) as the new field, the Sampling that run built from the same body before (equal for all 25 of the test's prompt and sampling pairs, host check).

docs/api.md:

  • :39: both backends reject malformed temperature, top_p, top_k and seed with 400. MLX also rejects its other numeric controls.
  • :108: CUDA returns 400 before generation for a template refusal or a chat_template_kwargs that is neither an object nor null, and 500 for a generation error on a non-streamed request. After a stream opens, both backends send a server_error event, then [DONE].

Accepted before, refused with 400 now:

  • a boolean in any of the four fields (temperature: true sampled at 1.0);
  • a non-finite temperature or top_p: JSON NaN, Infinity or 1e400, or the strings "inf" and "nan";
  • a non-integral top_k or seed, such as 2.5 or 1.5, which were truncated;
  • a malformed top_p, top_k or seed on a greedy request, which was not read;
  • chat_template_kwargs as [], "", false or 0, which were read as absent;
  • chat_template_kwargs as a list of key/value pairs, which dict() accepted.

Not in this PR:

  • Two-rank recovery. On two ranks, an engine failure part-way through a request still leaves the pair needing a restart (from reading the code, not run). This PR changes only what the client receives.
  • reasoning_effort inside chat_template_kwargs. Since 0.3.6.2 the Mac server reads it there and maps high to xhigh (server/http.py:175-183). The CUDA server passes chat_template_kwargs to the template unchanged, and the Qwen3.8-27B template refuses high when thinking is on; with this PR that refusal is a 400 naming it, not a closed connection.
  • tool_choice "required" on a template without tool-call markup. 0.3.6.2 refuses it inside run (cuda/server.py:331), so a streamed one still gets the invalid_request_error event after the role chunk.

Exactness

Error paths only. Valid requests make the same engine calls with the same prompt and the same Sampling. Building the Sampling before the stream opens changes when it is built, not what it is.

  • For a value accepted before, parse_numbers returns what float() or int() returned, numeric strings and integral floats (20.0 for top_k, 42.0 for seed) included.
  • parse_numbers clamps top_k at 0. Sampling already did (engine/exact_sampling.py:24), so a negative top_k gives the same Sampling.
  • A host check called the old and new sampling_for on every combination of 33 values (absent, null, integers, integral and non-integral floats, infinities, NaN, booleans, numeric and non-numeric strings, a list, an object) in the four fields, under 3 server defaults: 3,557,763 bodies. The 382,347 that both accept get equal Sampling values, field types included. None that the old one refused is accepted now. Each of the 1,405,186 refused now falls under the list above.

No kernel, engine or decoding code changes.

Tests

Host: macOS 26.4.1, Python 3.13.5, PyTorch 2.11.0 CPU, jinja2 3.1.6, tokenizers 0.22.2. The whole-suite runs had an import-only stand-in for Triton (no kernel launches); the new file does not need it.

tests/test_cuda_server_errors.py (new, 204 cases) uses a stand-in engine, a text tokenizer, and a small template that refuses a history without a user message and, with thinking on, an unknown reasoning_effort, as the Qwen3.8-27B checkpoint's template does (its chat_template.jinja:46-50). HTTP cases serve the real handler on 127.0.0.1:0. It checks:

  • 22 malformed bodies, streamed and not, on /v1/chat/completions and /v1/completions: two template refusals, ten with a malformed sampling field, and chat_template_kwargs as [], "", false, 0, true, a number, a string, a JSON string, a list and a list of pairs. Each gets HTTP 400 application/json with the exact message, before any stream bytes. The engine is never called, and a valid request afterwards gets 200. check() returns the same message for all 22, and GlmApp.check for six.
  • A null or {} chat_template_kwargs renders the same prompt as an absent one and gets 200, streamed and not.
  • An unexpected exception while preparing gets 400 with its message and a logged traceback. A body that is not UTF-8 gets the "not JSON" 400.
  • The engine raising, with and without text already emitted, chat and completion: HTTP 500 (non-streamed), or the chunks already sent, the server_error event and [DONE] (streamed). Both log the line and a traceback and release the lock, so the next request gets 200.
  • An exception with no message is reported by its type name.
  • An unknown reasoning_effort with no enable_thinking in the request follows the server's thinking default: 400 with it on, 200 with it off. enable_thinking in the request decides it either way.
  • Valid sampling: through HTTP the engine gets the old sampling_for's Sampling (60 cases, which pass before and after), and prepare() carries the same value (60 cases).
Run Result
New file on main's sources (71377a5) 142 failed, 62 passed (the 60 valid-sampling HTTP cases and the 2 null or {} chat_template_kwargs cases)
New file on this branch 204 passed, with and without the Triton stand-in; 10 of 10 repeated runs passed
Whole host suite (tests without tests/cuda), main (71377a5) 136 failed, 2,082 passed, 299 skipped, 18 errors
Same, this branch 136 failed, 2,286 passed, 299 skipped, 18 errors

The same 154 ids fail or error on both, and none is in a CUDA server test. Their causes on this host include transformers classes that are not installed (AutoTokenizer, GenerationMixin), no Triton backends, MLX 0.31.1 where GLM-5.3-Flash needs 0.32.2, a memory-window case that expects a Mac with at least 64 GiB (this one has 36 GiB), and files outside src and tests (tools/, CHANGELOG.md) that the test tree used here did not include. Ten one-line breakages of the fix, each applied alone, each fail between 1 and 31 of the new cases; reading a falsy chat_template_kwargs as absent again fails 13.

tests/cuda/test_qwen27_server_errors.py (new, GPU) uses the real Qwen3.8-27B checkpoint and a one-rank engine:

  • five refused requests, streamed and not, get 400, using the checkpoint's own template: "No user query found", reasoning_effort high with enable_thinking true (the template reads the effort only with thinking on, and App has thinking off by default), chat_template_kwargs as a string, temperature "hot", seed "abc";
  • a failure raised from the token callback at the first decode round gets 500 or the stream error event;
  • a sampled request's token_sha is the same before the refused requests, after them and after the failures, streamed and not.

GPU status

All three steps passed. Surface: one DGX Spark (GB10); the tensorfold-bench image (PyTorch 2.13.0a0, NVIDIA 26.07; CUDA 13.3), TORCH_CUDA_ARCH_LIST=12.1; TensorFold 8e375a6, this branch on main 71377a5, imported from the branch's tree. The 27B is Qwen3.8-27B-MLX-4bit (70ae7fac), the drafter DFlash2 (50307d4c).

Step Command Model Result
1 TF_QWEN27_MODEL=<Qwen3.8-27B-MLX-4bit directory> python3 -m pytest tests/cuda/test_qwen27_server_errors.py the 27B, no drafter 1 passed
1 the same with TF_QWEN27_DRAFTER=<DFlash2 directory> added the 27B with DFlash2 1 passed
2 TF_QWEN27_MODEL=<Qwen3.8-27B-MLX-4bit directory> python3 -m pytest tests/cuda the 27B for test_qwen27_server_errors.py, toy models elsewhere 549 passed (test_qwen27_client_gone.py's 2 included), 71 skipped; main (71377a5): 548 passed, the same 71 skipped

The 71 skipped tests need EXL3, Nemotron or MLX checkpoints, ExLlamaV3, or TENSORFOLD_TEST_NCCL=1; 18 of them compare with ExLlamaV3 at rate and codebook pairs it does not support.

Step 3, tensorfold serve <Qwen3.8-27B-MLX-4bit directory> --drafter <DFlash2 directory> --tp 1, with the generation settings at their defaults:

  • {"messages": [{"role": "tool", "content": "x"}]}: HTTP 400 application/json, "the chat template rejected the request: No user query found in messages."
  • "temperature": "hot" with "stream": true: HTTP 400 application/json, "temperature must be a finite number or null". No stream opened.
  • The next request (64 greedy tokens, thinking off): HTTP 200, 64 tokens.
  • No traceback in the server log.

Evidence

Surface: macOS, the Qwen3.8-27B checkpoint's tokenizer and chat template, tensorfold.cuda.server, and a stand-in engine. The App had thinking on by default, as tensorfold serve has (--thinking); the template reads reasoning_effort only with thinking on. No model ran.

On main (71377a5; the same results at beddbb7, 85653c7 and 34bae79):

  • Five malformed requests each got Remote end closed connection without response: an assistant/tool-only history (the template's "No user query found"), chat_template_kwargs.reasoning_effort "high", chat_template_kwargs as a string, temperature "hot", and seed "abc".
  • temperature "hot" with "stream": true got HTTP 200, the role chunk, then EOF.
  • With the engine raising, a non-streamed request got no response, and a streamed one got the role chunk, then EOF.
  • chat_template_kwargs as [], "", false, 0 or a list of pairs got 200, streamed and not; true, 1.5 and "x" closed the connection.

On this branch:

  • The five got HTTP 400 with the template's message or the field's message (for example "temperature must be a finite number or null").
  • The streamed "hot" request got the same 400 before any stream bytes.
  • With the engine raising, a non-streamed request got HTTP 500 with the engine's message, and a streamed one got the role chunk, the server_error event, then [DONE].
  • Those eight chat_template_kwargs values got 400 "chat_template_kwargs must be a JSON object or null", streamed and not. Null and {} got 200.

On both, a valid request sent after all of these got 200.

Overlaps


Submitted by an agent from Blockbrain Labs (https://x.com/blockbrain_labs, https://github.com/blockbrain-ai).

…nes with 500 or a stream error event

The CUDA server caught only RequestError and RequestCancelled. 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, or a per-token failure that run() raises after generate, 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. A client that has gone still gets nothing more written.
- Valid requests make the same engine calls with the same Sampling; it is built before the stream opens instead of after.
- tests/cuda/test_qwen27_client_gone.py builds its PreparedRequest with app.sampling_for(body, prompt), the Sampling run() built from the same body before.

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 (204 cases; 142 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; its stand-in template, like the Qwen3.8-27B checkpoint's, reads reasoning_effort only with thinking on), and tests/cuda/test_qwen27_server_errors.py for the 27B checkpoint and engine on a GPU.
@ashhart

ashhart commented Sep 29, 2026

Copy link
Copy Markdown
Owner

Thank you, @nood-co1. This is in 0.3.6.3 under your name (2bc35c43). The CUDA server now answers a malformed
request with a 400 before anything runs, and a failed one with a 500, or with a server_error event and [DONE] once
a stream is open, as the Mac server does. On a Spark all six malformed cases came back as 400s, and the 27B's replies
were unchanged. We added one line to the docs: after a generation error on two CUDA ranks, restart both.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants