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 request's combined image file is deleted when the request is refused or its answer never starts
sergiywithd50dc91177e9
diff --git a/serve/server.py b/serve/server.pyindex d798cdf36..1cdafd828 100644--- a/serve/server.py+++ b/serve/server.py@@ -2343,11 +2343,6 @@ class Service:if k != len(encoded):raise ValueError("the prompt and its images do not match")ids = out- combined = self.vision.dir / f"req-{uuid.uuid4().hex[:12]}.sve"- with open(combined, "wb") as f:- for path, _ in encoded:- f.write(path.read_bytes())- self.embeddings.path = combinedctx = self.engine.max_contextif ctx <= 0:if getattr(self.engine, "starting", False): # #344: (re)starting, not a prompt that is too long@@ -2370,8 +2365,25 @@ class Service:f"max_tokens (at most {max(0, room)} here), or add \"fit_max_tokens\": true to the ""model's strata-<model>.json to shorten it to the room left (#545)")max_new = max(1, room) # --fit-max-tokens: a shorter completion beats a 400+ if images:+ # The request's images in one file for GENI (~10 MB a picture), written once nothing above refuses the+ # request: one refused after it (the engine starting, no room) left it in the vision directory for good,+ # one more for every retry of a 503. run() deletes it; drop_embeddings() if run() never starts.+ combined = self.vision.dir / f"req-{uuid.uuid4().hex[:12]}.sve"+ self.embeddings.path = combined # first, so a half-written one is found as well+ with open(combined, "wb") as f:+ for path, _ in encoded:+ f.write(path.read_bytes())return ids, kwargs.get("enable_thinking", True) is not False, max_new+ def drop_embeddings(self) -> None:+ """Delete the combined image file prepare() wrote when no run() took it over (a run deletes its own as it+ ends): a request can end before its answer starts - its client gone, anything raised after prepare() - and+ then nothing else would. The handler calls this when a request is done."""+ path, self.embeddings.path = getattr(self.embeddings, "path", None), None+ if path is not None:+ Path(path).unlink(missing_ok=True)+def _note(self, n, evs, st=None, rate=None):with self.status_lock:s = self.status if st is None else st@@ -2447,7 +2459,7 @@ class Service:tail = "" # the last characters written (the newlines before a call)timings, before = None, None # this request's timings; the engine's `last` before itraw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text)- emb = getattr(self.embeddings, "path", None)+ emb, self.embeddings.path = getattr(self.embeddings, "path", None), None # this run's to delete now# Identity token: only a DONE line replaces engine.last, so a request that died, errored or was# disconnected must not have the PREVIOUS request's decode figures recorded as its own.engine_last0 = getattr(self.engine, "last", None)@@ -3455,6 +3467,7 @@ def make_handler(svc: Service):self._note(outcome="disconnected")raise # as before #332: the server's own handlingfinally:+ svc.drop_embeddings() # the images' file of a request that never got to run()if self.watch_done is not None:self.watch_done.set()record = self.recorddiff --git a/serve/test_server.py b/serve/test_server.pyindex 2df280c1e..c868d2bd3 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -215,6 +215,84 @@ class FitMaxTokens(unittest.TestCase):self.assertIn("no room to answer", b["error"]["message"])+class VisionTempFiles(unittest.TestCase):+ """A request's combined image file (req-*.sve, ~10 MB a picture) goes with the request: one refused after prepare()+ wrote it (the engine starting, no room) or whose answer never started left it in the vision directory for good."""++ MSGS = [{"role": "user", "content": [{"type": "text", "text": "what is it?"},+ {"type": "image", "source": "x.png"}]}]++ @staticmethod+ def leftovers(d):+ return sorted(p.name for p in Path(d).glob("req-*.sve"))++ def test_a_refused_request_writes_none(self):+ from serve.server import EngineStarting+ tok = ByteTokenizer()+ with tempfile.TemporaryDirectory() as d:+ engine = MockEngine(tok, "ok", max_context=0)+ svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"),+ vision=ImageMarkers.FakeVision(d))+ with self.assertRaises(EngineStarting):+ svc.prepare(self.MSGS, None, {}, 16)+ engine.max_context = 64 # the prompt alone fills it+ with self.assertRaisesRegex(ValueError, "no room to answer"):+ svc.prepare(self.MSGS, None, {})+ engine.max_context = CTX+ with self.assertRaisesRegex(ValueError, "exceeds the context"):+ svc.prepare(self.MSGS, None, {}, CTX)+ self.assertEqual(self.leftovers(d), [])+ svc.prepare(self.MSGS, None, {}, 16) # one that fits has it+ self.assertEqual(len(self.leftovers(d)), 1)+ svc.drop_embeddings() # ... until the request is done+ self.assertEqual(self.leftovers(d), [])++ def test_over_http(self):+ import serve.server as server+ tok = ByteTokenizer()+ with tempfile.TemporaryDirectory() as d:+ engine = MockEngine(tok, "</think>\n\nok", max_context=0)+ svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"),+ vision=ImageMarkers.FakeVision(d))+ httpd = serve(svc, port=0)+ base = f"http://127.0.0.1:{httpd.server_address[1]}"++ def post(path):+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}} \+ if path.endswith("completions") else \+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}}+ body = {"model": "m", "max_tokens": 8, "messages": [{"role": "user", "content": [+ {"type": "text", "text": "what is it?"}, image]}]}+ req = urllib.request.Request(base + path, data=json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=30) as r:+ return r.status+ except urllib.error.HTTPError as e:+ with e:+ return e.code++ try:+ paths = ("/v1/chat/completions", "/v1/messages")+ for path in paths:+ self.assertEqual(post(path), 503) # the engine is starting (#344); clients retry+ engine.max_context = 64+ for path in paths:+ self.assertEqual(post(path), 400) # no room to answer+ engine.max_context = CTX+ # the client gone after prepare(), before the answer started+ with mock.patch.object(server, "_debug_req", side_effect=ConnectionResetError("the client is gone")):+ for path in paths:+ with self.assertRaises(OSError):+ post(path)+ for path in paths:+ self.assertEqual(post(path), 200)+ self.assertEqual(self.leftovers(d), [])+ finally:+ httpd.shutdown()+ httpd.server_close()++class ImageMarkers(unittest.TestCase):"""#150: the text "<|image_pad|>" inside a message is text, not an image's place."""