Repository navigation
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
Conversation
This was referenced Sep 28, 2026
Closed
…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.
nood-co1
force-pushed
the
contrib/cuda-server-error-responses
branch
from
September 28, 2026 18:45
4236863 to
8e375a6
Compare
This was referenced Sep 28, 2026
Closed
nood-co1
marked this pull request as ready for review
September 28, 2026 22:05
ashhart
added a commit
that referenced
this pull request
Sep 29, 2026
…t, which now carries it (#61)
Owner
|
Thank you, @nood-co1. This is in 0.3.6.3 under your name (2bc35c43). The CUDA server now answers a malformed |
BlivionIaG
referenced
this pull request
in BlivionIaG/TensorFold
Oct 20, 2026
…t, which now carries it (#61)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The CUDA server catches only
RequestErrorand, 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:chat_template_kwargsthat is neither an object nor null ([],"",falseand0included), a malformedtemperature,top_p,top_korseed, and a body that is not UTF-8.{"error": {"message": ...}}for a non-streamed request. A streamed request gets an error event of typeserver_error, thendata: [DONE]. This includes a per-token failure thatrunre-raises aftergenerate(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).RequestErroris 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). Insrc/tensorfold/cuda/server.py:do_POSTcatches onlyRequestErrorandRequestCancelled: in prepare (:389-392), in the streamed run (:424-437) and in the non-streamed run (:458-464). Anything else goes tosocketserver'shandle_error, and the socket is closed.raise_exceptionraisesjinja2.exceptions.TemplateError(:44-45), and the render at:171does 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(...)andint(...)on the sampling fields insampling_for(:225-231).sampling_forruns insiderun(:241), after a stream's headers and role chunk are sent (:407-423). A streamed request with a badtemperaturegets HTTP 200, the role chunk, then EOF.runescapes the same way, as does a per-token failure thatrunre-raises aftergenerate(: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 aserver_errorevent then[DONE](finish_stream,:281-295, used at:365-375), answers other failures with 500 (:444-450), and parses the numeric fields withparse_numbers(:148).docs/api.mdsays 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, soprepare(),check()andGlmApp.checkrefuse the same requests:chat_template_kwargsmust be a JSON object or null. Null is read as absent, asdocs/api.mdreads 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 onlyenable_thinkingandreasoning_effortfrom 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;jinja2.exceptions.TemplateErrorand raisesRequestError("the chat template rejected the request: <the template's message>");Samplingis built here and carried onPreparedRequestin a new field,sampling.run()usesprepared.sampling, so a bad value is refused before any stream opens.sampling_for:temperature,top_p,top_kandseed, when present and not null, go throughserver/request_options.parse_numbers, the Mac server's parser. Server defaults are read as before.stopandignore_eosare 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.loadson bytes raisesUnicodeDecodeErrorthere, notJSONDecodeError).data: {"error": {"message": ..., "type": "server_error"}}anddata: [DONE], and the connection closes. The existinginvalid_request_errorevent uses the same guarded helper.except Exceptioncomes afterexcept RequestCancelled, so a client that has gone still gets nothing more written.AssertionError.tests/cuda/test_qwen27_client_gone.pybuilds aPreparedRequestdirectly. It now passesapp.sampling_for(body, prompt)as the new field, theSamplingthatrunbuilt 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 malformedtemperature,top_p,top_kandseedwith 400. MLX also rejects its other numeric controls.:108: CUDA returns 400 before generation for a template refusal or achat_template_kwargsthat is neither an object nor null, and 500 for a generation error on a non-streamed request. After a stream opens, both backends send aserver_errorevent, then[DONE].Accepted before, refused with 400 now:
temperature: truesampled at 1.0);temperatureortop_p: JSONNaN,Infinityor1e400, or the strings"inf"and"nan";top_korseed, such as2.5or1.5, which were truncated;top_p,top_korseedon a greedy request, which was not read;chat_template_kwargsas[],"",falseor0, which were read as absent;chat_template_kwargsas a list of key/value pairs, whichdict()accepted.Not in this PR:
reasoning_effortinsidechat_template_kwargs. Since 0.3.6.2 the Mac server reads it there and mapshightoxhigh(server/http.py:175-183). The CUDA server passeschat_template_kwargsto the template unchanged, and the Qwen3.8-27B template refuseshighwhen 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 insiderun(cuda/server.py:331), so a streamed one still gets theinvalid_request_errorevent after the role chunk.Exactness
Error paths only. Valid requests make the same engine calls with the same prompt and the same
Sampling. Building theSamplingbefore the stream opens changes when it is built, not what it is.parse_numbersreturns whatfloat()orint()returned, numeric strings and integral floats (20.0fortop_k,42.0forseed) included.parse_numbersclampstop_kat 0.Samplingalready did (engine/exact_sampling.py:24), so a negativetop_kgives the sameSampling.sampling_foron 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 equalSamplingvalues, 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 unknownreasoning_effort, as the Qwen3.8-27B checkpoint's template does (itschat_template.jinja:46-50). HTTP cases serve the real handler on127.0.0.1:0. It checks:/v1/chat/completionsand/v1/completions: two template refusals, ten with a malformed sampling field, andchat_template_kwargsas[],"",false,0,true, a number, a string, a JSON string, a list and a list of pairs. Each gets HTTP 400application/jsonwith 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, andGlmApp.checkfor six.{}chat_template_kwargsrenders the same prompt as an absent one and gets 200, streamed and not.server_errorevent and[DONE](streamed). Both log the line and a traceback and release the lock, so the next request gets 200.reasoning_effortwith noenable_thinkingin the request follows the server's thinking default: 400 with it on, 200 with it off.enable_thinkingin the request decides it either way.sampling_for'sSampling(60 cases, which pass before and after), andprepare()carries the same value (60 cases).main's sources (71377a5){}chat_template_kwargscases)testswithouttests/cuda),main(71377a5)The same 154 ids fail or error on both, and none is in a CUDA server test. Their causes on this host include
transformersclasses 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 outsidesrcandtests(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 falsychat_template_kwargsas 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:reasoning_efforthighwithenable_thinkingtrue (the template reads the effort only with thinking on, andApphas thinking off by default),chat_template_kwargsas a string,temperature"hot",seed"abc";token_shais 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-benchimage (PyTorch 2.13.0a0, NVIDIA 26.07; CUDA 13.3),TORCH_CUDA_ARCH_LIST=12.1; TensorFold 8e375a6, this branch onmain71377a5, imported from the branch's tree. The 27B is Qwen3.8-27B-MLX-4bit (70ae7fac), the drafter DFlash2 (50307d4c).TF_QWEN27_MODEL=<Qwen3.8-27B-MLX-4bit directory> python3 -m pytest tests/cuda/test_qwen27_server_errors.pyTF_QWEN27_DRAFTER=<DFlash2 directory>addedTF_QWEN27_MODEL=<Qwen3.8-27B-MLX-4bit directory> python3 -m pytest tests/cudatest_qwen27_server_errors.py, toy models elsewheretest_qwen27_client_gone.py's 2 included), 71 skipped;main(71377a5): 548 passed, the same 71 skippedThe 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 400application/json, "the chat template rejected the request: No user query found in messages.""temperature": "hot"with"stream": true: HTTP 400application/json, "temperature must be a finite number or null". No stream opened.Evidence
Surface: macOS, the Qwen3.8-27B checkpoint's tokenizer and chat template,
tensorfold.cuda.server, and a stand-in engine. TheApphad thinking on by default, astensorfold servehas (--thinking); the template readsreasoning_effortonly with thinking on. No model ran.On
main(71377a5; the same results at beddbb7, 85653c7 and 34bae79):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_kwargsas a string,temperature"hot", andseed"abc".temperature"hot"with"stream": truegot HTTP 200, the role chunk, then EOF.chat_template_kwargsas[],"",false,0or a list of pairs got 200, streamed and not;true,1.5and"x"closed the connection.On this branch:
"hot"request got the same 400 before any stream bytes.server_errorevent, then[DONE].chat_template_kwargsvalues 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
except RequestCancelledcomes before this PR'sexcept Exceptionin both runs, and a per-token failure it re-raises aftergenerategets this PR's 500 or stream error event. Itstests/cuda/test_qwen27_client_gone.pygets the one-line change above.docs/api.md(one paragraph) and in four places incuda/server.py: the imports,PreparedRequest's fields,_prepare's return and thesamplingline inrun. Resolution: keep both imports; putsampling, which has no default, beforeignore_eosandstop; build the request with all three; takeprepared.samplinginrun. With that, both PRs' host test files pass on 0.3.6.2: 399 tests.cuda/server.py:PreparedRequest's fields (samplingagainstgrammar),_prepare's return, and the error handlers of the streamed and the non-streamed run (this PR'sexcept Exceptionagainst feat(cuda): response_format JSON schemas on the 27B, exact under drafting and --parallel #80'sGrammarError).docs/api.mdmerges clean. Resolution: putsampling, which has no default, beforegrammar; compile the grammar in_prepare, then build the request with both; in each handler, put feat(cuda): response_format JSON schemas on the 27B, exact under drafting and --parallel #80'sGrammarErrorclause (aserver_errorevent, or HTTP 500 with that type) before this PR'sexcept Exception. With that, both PRs' host test files pass: 229 passed, 14 skipped (feat(cuda): response_format JSON schemas on the 27B, exact under drafting and --parallel #80's cases that need xgrammar, which is not installed on the test host).cuda/server.py. Git merges it with this branch with no conflict, and both PRs' host files pass on the merge: 205 tests.docs/api.md, and changesserver/messages.pyandserver/errors.py, which the CUDA server imports. Git merges it with this branch with no conflict, and this PR's host file passes on the merge.tests/cuda/test_qwen27_client_gone.py, on other lines. Git merges it with this branch with no conflict, and both PRs' host files pass on the merge (486 passed; 5 skipped, that PR's template tests without the tokenizer files). fix: say why a CUDA start is silent (SIGUSR1 stack dump, extension builds, stale build locks) #62, CUDA: read the Flash Next NVFP4 (ModelOpt FP4) checkpoint as it ships #67, perf: Flash Next reads a prompt chunk's n-gram rows on 16 threads (same bytes) #73, fix: preserve prefixes when checkpoint cannot fit #74, fix: the CUDA server types Qwen tool parameters by the tool's schema #75, fix: qwen3_5_moe CUDA graphs capture into a new pool after the buffers grow #78 and perf: Improve cuda startup/loading performance (3-15x faster on DGX spark) #82 share no file with this PR.parse_tool_calls, which 0.3.6.2 moved tocuda/reply_text.py(:77). It runs insiderun(cuda/server.py:307), so with this PR an exception from it would get the 500 or the stream error event. On the inputs of 0.3.6'stests/test_tool_call_content.pyit raises on none, and returns the same content and calls at 34bae79 and 71377a5.Submitted by an agent from Blockbrain Labs (https://x.com/blockbrain_labs, https://github.com/blockbrain-ai).