proxy v6.37: the served name on every attempt, the engine's end at once

Found in review and reproduced against a fake vLLM, each with a test that fails on the
proxy before it: a request held through Kolibri's boot went with its old model name
(the rename ran once, before the hold), and so did the first request after a switch
nobody asked about (the last lane's facts stayed 600 s); the rename now runs on every
attempt, after the unit's start is looked at. A client leaving a stream during its
prefill reached vLLM only with the first token: close() waited for the pump's read, so
the socket is shut down first, through the answer's own descriptor (urllib asks
Connection: close, and the connection gives its socket up). The engine a request went
to is noted when it goes, so a dropped fact no longer sends an abandoned Kolibri
stream down SGLang's /abort_request and drain. A unit that starts again drops the
vocabulary and the rid rule learned of the engine before. /invocations is renamed too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Hasan BasbunarandClaude Opus 5.5 committed 2026-10-14 06:16:59 +02:00
1 parent c6a462884d
commit 8cc458f48d
2 files changed
+238 -21

No files matched your search

+78 -18
View File
@@ -53,8 +53,14 @@ serve (404) where SGLang answers any name: a body naming another model is given
so a client keeps working across a lane switch as it always did. And what was learned of one
engine is dropped with it: the vocabulary (Kolibri's is 128,000 tokens, every Qwen lane's
248,320; the probe now names the served model, which vLLM requires, and reads vLLM's wording
too) and whether the engine honours x-override-rid. System One needs a Qwen lane (its labels
are measured on the Qwen tokenizer) and says so on Kolibri, a 400, where it failed as a 502.
too) and whether the engine honours x-override-rid, once its unit starts again. The name is
given again on every attempt (a request held through Kolibri's boot went with its old one), and
after a switch nobody asked about (the last lane's facts stayed 600 s). The connection of a
client that left is shut down, not only closed: a close waited for the stream's next byte,
which during a long prefill is its first token. And the engine a request went to is noted when
it goes: a dropped fact made an abandoned Kolibri stream take SGLang's /abort_request and drain.
System One needs a Qwen lane (its labels are measured on the Qwen tokenizer) and says so on
Kolibri, a 400, where it failed as a 502.
v6.36: a path under /ready passes the door without a key, as the engine leaves it open (its
auth rule opens /health, /ready and /metrics; the door had /health and /metrics only, so a
readiness probe got 401 here and 200 from the engine, found 2026-10-11).
@@ -1418,6 +1424,10 @@ def follow_engine_restarts():
if seen is None or ids == seen:
return False
invalidate_pool()
# v6.37: and what was learned of it, which note_engine drops only once the new engine
# named itself: on a Qwen lane the sampling guard reads the vocabulary first, and
# Kolibri's 128,000 refused token ids the 27B serves for up to an hour.
forget_engine_rules()
log("an engine unit started since the engine's pool and names were read (systemd): "
"they are read again")
return True
@@ -1551,6 +1561,7 @@ def served_vocab():
A failure is cached as hard as a success, for a shorter time. Without that, a busy
engine turns every request carrying one of these fields into another 8-second probe,
and a guard against a denial of service becomes one."""
follow_engine_restarts() # v6.37: a lane switch drops the last engine's vocabulary
if time.time() - _VOCAB["ts"] < (3600 if _VOCAB["size"] else 60):
return _VOCAB["size"]
_VOCAB["ts"] = time.time() # claimed before the probe, so a failure counts
@@ -2430,17 +2441,23 @@ def served_models():
_ENGINE_SEEN = {"names": (), "engine": ""}
def forget_engine_rules():
"""Drop the vocabulary and the x-override-rid verdict learned of the engine: the next
request that needs either learns it again, on the engine that serves now."""
global _rid_override_honoured
_VOCAB.update(size=0, ts=0.0)
_rid_override_honoured = None
def note_engine(names, owner):
"""Drop what was learned of the engine before, once another one names itself: its
vocabulary (Kolibri's is 128,000 tokens, the Qwen lanes' 248,320) and whether it takes
x-override-rid (vLLM takes no rid from the caller). Kept, the next engine was judged by
the last one's. The same engine back after a restart, same names, keeps both."""
global _rid_override_honoured
if (names, owner) == (_ENGINE_SEEN["names"], _ENGINE_SEEN["engine"]):
return
if _ENGINE_SEEN["names"]:
_VOCAB.update(size=0, ts=0.0)
_rid_override_honoured = None
forget_engine_rules()
log(f"the engine now serves {', '.join(names)[:120]} ({owner or 'unnamed engine'}): "
f"what was learned of the one before (vocabulary, request ids) is dropped")
_ENGINE_SEEN.update(names=names, engine=owner)
@@ -2448,7 +2465,8 @@ def note_engine(names, owner):
# v6.37: the routes whose JSON body names a model vLLM checks against what it serves.
VLLM_MODEL_ROUTES = ("/v1/chat/completions", "/v1/completions", "/v1/messages",
"/v1/messages/count_tokens", "/v1/responses", "/tokenize", "/detokenize")
"/v1/messages/count_tokens", "/v1/responses", "/tokenize", "/detokenize",
"/invocations")
def route_model_name(body, path):
@@ -2458,6 +2476,9 @@ def route_model_name(body, path):
between the Qwen lanes. Untouched on any doubt, and on SGLang always."""
if not body or path.split("?", 1)[0] not in VLLM_MODEL_ROUTES or b'"model"' not in body:
return body, None
# A switch with no request since kept the last lane's engine for up to 600 s: the first
# request after it reached vLLM with its old name, and a 404 (found in review, 2026-10-14).
follow_engine_restarts()
if not _SERVED["engine"]:
# What every prompt reads anyway, cached: on an engine without SGLang's info routes
# that read names it too (_vllm_facts). It costs a Qwen lane no request it did not make.
@@ -2938,11 +2959,13 @@ class H(BaseHTTPRequestHandler):
req = urllib.request.Request(UPSTREAM + self.path, data=body,
headers=self._hdrs(), method=self.command)
self._upstream_req = req # _watch_client ends req.upstream
self._upstream_engine = _SERVED["engine"] # v6.37: whose request this is (_abort_upstream)
# GETs are metadata and always fast; a generation may legitimately take
# tens of minutes before its first byte (cold giant prefill).
timeout = UPSTREAM_GET_TIMEOUT_S if self.command == "GET" else None
try:
return _UPSTREAM_OPENER.open(req, timeout=timeout), None, None
self._upstream_resp = _UPSTREAM_OPENER.open(req, timeout=timeout)
return self._upstream_resp, None, None
except urllib.error.HTTPError as e:
return None, e, None
except (urllib.error.URLError, OSError) as e:
@@ -3103,7 +3126,7 @@ class H(BaseHTTPRequestHandler):
_rid_override_honoured = (rid == forced)
# v6.37: on vLLM the rid is never used (closing stops it), and the
# SGLang advice below was a wrong lead in its journal
if _SERVED["engine"] != "vllm":
if (getattr(self, "_upstream_engine", "") or _SERVED["engine"]) != "vllm":
log("this engine honours x-override-rid: an abandoned request "
"can be aborted before it produces anything"
if _rid_override_honoured else
@@ -3159,11 +3182,17 @@ class H(BaseHTTPRequestHandler):
which is the caller's signal to drain instead of orphaning the generation."""
if getattr(self, "_aborted", False):
return True
if _SERVED["engine"] == "vllm":
# v6.37: vLLM stops a request whose connection closes, the stream and the plain
# answer alike (measured 2026-10-14): closing is the abort, and draining would only
# keep its generation going for nobody.
# v6.37: the engine this request was sent to, noted when it was (_open): the lane's
# facts can be dropped meanwhile (a pool read that failed), and an abandoned Kolibri
# stream then took SGLang's way, an /abort_request vLLM answers 404 and a drain.
if (getattr(self, "_upstream_engine", "") or _SERVED["engine"]) == "vllm":
# vLLM stops a request whose connection closes, the stream and the plain answer
# alike (measured 2026-10-14): closing is the abort, and draining would only keep
# its generation going for nobody. The socket is shut down here, before any
# close(): close() waits for the pump's read, which on a stream still prefilling
# returns with the first token only (48.5 s at 128K), and vLLM saw nothing until.
self._aborted = True
self._shut_upstream()
log(f"closing the upstream: vLLM stops what it generates for it ({why})")
return True
rid = self._abortable_rid()
@@ -3183,6 +3212,27 @@ class H(BaseHTTPRequestHandler):
log(f"abort_request failed for rid={rid}: {e}")
return False
def _shut_upstream(self):
"""End the connection to the engine now, from any thread: shutdown() wakes a read
blocked on it and the engine reads the end at once. Through the answer's own file
descriptor (a duplicate of it), since an answer that says Connection: close (urllib
asks for one) takes the socket from its HTTPConnection when it arrives."""
resp = getattr(self, "_upstream_resp", None)
try:
fd = resp.fileno() if resp is not None else -1
except Exception:
fd = -1
try:
if fd >= 0:
with socket.socket(fileno=os.dup(fd)) as dup:
dup.shutdown(socket.SHUT_RDWR)
return
up = getattr(getattr(getattr(self, "_upstream_req", None), "upstream", None), "sock", None)
if up is not None:
up.shutdown(socket.SHUT_RDWR)
except OSError:
pass
def _relay(self, resp):
"""A client that vanishes before the relay can start (30/08: a request that
showed as 'in flight' forever) used to leave the upstream response open and
@@ -3707,11 +3757,8 @@ class H(BaseHTTPRequestHandler):
if _pattern_drop_logged.first(pat):
log(f"{self._peer} tool schema: dropped a 'pattern' Python's re cannot "
f"compile (the engine would 400 the request): {pat[:120]}")
body, renamed = route_model_name(body, self.path)
if renamed and _model_rename_logged.first(renamed): # once per name, not per request
shown = repr(renamed[:60]) + ("..." if len(renamed) > 60 else "")
log(f"{self._peer} model {shown} is not what this lane serves (vLLM answers 404 to it): "
f"relayed as {(_SERVED['names'] or ('?',))[0]}")
asked = body
body = self._served_name(asked)
if self.command == "POST" and self.path.split("?")[0] == SYSTEMONE_PATH:
self._systemone(body); return
# A count generates nothing, so there is no scheduler for it to wedge, and it is how
@@ -3728,7 +3775,10 @@ class H(BaseHTTPRequestHandler):
return
kind, why, detail = gone
if self._hold(why, streamed):
continue # the engine answers again: the request goes now
# the engine answers again: the request goes now, named for the engine that
# answers (held through Kolibri's boot, it went with its old name, and a 404)
body = self._served_name(asked)
continue
if getattr(self, "_caller_left", False):
self._done("CLIENT GONE during hold"); return
if kind == "warming":
@@ -3739,6 +3789,16 @@ class H(BaseHTTPRequestHandler):
self._done(f"503 engine unreachable (upstream {detail})"); return
self._done("503 engine unreachable"); return
def _served_name(self, body):
"""The body as the engine that serves now takes it (route_model_name), the rename
said once per name."""
body, renamed = route_model_name(body, self.path)
if renamed and _model_rename_logged.first(renamed): # once per name, not per request
shown = repr(renamed[:60]) + ("..." if len(renamed) > 60 else "")
log(f"{self._peer} model {shown} is not what this lane serves (vLLM answers 404 to it): "
f"relayed as {(_SERVED['names'] or ('?',))[0]}")
return body
def _forward(self, body, count_only):
"""The request from the size guard to its answer. None once it is answered. When the
engine did not answer, nothing has been sent to it or answered yet, and this returns
+160 -3
View File
@@ -20,9 +20,11 @@ import importlib.util
import io
import json
import os
import select
import socket
import sys
import threading
import tempfile
import time
import unittest
from contextlib import redirect_stderr
@@ -107,6 +109,17 @@ class FakeVllm(http.server.BaseHTTPRequestHandler):
self.send_header("Content-Type", "text/event-stream")
self.send_header("Connection", "close")
self.end_headers()
self.wfile.flush()
if prompt.startswith("prefill"):
# vLLM sends a stream's headers before its prefill, then nothing until the first
# token: here 5 s, watching for the end of the connection as vLLM does
end = time.time() + 5
while time.time() < end:
r, _, _ = select.select([self.connection], [], [], 0.05)
if r and not self.connection.recv(1, socket.MSG_PEEK):
with FakeVllm.lock:
FakeVllm.closed_at[prompt] = time.time()
return
n = 200 if prompt.startswith("slow") else 2
try:
for i in range(n):
@@ -162,7 +175,7 @@ class PureParts(unittest.TestCase):
out, was = self.mod.route_model_name(self.body(), "/v1/chat/completions")
self.assertEqual(was, "qwen3.8-27b")
self.assertEqual(json.loads(out)["model"], "kolibri-1")
for path in ("/v1/messages", "/v1/messages/count_tokens", "/v1/completions", "/tokenize"):
for path in ("/v1/messages", "/v1/messages/count_tokens", "/v1/completions", "/tokenize", "/invocations"):
self.assertEqual(json.loads(self.mod.route_model_name(self.body(), path)[0])["model"], "kolibri-1", path)
def test_a_served_name_a_foreign_route_or_a_doubt_go_as_they_came(self):
@@ -213,8 +226,12 @@ class ThroughTheProxy(unittest.TestCase):
CLIENT_IO_S="5", PROMPT_CEILING_TOKENS="0", FLASH_PROMPT_CEILING_TOKENS="0")
cls.mod = load_proxy("kproxy_vllm_lane")
cls.mod._api_key = lambda: KEY
cls.log = io.StringIO()
cls.err = redirect_stderr(cls.log)
# this proxy's own lines only: stderr is the process's, and a drain left running by
# another module's proxy wrote its line into this one's (the full unittest run, 2026-10-14)
cls.lines = []
cls.mod.log = lambda msg: cls.lines.append(f"[proxy] {msg}")
cls.log = type("Lines", (), {"getvalue": staticmethod(lambda: "\n".join(cls.lines) + "\n")})()
cls.err = redirect_stderr(io.StringIO())
cls.err.__enter__()
cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H)
threading.Thread(target=cls.proxy.serve_forever, daemon=True).start()
@@ -286,6 +303,43 @@ class ThroughTheProxy(unittest.TestCase):
# and no SGLang advice in a vLLM lane's journal (it did, on the reference box)
self.assertNotIn("SGLANG_ENABLE_REQUEST_HEADER_OVERRIDES", self.log.getvalue())
def test_a_client_that_leaves_during_the_prefill_is_seen_by_the_engine_at_once(self):
# close() waited for the stream's next byte, the first token after a long prefill
# (48.5 s at 128K): the engine computed it for nobody (found in review, 2026-10-14)
s = self.post({"model": "kolibri-1", "stream": True,
"messages": [{"role": "user", "content": "prefill long"}]}, read_all=False)
s.settimeout(10)
s.recv(4096) # the headers, then the proxy's keepalives
t0 = time.time()
s.close()
end = time.time() + 8
while time.time() < end and "prefill long" not in FakeVllm.closed_at:
time.sleep(0.05)
self.assertIn("prefill long", FakeVllm.closed_at, "the engine never saw its connection end")
self.assertLess(FakeVllm.closed_at["prefill long"] - t0, 2.0)
self.assertEqual(FakeVllm.aborts, [])
def test_the_engine_a_request_went_to_decides_how_it_ends(self):
# the lane's facts dropped while the stream ran (a pool read that failed): an abandoned
# Kolibri stream took SGLang's way, an /abort_request answered 404, and a drain
since = len(self.lines)
s = self.post({"model": "kolibri-1", "stream": True,
"messages": [{"role": "user", "content": "slow and dropped"}]}, read_all=False)
s.settimeout(10)
s.recv(4096)
self.mod.invalidate_pool()
t0 = time.time()
s.close()
end = time.time() + 5
while time.time() < end and "slow and dropped" not in FakeVllm.closed_at:
time.sleep(0.05)
self.assertLess(FakeVllm.closed_at.get("slow and dropped", 1e12) - t0, 2.0)
self.assertEqual(FakeVllm.aborts, [], "vLLM has no /abort_request")
time.sleep(0.3)
mine = "\n".join(self.lines[since:])
self.assertNotIn("drained an abandoned", mine)
self.assertNotIn("SGLANG_ENABLE_REQUEST_HEADER_OVERRIDES", mine, "SGLang's advice on a vLLM request")
def test_the_vocabulary_is_read_in_vllms_words_with_the_served_name(self):
self.mod.pool_tokens() # names known, as on any prompt
self.assertEqual(self.mod.served_vocab(), 128000)
@@ -299,5 +353,108 @@ class ThroughTheProxy(unittest.TestCase):
self.assertEqual(FakeVllm.bodies[-1]["model"], "my-alias")
class ALaneSwitch(unittest.TestCase):
"""The proxy in front of a Kolibri unit that boots, then serves: a systemctl that reads the
unit's state and its start's invocation id from files, and the fake engine on the port."""
def setUp(self):
self.t = Path(tempfile.mkdtemp(prefix="vllm-switch-"))
(self.t / "bin").mkdir()
self.state, self.inv = self.t / "state", self.t / "inv"
self.state.write_text("activating\n")
self.inv.write_text("start-1\n")
(self.t / "bin/systemctl").write_text(
"#!/bin/sh\n"
f'case "$*" in *InvocationID*) cat "{self.inv}"; exit 0;; esac\n'
f'if [ "$1" = show ]; then cat "{self.state}"; exit 0; fi\n'
"exit 3\n")
(self.t / "bin/systemctl").chmod(0o755)
with socket.socket() as sk:
sk.bind(("127.0.0.1", 0))
self.engine_port = sk.getsockname()[1]
saved, saved_argv = dict(os.environ), list(sys.argv)
self.addCleanup(lambda: (os.environ.clear(), os.environ.update(saved), setattr(sys, "argv", saved_argv)))
os.environ.update(UPSTREAM=f"http://127.0.0.1:{self.engine_port}", KEEPALIVE_S="0.4",
PROXY_HOLD_UNITS="qwen38-kolibri.service", PROXY_HOLD_MAX_S="30",
PROXY_HOLD_POLL_S="0.2", PROMPT_CEILING_TOKENS="0", FLASH_PROMPT_CEILING_TOKENS="0",
PATH=f"{self.t / 'bin'}:{os.environ.get('PATH', '')}")
self.mod = load_proxy(f"kproxy_switch_{time.time_ns()}")
self.mod._api_key = lambda: KEY
self.lines = []
self.mod.log = self.lines.append
self.proxy = self.mod.Server(("127.0.0.1", 0), self.mod.H)
threading.Thread(target=self.proxy.serve_forever, daemon=True).start()
self.addCleanup(lambda: (self.proxy.shutdown(), self.proxy.server_close()))
self.engine = None
FakeVllm.served, FakeVllm.owner = "kolibri-1", "vllm"
with FakeVllm.lock:
FakeVllm.bodies.clear(); FakeVllm.aborts.clear(); FakeVllm.closed_at.clear()
def start_engine(self):
self.engine = http.server.ThreadingHTTPServer(("127.0.0.1", self.engine_port), FakeVllm)
self.engine.daemon_threads = True
threading.Thread(target=self.engine.serve_forever, daemon=True).start()
self.addCleanup(lambda: (self.engine.shutdown(), self.engine.server_close()))
def started_again(self):
"""The unit's next start, as systemd says it; the proxy looks at most every 2 s."""
self.inv.write_text("start-2\n")
self.mod._STARTS["ts"] = -1e9
def ask(self, model, out):
raw = json.dumps({"model": model, "stream": True,
"messages": [{"role": "user", "content": "hi"}]}).encode()
s = socket.create_connection(("127.0.0.1", self.proxy.server_address[1]), timeout=40)
s.sendall(f"POST /v1/chat/completions HTTP/1.1\r\nHost: p\r\nAuthorization: Bearer {KEY}\r\n"
f"Content-Type: application/json\r\nContent-Length: {len(raw)}\r\n\r\n".encode() + raw)
got = b""
while True:
c = s.recv(65536)
if not c:
break
got += c
s.close()
out.append(got)
def test_a_request_held_through_the_boot_reaches_kolibri_by_its_name(self):
out = []
th = threading.Thread(target=self.ask, args=("qwen3.8-27b", out), daemon=True)
th.start()
time.sleep(1.0) # held: the port is closed, the unit is activating
self.start_engine()
self.state.write_text("active\n")
th.join(30)
self.assertTrue(out, "no answer")
self.assertIn(b"t1 ", out[0], out[0][-300:])
self.assertEqual([b["model"] for b in FakeVllm.bodies if not b.get("logit_bias")], ["kolibri-1"])
def test_the_first_request_after_a_switch_nobody_asked_about_is_renamed(self):
FakeVllm.served, FakeVllm.owner = "qwen3.8-27b", "sglang"
self.state.write_text("active\n")
self.start_engine()
self.mod.served_models() # the 27B, read and cached for 600 s
self.assertEqual(self.mod._SERVED["engine"], "sglang")
FakeVllm.served, FakeVllm.owner = "kolibri-1", "vllm" # the cockpit loads Kolibri
self.started_again()
out = []
self.ask("qwen3.8-27b", out)
self.assertIn(b"t1 ", out[0], out[0][:300])
self.assertEqual(FakeVllm.bodies[-1]["model"], "kolibri-1")
def test_a_unit_that_started_again_drops_the_vocabulary(self):
self.state.write_text("active\n")
self.start_engine()
self.mod.follow_engine_restarts() # the first start, as the proxy first sees it
self.mod._VOCAB.update(size=128000, ts=time.time()) # learned on Kolibri
self.mod._rid_override_honoured = False
self.started_again() # the cockpit loads the 27B
FakeVllm.served, FakeVllm.owner = "qwen3.8-27b", "sglang"
self.mod.served_vocab()
self.assertTrue(any(b.get("logit_bias") for b in FakeVllm.bodies), "learned again, not kept")
self.assertIsNone(self.mod._rid_override_honoured)
if __name__ == "__main__":
unittest.main(verbosity=2)