Skip to content

Commit 24afe5e

Browse files
nood-co1ashhart
authored andcommitted
fix: the CUDA server stops a request when its client has gone or its per-token work fails
The CUDA server stopped a request only when a streamed write failed with a broken pipe or a reset. A non-streamed request always ran to its reply limit, a stream stopped only at a round that wrote text (not inside a hidden tool call), and a request queued behind the server lock was prefilled and decoded after its client had left. A write that timed out, or any other failure in the per-token callback, raised into the engine's decode loop; with two ranks that skips the stop that keeps rank 1 in step. - App.run takes cancelled=; the handler passes the Mac server's socket check (socket_cancellation) for streamed and non-streamed requests. The callback checks it every round, with or without new text, and asks the engine to stop. - A request whose client left while it waited for the lock raises RequestCancelled before generate: no prefill, no engine call, nothing written. - A request stopped for its client raises RequestCancelled once generate returns, as on the Mac server: no final chunk, no [DONE], no JSON reply. A client that has only shut its sending side does not get the stopped prefix as a whole reply with finish_reason "length". - The callback never raises into the engine. A failure is kept, the engine is asked to stop, and the failure is raised after generate returns. After a stop or a failure the callback returns True at once, for the engines that finish on both ranks and keep calling. - A streamed write treats any OSError (timed out, host unreachable) as a client that has gone; the JSON reply ignores a broken pipe or a reset. Engines stop through the path a failed streamed write already takes. No engine or arithmetic change; tokens sent before a stop are unchanged. Not covered: a request waiting inside the concurrent scheduler before admission is prefilled, then stops after its first round. Test: tests/test_cuda_server_disconnect.py (17 cases; 14 fail without the fix). (cherry picked from commit c55cb7d)
1 parent 6f474d1 commit 24afe5e

3 files changed

Lines changed: 478 additions & 23 deletions

File tree

‎src/tensorfold/cuda/server.py‎

Lines changed: 54 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from pathlib import Path
1515
from typing import Any, Callable
1616

17+
from tensorfold.server.cancellation import RequestCancelled, socket_cancellation
1718
from tensorfold.server.errors import RequestError
1819
from tensorfold.server.http import Server
1920
from tensorfold.server.messages import (_normalize_tool_call_arguments, late_system_role, normalize_messages,
@@ -355,7 +356,11 @@ def sampling_for(self, body: dict[str, Any], prompt: list[int]):
355356
return Sampling(int(seed) if seed is not None else seed_for(prompt), temp, int(top_k), float(top_p))
356357

357358
def run(self, body: dict[str, Any], chat: bool, emit: Callable[[dict[str, Any]], bool], *,
358-
prepared: PreparedRequest | None = None) -> dict[str, Any]:
359+
prepared: PreparedRequest | None = None, cancelled: Callable[[], bool] | None = None) -> dict[str, Any]:
360+
"""One reply. ``cancelled()`` is true once the client has gone: a request that has not started raises
361+
``RequestCancelled`` without an engine call. A running one stops at its next round, as it does when ``emit``
362+
fails, and raises ``RequestCancelled`` once ``generate`` returns, so no truncated reply is written."""
363+
359364
prepared = prepared if prepared is not None else self.prepare(body, chat)
360365
prompt, max_tokens = prepared.prompt, prepared.max_tokens
361366
tools, thinking = prepared.tools, prepared.thinking
@@ -364,6 +369,7 @@ def run(self, body: dict[str, Any], chat: bool, emit: Callable[[dict[str, Any]],
364369
out: list[int] = []
365370
sent = {"reasoning": 0, "content": 0}
366371
stopped = {"client": False}
372+
failed: list[Exception] = []
367373
stream = StreamDecoder(self.tok, tuple(self.engine.eos))
368374

369375
def visible(finished: bool) -> tuple[str, str]:
@@ -378,18 +384,28 @@ def visible(finished: bool) -> tuple[str, str]:
378384
return reasoning, answer
379385

380386
def on_tokens(new: list[int]) -> bool:
381-
out.extend(new)
382-
stream.add(new)
383-
reasoning, answer = visible(False)
384-
delta: dict[str, Any] = {}
385-
if len(reasoning) > sent["reasoning"]:
386-
delta["reasoning_content"] = reasoning[sent["reasoning"]:]
387-
sent["reasoning"] = len(reasoning)
388-
if len(answer) > sent["content"]:
389-
delta["content"] = answer[sent["content"]:]
390-
sent["content"] = len(answer)
391-
if delta and not emit(delta):
392-
stopped["client"] = True
387+
# True stops the engine after this round. Engines that finish on both ranks (two-rank Flash Next,
388+
# Nemotron and GLM) keep calling; they get True again, and no more text is decoded or sent.
389+
if stopped["client"] or failed:
390+
return True
391+
try:
392+
out.extend(new)
393+
stream.add(new)
394+
reasoning, answer = visible(False)
395+
delta: dict[str, Any] = {}
396+
if len(reasoning) > sent["reasoning"]:
397+
delta["reasoning_content"] = reasoning[sent["reasoning"]:]
398+
sent["reasoning"] = len(reasoning)
399+
if len(answer) > sent["content"]:
400+
delta["content"] = answer[sent["content"]:]
401+
sent["content"] = len(answer)
402+
if delta and not emit(delta):
403+
stopped["client"] = True
404+
elif cancelled is not None and cancelled(): # every round, with or without new text
405+
stopped["client"] = True
406+
except Exception as exc: # noqa: BLE001 raised after generate returns, never into the engine
407+
failed.append(exc)
408+
return True
393409
return stopped["client"]
394410

395411
draft = body.get("draft", True) is not False
@@ -400,7 +416,13 @@ def generate(ids: list[int], count: int, feed: Callable[[list[int]], bool]) -> A
400416

401417
# an engine that decodes concurrent requests together (``concurrent``) takes them as they come
402418
with (nullcontext() if getattr(self.engine, "concurrent", False) else self.lock):
419+
if cancelled is not None and cancelled(): # the client left while this request waited
420+
raise RequestCancelled("the client left before the request started")
403421
stats = generate_gated(generate, prompt, max_tokens, gate, on_tokens)
422+
if failed:
423+
raise failed[0]
424+
if stopped["client"]: # as the Mac server: nothing more is written
425+
raise RequestCancelled("the client left during the reply")
404426
stats = {**(stats or {}), "token_sha": token_sha(out)}
405427
reasoning, answer = visible(True)
406428
final: dict[str, Any] = {}
@@ -467,11 +489,14 @@ def log_message(self, fmt, *args): # quiet
467489

468490
def _json(self, code: int, payload: dict[str, Any]) -> None:
469491
data = json.dumps(payload).encode()
470-
self.send_response(code)
471-
self.send_header("Content-Type", "application/json")
472-
self.send_header("Content-Length", str(len(data)))
473-
self.end_headers()
474-
self.wfile.write(data)
492+
try:
493+
self.send_response(code)
494+
self.send_header("Content-Type", "application/json")
495+
self.send_header("Content-Length", str(len(data)))
496+
self.end_headers()
497+
self.wfile.write(data)
498+
except (BrokenPipeError, ConnectionResetError): # the client has gone
499+
self.close_connection = True
475500

476501
def do_GET(self):
477502
if self.path.rstrip("/") in ("/v1/models", "/models"):
@@ -497,6 +522,8 @@ def do_POST(self):
497522
created = int(time.time())
498523
stream = bool(body.get("stream"))
499524
kind = "chat.completion.chunk" if chat else "text_completion"
525+
gone = socket_cancellation(self.connection) # the Mac server's check: the client has closed
526+
cancelled = lambda: gone.cancelled # noqa: E731
500527

501528
def chunk(delta: dict[str, Any], finish: str | None = None) -> dict[str, Any]:
502529
if chat:
@@ -517,13 +544,16 @@ def emit(delta: dict[str, Any]) -> bool:
517544
self.wfile.write(f"data: {json.dumps(chunk(delta))}\n\n".encode())
518545
self.wfile.flush()
519546
return True
520-
except (BrokenPipeError, ConnectionResetError):
547+
except OSError: # reset, broken pipe, timed out, host unreachable: the client has gone
521548
return False
522549

523550
if chat:
524551
emit({"role": "assistant"})
525552
try:
526-
result = app.run(body, chat, emit, prepared=prepared)
553+
result = app.run(body, chat, emit, prepared=prepared, cancelled=cancelled)
554+
except RequestCancelled:
555+
self.close_connection = True
556+
return
527557
except RequestError as exc:
528558
error = {"error": {"message": str(exc), "type": "invalid_request_error"}}
529559
try:
@@ -554,7 +584,10 @@ def emit(delta: dict[str, Any]) -> bool:
554584
self.close_connection = True
555585
return
556586
try:
557-
result = app.run(body, chat, lambda delta: True, prepared=prepared)
587+
result = app.run(body, chat, lambda delta: True, prepared=prepared, cancelled=cancelled)
588+
except RequestCancelled:
589+
self.close_connection = True
590+
return
558591
except RequestError as exc:
559592
return self._json(400, {"error": {"message": str(exc), "type": "invalid_request_error"}})
560593
usage = {"prompt_tokens": result["prompt_tokens"], "completion_tokens": result["completion_tokens"],

‎src/tensorfold/families/glm5_next/cuda/app.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ def check(self, body: dict[str, Any], *, prepared: PreparedRequest | None = None
4949
f"shorten the prompt or reply{self._restart(need, ' both ranks')}")
5050

5151
def run(self, body: dict[str, Any], chat: bool, emit: Callable[[dict[str, Any]], bool], *,
52-
prepared: PreparedRequest | None = None) -> dict[str, Any]:
52+
prepared: PreparedRequest | None = None, cancelled: Callable[[], bool] | None = None) -> dict[str, Any]:
5353
model = str(body.get("model") or "")
5454
self.engine.request.policy = body.get("tf_policy") or (model.split("@", 1)[1] if "@" in model else None)
5555
self.engine.request.stop_eos = not bool(body.get("ignore_eos", False))
56-
return super().run(body, chat, emit, prepared=prepared)
56+
return super().run(body, chat, emit, prepared=prepared, cancelled=cancelled)

0 commit comments

Comments
 (0)