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 client that leaves while its pictures are downloaded, waiting for the turn or encoded stops the preparation: cancel exists before prepare() (#1999)

Niko1221873a0d66b6f8
diff --git a/serve/server.py b/serve/server.py
index 8e61c180c..ff1b935c3 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -305,6 +305,11 @@ class EngineStarting(RuntimeError):
not a 400 about the prompt."""
+class ClientGone(Exception):
+ """#1999: the client hung up while its request was being prepared (an image URL downloading, a picture encoding or
+ waiting for its turn): nothing is left to answer."""
+
+
class ModelBusy(RuntimeError):
"""Explicit model controls must not interrupt active or queued requests."""
@@ -2229,12 +2234,14 @@ class Vision:
im.save(out, format="PNG")
return out.getvalue()
- def encode_all(self, sources: list) -> list[tuple[Path, int]]:
+ def encode_all(self, sources: list, cancel=None) -> list[tuple[Path, int]]:
"""encode() for every image of one request: the files of this request's earlier images are never evicted to
make room for a later one (#1072: with more than 64 unique images the first was deleted before the request
- had read it)."""
+ had read it). `cancel` (#1999): a request whose client left does not encode its next pictures."""
out: list[tuple[Path, int]] = []
for src in sources:
+ if cancel is not None and cancel.is_set():
+ raise ClientGone()
out.append(self.encode(src, keep=[p for p, _ in out]))
return out
@@ -3538,7 +3545,22 @@ class Service:
prompt, plain = unmark_think_literals(prompt, self.literals)
return self.tok.encode(prompt, parse_special=True, plain=plain)
- def _note_unreadable_tool_images(self, messages):
+ @contextlib.contextmanager
+ def _turn(self, cancel=None):
+ """The engine's single turn (self.fifo) for an image encode. #1999: a client that leaves while this request
+ waits for it gives its place up (ClientGone), as a queued generation does (#1619)."""
+ if cancel is None:
+ self.fifo.acquire()
+ else:
+ while not self.fifo.acquire(timeout=0.25):
+ if cancel.is_set():
+ raise ClientGone()
+ try:
+ yield
+ finally:
+ self.fifo.release()
+
+ def _note_unreadable_tool_images(self, messages, cancel=None):
"""A picture a tool returned (Claude Code's Read of an image file) that this server cannot read - it has no
image encoder, or the encoder refuses that picture - becomes a short note in its place instead of a 400.
Clients resend the whole history every turn, so one unreadable tool picture would fail every later request of
@@ -3556,9 +3578,11 @@ class Service:
if why is None:
src = item["source"]
try:
+ if cancel is not None and cancel.is_set():
+ raise ClientGone()
if src.startswith(("http://", "https://")):
src = fetched[item["source"]] = Vision.download(src) # outside the FIFO, as in prepare()
- with self.fifo: # the encoder takes its turn with the requests (see below)
+ with self._turn(cancel): # the encoder takes its turn with the requests (see below)
self.vision.encode(src)
except (ValueError, OSError) as e:
why = str(e)
@@ -3567,11 +3591,13 @@ class Service:
content[n] = {"type": "text", "text": f"[image omitted: {why}]"}
return fetched
- def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None):
+ def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None, cancel=None):
"""-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited":
the rest of the context. `force` (forced_call): without thinking the reply starts with it, so it ends the
prompt; with thinking, Service.run writes it once the thinking is over."""
- fetched = self._note_unreadable_tool_images(messages)
+ # `cancel` (#1999): set when the client hangs up; the downloads, the wait for the turn and the encodes stop
+ # between pictures and raise ClientGone
+ fetched = self._note_unreadable_tool_images(messages, cancel)
ids = self.encode_prompt(messages, tools, kwargs)
if force and kwargs.get("enable_thinking", True) is False:
ids = ids + self.tok.encode(force, parse_special=True)
@@ -3585,14 +3611,18 @@ class Service:
start = self.tok.encode(VISION_START, parse_special=True)[0]
# An image URL is downloaded first, outside the FIFO: under it, a slow server held every other request
# for as long as urlopen waited.
- images = [fetched[src] if src in fetched else Vision.download(src) if src.startswith(("http://", "https://"))
- else src for src in images]
+ def fetch(src):
+ if cancel is not None and cancel.is_set():
+ raise ClientGone()
+ return fetched[src] if src in fetched else Vision.download(src) \
+ if src.startswith(("http://", "https://")) else src
+ images = [fetch(src) for src in images]
# Encode only while the engine is idle: the engine and the image encoder (a separate process) must not
# run on the GPU at the same time - an encode during a running request left that request stuck at
# "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the
# same FIFO as the requests.
- with self.fifo:
- encoded = (self.vision.encode_all(images) if hasattr(self.vision, "encode_all")
+ with self._turn(cancel):
+ encoded = (self.vision.encode_all(images, cancel) if hasattr(self.vision, "encode_all")
else [self.vision.encode(src) for src in images])
# one <|image_pad|> per image -> one per image token. Only the markers the template writes for an image
# (right after <|vision_start|>) are images: the same text inside a message (an agent reading these docs,
@@ -4401,7 +4431,11 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new,
**({"reasoning_content": "".join(reasoning).strip()} if reasoning else {}),
"tool_calls": [{"function": {"name": c.name, "arguments": c.arguments}} for c in calls]})
messages += [{"role": "tool", "content": r} for r in results]
- ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req)
+ try:
+ ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req, cancel=cancel)
+ except ClientGone: # #1999: the client left while a picture was prepared
+ done = {**done, "finish": "cancel"}
+ break
yield "done", {**done, "completion_tokens": total, "prompt_tokens": len(ids)}
@@ -5240,6 +5274,8 @@ def make_handler(svc: Service):
except EngineStuck as e: # an unload or restart that could not end the engine
self._json(503, {"error": {"type": "server_error", "message": str(e)}})
+ except ClientGone: # #1999: the client left while the request was prepared
+ self._note(outcome="disconnected")
except OSError:
self._note(outcome="disconnected")
raise # as before #332: the server's own handling
@@ -5483,10 +5519,10 @@ def make_handler(svc: Service):
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()
- self._watch_client(cancel) # #430 #431
+ self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long)
+ ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req, cancel=cancel)
+ _debug_req("openai", req, messages, tools, max_new, thinking, len(ids))
run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel,
{t["name"] for t in extra}) if use_mcp else None
chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run, force=force)
@@ -5544,16 +5580,19 @@ def make_handler(svc: Service):
return self._json(e.status, e.body())
if title is not None:
return self._responses_ready(req, title)
+ cancel = threading.Event()
+ self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long)
try:
- ids, thinking, tools, max_new, asm, validator, req = self._responses_prepare(req)
+ ids, thinking, tools, max_new, asm, validator, req = self._responses_prepare(req, cancel)
+ except ClientGone:
+ self._note(outcome="disconnected")
+ return
except ResponsesError as e:
return self._json(e.status, e.body())
except ModelBusy as e:
return self._json(409, responses_error_body(str(e), "server_error", code="model_busy"))
except (GpuBusy, EngineStarting, EngineStuck, EngineDied) as e:
return self._json(503, responses_error_body(str(e), "server_error", code="server_error"))
- cancel = threading.Event()
- self._watch_client(cancel) # #430 #431
def check(text, finish):
return validated_json(text, validator, finish)
@@ -5626,7 +5665,7 @@ def make_handler(svc: Service):
except OSError:
pass
- def _responses_prepare(self, req):
+ def _responses_prepare(self, req, cancel=None):
responses_api.check_request(req)
messages = responses_api.input_messages(req)
tools, names, skipped = responses_api.request_tools(req)
@@ -5664,12 +5703,14 @@ def make_handler(svc: Service):
shown = responses_api.prompt_tools(req, tools) if svc.codex_compaction_cache else tools
try:
try:
- ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req)
+ ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req,
+ cancel=cancel)
except ValueError:
if shown is tools:
raise
shown = tools # too long with the kept tools: the request as sent
- ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req)
+ ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req,
+ cancel=cancel)
except ResponsesError:
raise
except ValueError as e: # too long for the context, an image without vision
@@ -5705,10 +5746,10 @@ def make_handler(svc: Service):
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()
- self._watch_client(cancel) # #430 #431
+ self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long)
+ ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req, cancel=cancel)
+ _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids))
events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel, force=force)
events = self._capture(events, "anthropic")
if not req.get("stream"):
diff --git a/serve/test_server.py b/serve/test_server.py
index 8f5c73736..bbb176ada 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -5439,3 +5439,72 @@ class UntimedReads(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
+
+
+class PrepareCancelled(unittest.TestCase):
+ """#1999: a client that leaves while its pictures are prepared gives the turn up and encodes nothing more."""
+
+ def make(self, d, vision):
+ tok = ByteTokenizer()
+ return Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"),
+ vision=vision(d))
+
+ @staticmethod
+ def msgs(n=2):
+ return [{"role": "user", "content": [{"type": "text", "text": "look"}] +
+ [{"type": "image", "source": f"{i}.png"} for i in range(n)]}]
+
+ def test_cancel_before_the_encode_runs_none(self):
+ import tempfile
+ calls = []
+
+ class V(ImageMarkers.FakeVision):
+ def encode(self, source):
+ calls.append(source)
+ return self.rows, 3
+ with tempfile.TemporaryDirectory() as d:
+ svc = self.make(d, V)
+ cancel = threading.Event()
+ cancel.set()
+ from serve.server import ClientGone
+ with self.assertRaises(ClientGone):
+ svc.prepare(self.msgs(), None, {}, cancel=cancel)
+ self.assertEqual(calls, [])
+ self.assertTrue(svc.fifo.acquire(blocking=False)) # the turn was not left held
+ svc.fifo.release()
+
+ def test_cancel_while_waiting_for_the_turn(self):
+ import tempfile
+ from serve.server import ClientGone
+ with tempfile.TemporaryDirectory() as d:
+ svc = self.make(d, ImageMarkers.FakeVision)
+ cancel = threading.Event()
+ threading.Timer(0.3, cancel.set).start()
+ with svc.fifo: # another request holds the engine
+ t0 = time.perf_counter()
+ with self.assertRaises(ClientGone):
+ svc.prepare(self.msgs(1), None, {}, cancel=cancel)
+ self.assertLess(time.perf_counter() - t0, 3)
+
+ def test_cancel_between_pictures_stops_the_next_encode(self):
+ import tempfile
+ from serve.server import ClientGone, Vision
+ cancel, seen = threading.Event(), []
+ v = Vision.__new__(Vision)
+
+ def encode(src, keep=()):
+ seen.append(src)
+ cancel.set() # the client leaves during the first encode
+ return Path("x"), 3
+ v.encode = encode
+ with self.assertRaises(ClientGone):
+ v.encode_all([b"a", b"b", b"c"], cancel)
+ self.assertEqual(seen, [b"a"])
+
+ def test_without_cancel_nothing_changes(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ svc = self.make(d, ImageMarkers.FakeVision)
+ ids, _, _ = svc.prepare(self.msgs(), None, {}, cancel=threading.Event())
+ self.assertEqual(ids.count(ByteTokenizer().encode("<|image_pad|>", parse_special=True)[0]), 6)
+ svc.embeddings.path.unlink(missing_ok=True)