#!/usr/bin/env python3 """Keepalive proxy in front of SGLang or vLLM (v6.41). No content logging, and the only rewriting is the tool-schema guard (role 4); one route, POST /v1/systemone, is answered here instead of relayed (role 5). Six roles, nothing else: 1. fill the silences of the SSE stream (SGLang's tool-call parser buffers the arguments: 127 s of measured silence for a 400-line file write) by injecting the OFFICIAL Anthropic "ping" event every KEEPALIVE_S seconds on the Anthropic dialect (an SSE comment ": keepalive" KILLS Claude-family parsers: measured 2026-08-23, client death 10-20 s after the first comment) and an authentic empty chunk on the OpenAI dialect (opencode/AI SDK stall detectors ignore comments and drop the stream after ~140-180 s without a real chunk). It starts before the engine answers: SGLang sends a stream's headers with its first chunk, after the queue and the prefill, so past KEEPALIVE_S without them the proxy opens the stream itself (v6.31); 2. never leave a generation running for a client that is gone: the proxy names every request itself (x-override-rid), POSTs /abort_request BEFORE it closes the upstream socket, and drains the answer when the engine offers no rid to abort with. The caller of a non-streamed answer, who hears nothing until it is whole, is watched instead: when it leaves, the upstream is ended, and the engine drops the request on its own. So is the caller of a stream until the engine answers (v6.31): a request queued behind a full KV pool otherwise stayed in the engine's queue after its caller had gone; 3. never lull a client on a dead upstream: past MAX_SILENCE_S an EXPLICIT SSE error event is sent, then the stream is closed. MAX_SILENCE_S must stay ABOVE the worst legitimate prefill (40 min measured for 690K tokens on a cold cache), hence the 3600 s default; 4. keep one tool schema from killing a whole session: the 'pattern' values that Python's re cannot compile are dropped from tool parameter schemas, because the engine validates them with a Python regex and 400s the request otherwise. Nothing else in the body is ever touched; 5. answer typed decisions on POST /v1/systemone (the wire contract of TypeSafe's Jev) from the lane behind it: one single-token completion per question, the option labels read off top_logprobs, so a pipeline or an agent gets choice, score and yes/no probabilities from the model it already runs, with nothing generated and nothing parsed. The "System One endpoint" section below carries the design and its receipts; 6. keep a request through an engine restart: one that arrives while the engine does not answer and its unit (PROXY_HOLD_UNITS) is on its way back waits for it, at most PROXY_HOLD_MAX_S, instead of failing at once. A streamed one hears from the proxy at once (200, then the keepalives of role 1); see "Holding a request" below. v6.41: what a review of the repository found open, closed (2026-10-17). The network's share of the port is bounded: another machine holds at most PROXY_MAX_CONN_PER_ADDRESS connections open, the network PROXY_MAX_REMOTE_CONN, and such a connection has CLIENT_HEADER_S in all for its request's headers; the bodies in flight share BODY_BUDGET_BYTES, a compressed body is refused (415). Behind the identity wall a client key reaches the routes that generate, count and read, not the engine's operator routes; a redirect from the engine is relayed, never followed. /v1/score's token ids are bounded and its label_token_ids refused like token_ids_logprob; a video is priced at SGLang's own ceiling where a prompt can wedge the engine, the media of an uncountable body as media; token ids past every lane's vocabulary wait while it is unknown; the counting routes have a ceiling of their own; a held request is judged again for the engine that comes back; and an abandoned /v1/messages answer is aborted on an SGLang lane that takes the request id override. v6.40: the Nemotron lane (NVIDIA's Bolt on vLLM) takes a reasoning effort as its chat template reads it, enable_thinking and medium_effort: none and minimal turn the reasoning off, low and medium ask its shorter one, high and above its default. vLLM handed the template a top-level "none" it does not read, and the answer came back inside the reasoning, its content null (measured 2026-10-15); pi and the OpenAI SDKs send the field so. v6.39: an engine that has neither of SGLang's info routes is not asked them again. Every read of the pool on the Kolibri lane (vLLM) began with /server_info and /get_server_info, two 404s, and the hold's probe asked /server_info each time it looked: the proxy notes that this engine has none, reads vLLM's own facts at once, and probes /health there, which on vLLM generates nothing. A new engine (any restart, any lane switch) is asked again (found in review, 2026-10-14), and so is one that took the port with no start the proxy saw (a proxy told no unit to watch): the first read that finds it is not vLLM drops what was read from the vLLM engine and goes back to SGLang's routes (the review of the fix, the same day). v6.38: the client's key reaches the engine without the whitespace around it. The spaces around a header's value are not part of it (RFC 9110, section 5.5), and SGLang reads it so: a key sent as "Bearer " passed on a Qwen lane. The proxy forwarded the header as it came, and vLLM's own check, like the Kolibri lane's (vllm_engine_auth.py), compares the value exactly: the same client got a 401 there (the production checks after v1.29.0, 2026-10-14). v6.37: the Kolibri lane serves on vLLM behind this door, and four things SGLang does that vLLM does not are now asked of the engine instead of assumed. Its /v1/models says which one serves ("owned_by": "vllm"). vLLM has neither /server_info nor /get_server_info: the pool and the window come from its /metrics (cache_config_info's kv_cache_size_tokens, the figure its boot log prints) and its /v1/models (max_model_len), where without them every body past 256 KiB was held as "not measured yet" for good. vLLM stops a request whose connection closes (measured 2026-10-14: one running before the client left, none 0.5 s after, no token in the next 2 s, the stream and the plain answer alike): a client that leaves closes the upstream there, where it was drained up to DRAIN_MAX_S for want of an /abort_request. vLLM refuses a model it does not serve (404) where SGLang answers any name: a body naming another model is given the served one, 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, 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). v6.35: a lane switch is followed at once, request or not. The pool, the window and the names read from the engine were kept 600 s and dropped only by a request that found the engine gone, so after a switch made while no request came, a lane that boots in less than 600 s served its first minutes under the stopped lane's: the 27B, which boots in about 7 min on the reference box, refused every prompt past the flash lane's 250,000 ceiling for up to 2.5 min and /v1/systemone answered as the flash (found 2026-10-08), and a restart of the 27B kept the pool of the boot before. The units the installed proxy names in PROXY_HOLD_UNITS are now asked for their invocation id when those facts are read, at most every 2 s, and a new one, which systemd gives every start, drops them. A proxy that names no unit keeps them its 600 s, as before. v6.34: the serving key is checked before a body is read. The README promises that the key is this port's one gate, and a caller without it still had its body read whole (up to MAX_BODY_BYTES) and, past the size guard's nomination line, counted by the engine on the proxy's own key, before the engine's 401. Without the identity wall, a request now has to carry what the engine's own check admits (the same rule, measured on the live engine), or it gets the engine's own 401 at once; /health and /metrics stay open, as the engine keeps them. Where the engine would accept a prompt past the share of its pool the size guard lets through (the 27B lane: 863,638 tokens accepted, 794,552 usable), the guard nominates a body by a bound, not an average: a token is at least one byte, so a body counts as its length in bytes until the engine's count says otherwise (2.5 bytes a token let digit-heavy text through uncounted, and a prompt in that zone wedges the scheduler); where the engine's window is under that share, it refuses past it itself. And token_ids_logprob is refused where the engine reads it: on a batch that mixes it with an ordinary request, the served build's scheduler dies (sglang#34719). v6.33: an answer relayed from the engine carries one Server header and one Date. The proxy writes its own, and relayed the engine's beside them (uvicorn's `server: uvicorn` and `date`): two of each on every relayed answer, which RFC 9110 (5.3) does not allow. aiohttp refuses such an answer by default in 3.13.4, and in its strict mode (python -X dev) since then, so a LiteLLM gateway in front of the proxy answered "Duplicate 'Server' header found." (issue #39, 2026-10-06). The engine's two are no longer relayed, as the cockpit's agent relay already did. v6.32: /server_info no longer carries the engine's key anywhere. v6.24 took SGLang's key fields out of the answer, at the top and in every internal state, but the answer also repeats the engine's whole command line in launch_command, the key included (the flash lane on the reference box, found by the audit of 2026-10-03): a named client behind the wall could still read the one secret the wall keeps from it. The value of every key flag is now masked in every string of the answer, and the engine's key itself wherever it shows; the TLS key password field goes with the key fields. v6.31: a stream is kept, and watched, before the engine answers. SGLang holds a stream's status and headers back until its first chunk, after the request was queued and its prompt computed, and this proxy wrote nothing before them and did not watch the caller. On 2026-10-03, eight agents whose contexts (771,301 tokens at 01:00) overflowed the KV pool (437,184) waited longer than opencode's 300 s for headers; opencode gave up and sent again, and each request it gave up on stayed queued until the engine reached it, computed its prompt for nobody, and was aborted at the proxy's first write: 704 between 01:24 and 11:36, and 163 requests in the queue at the end, for eight agents. Now the caller of a stream is watched until the engine answers, and its leaving ends the upstream, which the engine sees within 4 s; past KEEPALIVE_S the stream is opened and kept alive, as a hold does; past MAX_SILENCE_S without the engine's first byte the request is dropped, as a silent stream is. v6.30: a level SGLang refuses at the top of a request that also names one in chat_template_kwargs is dropped. SGLang takes the chat_template_kwargs copy over the top-level one, so the top-level copy changed nothing but the answer, a 400 from its validation: omp's default dialect sends both (omp 18.4.9, 2026-10-01). The level the client put in chat_template_kwargs is kept, a null there is filled as an absent one is, and a top-level level SGLang accepts is still left alone. v6.29: a body that never arrived whole is not sent on. A caller that closed before the last byte of its body (a reset at once after sending, or a client dying mid-send) left the proxy a short read, and the proxy sent the engine what had come: of 300 requests closed so, 11 were read short and sent on all the same. No engine can serve that, so nothing was generated, but no request should go out so. It now ends "CLIENT GONE before its body", and the engine is not asked. (The engine still sees a body cut short when the proxy closes its side as the request goes out, its caller gone: by design, the engine never has it.) v6.28: a request is held while its engine comes back (issue #26). systemd starts a crashed engine again 15 s after it stops, and the boot takes 7 to 11 min; every request of that window got a 503 at once, and the clients gave up long before the engine was back: opencode 1.18.32 retried a 503 six times on its Retry-After and failed the session after 151 s (measured against a fake engine, 2026-10-01). Now a request that finds the engine not answering, while a unit named in PROXY_HOLD_UNITS is starting, between two attempts, up, or in the stop half of a restart, waits for it. A streamed request gets its 200 and the role-1 keepalives at once, which opencode and Claude Code both waited on for 400 s and then took the answer; a non-streamed one waits in silence. Should the request still fail once the wait is over (the engine not back within PROXY_HOLD_MAX_S, or the prompt too long for the lane that came back), a stream the proxy opened ends with an error event, and both clients then send it again (measured), to an engine that now answers. With no unit named, nothing waits. An engine's mid-stream cut now reaches the client as a cut, with no error event and no closing chunk: Claude Code sends a cut stream again as a stream, which the hold keeps alive, where the error event made it retry without one, held in silence, which it gave up on after about 330 s (an engine made a zombie under real clients on the reference box, 2026-10-01). v6.27: the second pass of the same review found the guards still judgeable by value type. The engine's request models (pydantic v2, lax) coerce "999999", 999999.0 and [-1] spelled as strings into the ints the scheduler then acts on, and the guards only read the raw JSON type, so the crash shapes were one pair of quotes away (verified against the installed build: n, logprobs, top_logprobs, top_logprobs_num, and the elements of stop_token_ids, input_ids and prompt). The guards now judge each value as the engine reads it (_engine_int), and the vertex route also judges parameters.sampling_params, which the scheduler spreads into SamplingParams. Found in review, 2026-09-26. v6.26: the review's three open guard findings, closed. S4: a key spelled with a \\u escape (e.g. \\u0074op_logprobs) carried none of the bytes the guards scanned for, so the ceiling and the token-id refusals were skipped; any \\u in the body now forces the parse. S5: the sampling and logprob guards also cover /v1/responses, /invocations and /vertex_generate, read input_ids as a batch of lists, read sampling_params as a list, read prompt as token ids on /v1/completions, and the oversize guard reaches /generate and the other non-/v1/ generation routes. S6: the TLS handshake no longer runs in the accept loop (one silent connection parked every other client behind its timeout); it now runs in the connection's own thread on its own budget, and a handshake that dies leaves one journal line, no traceback. Found in review, 2026-09-24; fixed 2026-09-26. v6.25: a caller that leaves a non-streamed answer stops the generation. The proxy waited inside the upstream call for the whole answer, so it never saw that caller go and kept the upstream open: the engine worked to the end (measured on the box, a 69k-token prefill and its decode ran 53.6 s past the caller), then got an abort that found nothing to abort. The caller's socket is watched during that wait now, and at its EOF the upstream is ended: SGLang checks its own HTTP client every 4 s for a non-streamed request and drops it (the same prefill stopped 4.0 s after the caller left). A non-streamed body the engine ends early is no longer relayed as complete: the client sees the cut, as it would from the engine itself. An Anthropic body is counted by the engine's own /v1/messages/count_tokens, tools included and screenshots priced from their headers wherever they sit: five screenshots in tool_result blocks were counted 2,044,251 tokens and refused, for 28,463 served. A raw control or non-ASCII byte in a query is a 400 instead of a dropped socket; the values logged once are remembered as digests, in bounded memory, and an effort level is printed short; and a client named by the identity wall is named on the line that opens its request too, in one word. And the flash lane's one-prompt ceiling follows the lane that serves, by its model's name (FLASH_PROMPT_CEILING_TOKENS), instead of being moved by a switch, with a restart, while the old lane still served. Found in review, 2026-09-24. v6.24: the identity wall covers every route and every method but /health (it looked at POST /v1/... only, while the engine's key went upstream on everything relayed, so GET /server_info, /generate, /flush_cache and /abort_request needed no listed key); a path still escaped after one decode is refused, since SGLang decodes again before it routes; relayed /server_info answers lose the engine's key fields in both modes; and an unreadable keys file says so instead of "missing, malformed or empty". Found in review, 2026-09-24. v6.23: the pool is read from /server_info, and from the deprecated /get_server_info only on an engine that answers 404 to the new route. SGLang logs a deprecation warning for each call of the old one, on the 27B image and the flash image alike, and says it will go. v6.22: an engine that is gone because the box switched to its image lane says so. The text engine is stopped on purpose by that switch and nothing brings it back until someone switches back, so "stopped, restarting or still loading (about 9 minutes)" sent clients to wait for an engine that was not coming. The error path, and only it, asks systemd whether qwen38-image.service is active (at most every 5 s) and names the way back. v6.21: PROXY_BIND chooses the interface this proxy answers on, and it answered on every one of them before. Seven days of journal on the reference box: 8,288 requests, all from 127.0.0.1, because the clients that need it run on the same machine. The default does not move, since somebody else's laptop may legitimately point at this port. v6.20: the request fields SGLang leaves unbounded and dies on rather than refusing are refused here instead. top_logprobs (chat), logprobs (completions) and top_logprobs_num (/generate) past a ceiling: the number reaches logprobs.topk(max_k) unexamined and, past the vocabulary, raises "selected index k out of range" inside the scheduler, which ends the engine for every client (sglang#40076, open; reproduced on the reference box). And the family sglang#31597 catalogued in July, whose two fixes were closed without being merged: a stop_token_ids or input_ids entry past the vocabulary indexes a scatter_add_ or the embedding out of bounds, and n expands a list before anything is scheduled. The vocabulary is learned from the one place the engine states it, the message refusing an out-of-range logit_bias; when that probe fails the guard stands down rather than refuse traffic it cannot judge, and a negative id is refused either way. v6.19: POST /v1/systemone, typed decisions with the Jev wire contract, served by the lane this proxy fronts. One chat completion of one token per question, options as single-token letters, probabilities from top_logprobs, the state as the shared prefix the radix cache reuses. top_logprobs on /v1/chat/completions and never token_ids_logprob on /generate: on the served build the latter kills the scheduler on the first batch that mixes it with an ordinary request (sglang#34719), and a shared lane mixes on every step. Jev's three aliases resolve to the served model and every other name is refused the way the hosted API refuses it, so the TypeSafe SDK runs here with one base URL changed and a bad request reads the same: 422 with a detail list that names the path that failed, 400 for a request that parses and cannot be served, each shape probed case by case against api.typesafe.ai. v6.18: a reasoning-effort level the chat template knows but SGLang's request model does not is relayed through chat_template_kwargs instead of being refused at the door. Nothing in SGLang's own enum is touched. v6.17: the identity wall learns the second half of its job. v6.16 named WHO; admission is a separate question, and forwarding the client's token verbatim meant a labeled request met the engine's own --api-key and died there: the wall identified everyone and admitted no one (found live on the reference box, not in a test: the fake engines enforce nothing, the real one does). QWEN38_UPSTREAM_API_KEY names the engine's key to the proxy; when both are set, the client's bearer names them on the journal line and the engine's key admits them upstream, on relays and on abort calls alike. Without it the old verbatim behavior stays, and the banner warns loudly: an engine with no key check of its own, or one shared key on purpose, changes nothing. v6.16: two walls operators kept building in front of this box, built in but opt-in. Optional TLS: name a certificate with QWEN38_TLS_CERT (and QWEN38_TLS_KEY when the key is a separate file) and the listening socket speaks it; unset changes nothing for the loopback and tailnet users this box is designed for. Optional per-client identity: QWEN38_CLIENT_KEYS_FILE is a JSON map of bearer token to label; when set, a /v1/ request without a listed key gets 401 in its own dialect, /health stays open for monitoring, and the label rides every journal line of that request (who sent what, the question one shared key can never answer). A keys file that is missing, malformed or empty makes the unit refuse to start: an identity wall that vanished silently is worse than no wall. What the engine sees is v6.17's business now (which key admits a named client); naming them is this version's. v6.15: an image costs what it costs, and a refusal a client can act on. The oversize guard charged every media part a flat 4,096 tokens. Measured against this engine at twelve sizes, an agent screenshot really costs 880 (1280x720) to 1,562 (1680x950), so a session holding 24 of them carried ~61,000 tokens of context it was not using: on 2026-09-12 a 139,868-token conversation was refused as "200,684 prompt tokens". Every oversize refusal this box has logged was such a session. The guard now reads the image header (PNG, JPEG, GIF, WebP) and prices it with the vision tower's own geometry (patch 16 x merge 2, clamped into the processor's pixel range), exact at all twelve sizes; the flat budget survives only for what has no readable header. The refusal also says "the prompt is too long" and carries error.code=context_length_exceeded, because a client that does not recognise the refusal as an overflow just resends the same prompt: opencode did, twice, 3 s apart. v6.14: an abandoned request no longer becomes a zombie. Three holes, all measured here on 2026-09-09 (6,582 flood lines in one day, one request decoding 6 minutes for nobody): a client that gave up during prefill left a request the proxy could not name, because it learned the rid from the first SSE event; the Anthropic dialect's id (msg_) was sent to /abort_request although it names nothing the engine knows; and the abort was fired in a thread that raced the socket close, which is what deletes the state the abort needs (sglang #35255, in main since 2026-09-04 and in neither image this repo serves). The proxy now imposes the rid with x-override-rid on the routes that honour it, aborts synchronously before closing, and on /v1/messages, where the engine mints its own id and applies no header overrides, drains the answer to its end instead of orphaning it. v6.13: Claude Code's Artifact tool carries an ECMA-262 'pattern' with Unicode property escapes ([^\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}...]). SGLang validates every tool schema with jsonschema, whose 'regex' format check compiles patterns with Python's re, which raises "bad escape \\p": the engine answered 400 to EVERY request of the session (measured 09/09 against Claude Code v2.1.266, sglang serving_chat.py:868). The proxy drops the patterns Python cannot compile and forwards the rest untouched. v6.12: the tripwire trips at 128 marker characters (48 is a plausible banner line in a code block; 128 is not something a model writes, and real corruption runs to max_tokens), and the OpenAI dialect gets "data: [DONE]" after the error event so a strict client sees a terminated stream, not a truncated one. v6.11: a corruption tripwire. A decode kernel that loses its state on this hardware emits runs of token id 0, which is "!" in the Qwen tokenizer (sglang#36537, #36558, #36806, #36845). The proxy counts consecutive marker characters across the stream and, past CORRUPTION_RUN of them, aborts the generation upstream and sends the client an explicit error instead of a wall of exclamation marks. It reads only the delta text it already relays; nothing is logged or rewritten. v6.10: the cached KV pool is dropped whenever the engine proves unreachable or a refresh read fails. It was cached for 600 s and invalidated nowhere, so after an engine restart the oversize guard enforced the previous engine's limit for up to ten minutes; the pool is a boot lottery and differs by lane (about 863k on 27B against 184k on flash), so a prompt accepted against a stale larger pool could be relayed to a smaller engine and wedge its scheduler. v6.9: an engine that does not answer (stopped, crashed, restarting, loading) gets a 503 engine_unavailable with Retry-After on EVERY path, never a false context_too_long: on 30/08 the size fallback refused a 68k-token request as "~409k tokens" while the engine was restarting after a GPU fault. Unknown request shapes still refuse on size. v6.8: oversize guard counts with the engine tokenizer (size only nominates), 8 percent margin, absolute per-lane prompt ceiling (PROMPT_CEILING_TOKENS). v6.7: abort_request on client loss. v6.6: upstream reads via read1() and TCP_NODELAY on the client side. resp.read(8192) on chunked HTTP BLOCKS until 8 KB (~30 SSE events) accumulate before relaying them at once: measured 2026-08-23, median inter-event gap 0 ms / max 1307 ms through the proxy vs a steady 118 ms direct. read1() returns as soon as bytes are available, so the stream stays token by token. """ import base64, collections, concurrent.futures, hashlib, hmac, http.client, io, ipaddress, json, math, os, queue, re, select, socket, ssl, string, subprocess, sys, threading, time, urllib.parse, urllib.request, urllib.error, uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer class EngineUnreachable(Exception): """The engine did not answer /tokenize: stopped, crashed, restarting or still loading.""" # The image and video lanes hold the GPU instead of a text engine once the box is # switched to one of them, and a text engine does not come back from that by itself. # Asked only on the error path, where the answer changes what the client is told, # and at most every 5 s per lane. IMAGE_UNIT = "qwen38-image.service" _IMAGE_SEEN = {"ts": -1e9, "active": False} VIDEO_UNIT = "qwen38-video.service" _VIDEO_SEEN = {"ts": -1e9, "active": False} def _lane_active(unit: str, seen: dict) -> bool: now = time.monotonic() if now - seen["ts"] > 5: try: seen["active"] = subprocess.run(["systemctl", "is-active", "--quiet", unit], timeout=2).returncode == 0 except Exception: seen["active"] = False seen["ts"] = now return seen["active"] def image_lane_serving(): return _lane_active(IMAGE_UNIT, _IMAGE_SEEN) def video_lane_serving(): return _lane_active(VIDEO_UNIT, _VIDEO_SEEN) # ── Holding a request while its engine comes back (v6.28, role 6) ────────── # Only the units the installed proxy names count: a proxy run by hand or by a test, with # PROXY_HOLD_UNITS unset, answers an absent engine at once, as it always did. HOLD_UNITS = tuple(os.environ.get("PROXY_HOLD_UNITS", "").split()) HOLD_MAX_S = float(os.environ.get("PROXY_HOLD_MAX_S", "1200") or 0) HOLD_POLL_S = float(os.environ.get("PROXY_HOLD_POLL_S", "2") or 2) # An engine that answers again and still fails the request (its info route is up, its # generations still 503: a boot not quite done) gets it again this many times, each after a # pause. Without the bound and the pause, the request went back to it in a loop with no # sleep until PROXY_HOLD_MAX_S (found in review before v6.28 shipped). HOLD_ROUNDS_MAX = 10 _HOLD_SEEN = {"ts": -1e9, "coming": False} _HOLD_LOCK = threading.Lock() # The systemd jobs that end with the unit started. A restart runs its stop half as the unit # "deactivating" under a job of type restart, and a stop under one of type stop (both read # from `systemctl list-jobs` on the reference box, 2026-10-01). _BACK_JOBS = ("start", "restart", "try-restart", "reload-or-start") def engine_coming(): """True when a unit named in PROXY_HOLD_UNITS is starting, waiting for its next attempt, up, or stopping only to start again: a restart. A hold that ended on the restart's stop half sent every waiting client an error to answer (seen 2026-10-01, when the cockpit restarted an engine left without its scheduler). systemd is asked at most every 2 s.""" if not HOLD_UNITS or HOLD_MAX_S <= 0: return False with _HOLD_LOCK: now = time.monotonic() if now - _HOLD_SEEN["ts"] > 2: try: out = subprocess.run(["systemctl", "show", *HOLD_UNITS, "-p", "ActiveState", "--value"], capture_output=True, text=True, timeout=3).stdout.split() coming = any(st in ("active", "activating", "reloading") for st in out) if not coming: jobs = subprocess.run(["systemctl", "list-jobs", "--no-legend", "--no-pager", *HOLD_UNITS], capture_output=True, text=True, timeout=3).stdout coming = any(len(f) >= 3 and f[1] in HOLD_UNITS and f[2] in _BACK_JOBS for f in (ln.split() for ln in jobs.splitlines())) _HOLD_SEEN["coming"] = coming except Exception: _HOLD_SEEN["coming"] = False _HOLD_SEEN["ts"] = now return _HOLD_SEEN["coming"] def engine_answers(): """True when the engine answers at all: any status under 500 on its info route. A held request may go then; 5xx is SGLang starting or stopping, and no answer is no engine.""" try: headers = {"Authorization": f"Bearer {_api_key()}"} except OSError: headers = {} # a 401 still says an engine is there # v6.39: an engine without SGLang's info routes (vLLM) is probed on /health, which there # generates nothing req = urllib.request.Request(UPSTREAM + (_INFO_ROUTE["path"] or "/health"), headers=headers) try: urllib.request.urlopen(req, timeout=10).read() return True except urllib.error.HTTPError as e: return e.code < 500 except Exception: return False def engine_gone_reason(): """What an unanswering engine means on this box, and what brings it back.""" if image_lane_serving(): return ("This box is serving images right now (qwen38-image.service), and a text engine " "does not come back by itself: switch back to a text lane from the cockpit's " "switcher, or run ./switch-model.sh with a text target") if video_lane_serving(): return ("This box is serving video right now (qwen38-video.service), and a text engine " "does not come back by itself: switch back to a text lane from the cockpit's " "switcher, or run ./switch-model.sh with a text target") return "It is stopped, restarting or still loading (a restart takes minutes, about 9 on a DGX Spark)" # The interface this proxy listens on. It answered on every one of them until v6.21, and # on the reference box seven days of journal showed 8,288 requests, every last one from # 127.0.0.1: the clients that need it (opencode, Claude Code, the cockpit) run on the # same machine. An interface nobody uses is an interface worth not opening, so an # operator can close it, and the default stays what it was because someone else's laptop # may legitimately point at this port. BIND = os.environ.get("PROXY_BIND", "0.0.0.0").strip() or "0.0.0.0" UPSTREAM = os.environ.get("UPSTREAM", "http://127.0.0.1:30000") KEEPALIVE_S = float(os.environ.get("KEEPALIVE_S", "10")) MAX_SILENCE_S = float(os.environ.get("MAX_SILENCE_S", "3600")) CLIENT_IO_S = float(os.environ.get("CLIENT_IO_S", "900")) # write blocked toward a frozen client TLS_HANDSHAKE_S = float(os.environ.get("QWEN38_TLS_HANDSHAKE_S", "10")) # A TLS client that connects and then says nothing must not pin a handshake thread (or, # before S6, the accept loop itself) open for CLIENT_IO_S; the handshake gets this # short, separate budget. # Oversize guard (v6.7): a prompt longer than the engine's KV pool is not rejected by # this SGLang build, it wedges the scheduler (measured 29/08). The proxy learns the # pool size from /get_server_info once the upstream is healthy and refuses, with a # clear 400, a body the engine's own count puts past it. # Where the engine would accept a prompt that can wedge it (see wedge_possible), which bodies # get counted is decided by a bound (v6.34): a token is at least one byte, so no body can be # more tokens than it has bytes, and one that fits by its byte length fits. It was 2.5, an # average: prose runs 3.4 to 4.6 bytes a token on the served tokenizer, but digits are one # token each, so a body of numbers went through uncounted at well over twice its estimate. # A value at or under 0 would divide by nothing. CHARS_PER_TOKEN_MIN = float(os.environ.get("CHARS_PER_TOKEN_MIN", "1.0")) if CHARS_PER_TOKEN_MIN <= 0: CHARS_PER_TOKEN_MIN = 1.0 # The average this guard used before v6.34. It still nominates where no wedge is possible # (the engine refuses past its own window), and it judges a body the engine cannot count (a # shape its tokenizer refuses), so those paths decide as they did. It is not a bound, which # is why it never refuses a body the engine has counted. NOCOUNT_CHARS_PER_TOKEN = 2.5 # Usable share of the pool for one prompt: the rest is room for the answer and the # scheduler's own buffers. The 92 percent comes from the flash lane as it was in v1.5: # with a 178,560-token pool a single prompt topped out near 165K (CHANGELOG v1.5.x). OVERSIZE_MARGIN_FRAC = float(os.environ.get("OVERSIZE_MARGIN_FRAC", "0.08")) # Absolute ceiling for one prompt, in tokens (0 = none). The KV pool is not the only limit: # on the flash lane the prefill of a long prompt grows the engine's footprint by ~0.27 GiB # per 1k tokens beyond ~90k (measured 29/08), so the ceiling that keeps the box away from # the memory edge is a token count set per lane by install.sh, not a share of the pool. PROMPT_CEILING_TOKENS = int(os.environ.get("PROMPT_CEILING_TOKENS", "0") or 0) # The flash lane's own ceiling, applied while the flash lane is what serves (v6.25), which # the served model's name says. It was PROMPT_CEILING_TOKENS above, set per install and # moved by switch-model.sh at switch time with a proxy restart, while the old lane still # served: a switch to flash queued behind a 27B serving 1M refused every prompt past # 250,000 until the next boot, and the restart cut every stream in flight (found in review, # 2026-09-24). PROMPT_CEILING_TOKENS stays, as a ceiling on any lane. FLASH_PROMPT_CEILING_TOKENS = int(os.environ.get("FLASH_PROMPT_CEILING_TOKENS", "0") or 0) FLASH_SERVED_NAMES = frozenset({"qwen3.8-flash-next"}) # Hard ceiling on one request body, in bytes (0 = none). The oversize guard # below measures prompt bodies once they are read; without a cap a lying or broken # Content-Length in the gigabytes is allocated before anything is counted, # and a non-numeric one kills the handler thread with a ValueError (measured: # the client gets zero bytes back and the journal only says "no outcome"). # 256 MiB is ~100x the largest legit text request on the 1M lane and leaves # heavy vision payloads room. MAX_BODY_BYTES = int(os.environ.get("MAX_BODY_BYTES", str(256 * 1024 * 1024)) or 0) # Every body in flight at once, in bytes (2026-10-16; 0 = none). MAX_BODY_BYTES caps one body # and nothing capped them together: each is read whole and parsed again by the guards, and four # legitimate bodies near the cap reach the unit's MemoryMax=1G at once, where the kernel kills # the proxy and every stream in flight with it (found in review, 2026-10-16). Past this budget a # body is not read: 503 with Retry-After, which the SDKs and the agents retry. A body arriving # when none is in flight is always read, so a budget under the cap never refuses one forever. BODY_BUDGET_BYTES = int(os.environ.get("BODY_BUDGET_BYTES", str(384 * 1024 * 1024)) or 0) # A body at or under BODY_SMALL_BYTES is always read and holds none of the budget; a larger one # takes its bytes from it as they arrive, BODY_SMALL_BYTES at a time (2026-10-17). The budget was # taken whole on the Content-Length before a byte was read, and kept to the end: a key holder # announcing large bodies and sending nothing held all of it, and every other body, the box's own # clients' included, got a 503 (found in review, 2026-10-17). A larger body that finds no room on # its way is refused then, except the oldest one being read, which waits up to BODY_WAIT_S for # the room the others give back: two bodies read at once could otherwise each keep the other out # until both were refused. BODY_SMALL_BYTES = int(os.environ.get("BODY_SMALL_BYTES", str(1024 * 1024)) or 0) BODY_WAIT_S = float(os.environ.get("BODY_WAIT_S", "30") or 0) _BODY_BUDGET = {"used": 0, "seq": 0} _BODY_READERS = set() # the admission numbers of the larger bodies being read now _BODY_BUDGET_LOCK = threading.Lock() _BODY_ROOM = threading.Condition(_BODY_BUDGET_LOCK) # Time to first response byte from the upstream on GETs (models, health, load: # always fast or dead). Generations keep no deadline: a cold 690k-token # prefill legitimately takes tens of minutes to answer, streaming or not, and # any finite timeout there would break that flagship use case. UPSTREAM_GET_TIMEOUT_S = float(os.environ.get("UPSTREAM_GET_TIMEOUT_S", "30")) def lane_ceiling(): """The one-prompt ceiling for the lane that serves now (0 = none): PROMPT_CEILING_TOKENS on any lane, and the flash lane's own while it serves. A lane that cannot be told gets the flash one too, when it is set: a refusal a client can retry is the cheaper mistake, the ceiling being what keeps a long flash prefill off the memory edge.""" ceiling = PROMPT_CEILING_TOKENS if FLASH_PROMPT_CEILING_TOKENS > 0: try: served = set(served_models()) except EngineUnreachable: served = set() if not served or served & FLASH_SERVED_NAMES: ceiling = FLASH_PROMPT_CEILING_TOKENS if ceiling <= 0 else min(ceiling, FLASH_PROMPT_CEILING_TOKENS) return ceiling def wedge_possible(pool): """True when the engine would accept a prompt past the share of its pool this guard lets through, the zone where a prompt is queued and never admitted (a wedge): its window (max_req_input_len) is larger than that share, or not known. On the 27B lane the engine accepts up to 863,638 tokens on a pool of 863,644, past the 794,552 usable here (measured 2026-10-08). Only there is a body nominated by its bound, at a measured cost of one more count (115 ms on a lone 300 kB prompt, 1.65 s on a burst of eight). Where the window is under that share (the flash lane: 262,138 for 428,823 usable of 466,112), the engine refuses past it itself, and the average nominates as it always did.""" window = _POOL.get("window") return pool is None or not window or window > int(pool * (1.0 - OVERSIZE_MARGIN_FRAC)) def nomination_estimate(n_bytes, pool): """The token estimate that decides whether a body is counted: its bound where a wedge is possible, the pre-v6.34 average elsewhere.""" return n_bytes / (CHARS_PER_TOKEN_MIN if wedge_possible(pool) else NOCOUNT_CHARS_PER_TOKEN) def prompt_limit(pool): """Usable prompt tokens: the pool share, capped by the serving lane's ceiling when set.""" limit = int(pool * (1.0 - OVERSIZE_MARGIN_FRAC)) ceiling = lane_ceiling() if ceiling > 0: limit = min(limit, ceiling) return limit MEDIA_BLOCKS = ("image", "image_url", "input_audio", "video_url", "document", "audio_url") # Fallback budget for a media part whose real cost cannot be derived: audio, video, # documents, and images whose header the parser below does not recognise. An IMAGE # is never guessed at any more, because guessing was the bug (see _image_tokens). TOKENS_PER_MEDIA = int(os.environ.get("TOKENS_PER_MEDIA", "4096")) # Vision geometry of every checkpoint this repo serves (patch_size 16, merge_size 2 # in preprocessor_config.json, identical on the 27B and flash lanes): the vision # tower sees a grid of MEDIA_PATCH_PX-sized cells and emits one token per cell. MEDIA_PATCH_PX = int(os.environ.get("MEDIA_PATCH_PX", "32")) MEDIA_MIN_PIXELS = int(os.environ.get("MEDIA_MIN_PIXELS", "65536")) # size.shortest_edge MEDIA_MAX_PIXELS = int(os.environ.get("MEDIA_MAX_PIXELS", "16777216")) # size.longest_edge # Tokens a single image adds beyond its cells: <|vision_start|> and <|vision_end|>. # The stripped body loses the whole block, so the delta is cells + 2 (measured). MEDIA_WRAP_TOKENS = 2 # An IMAGE whose header the parser does not recognise is still bounded: the # processor clamps it to MEDIA_MAX_PIXELS, so no image can ever cost more than # that many cells. Charging the bound (16,384 at the stock geometry) instead of # the flat budget keeps the guard honest in the direction that matters, because # a 3840x2160 screenshot really costs 8,162 and the flat 4,096 would UNDER-count # it. opencode only ever attaches jpeg, png, gif and webp, all four of which the # parser reads, so this is the belt to the parser's braces. IMAGE_BLOCKS = ("image", "image_url") # Bytes of the payload to look at when reading an image header. PNG, GIF and WebP # carry the size in the first 32; JPEG hides it behind APPn segments and quant # tables, so the scan needs room, and 48 KiB covers an EXIF thumbnail too. MEDIA_HEADER_BYTES = 48 * 1024 # Corruption tripwire: consecutive "!" (token id 0) that mean the decode path lost # its state rather than the model writing prose. 0 disables the guard. CORRUPTION_RUN = int(os.environ.get("CORRUPTION_RUN", "128") or 0) CORRUPTION_MARK = "!" # Optional TLS: name the operator's own certificate (tailnet CA, LAN-trusted) and # the socket speaks it. The proxy invents no trust, it speaks the one you point at. TLS_CERT = os.environ.get("QWEN38_TLS_CERT", "") TLS_KEY = os.environ.get("QWEN38_TLS_KEY", "") # The engine's own key, held by the proxy for admission (v6.17). Unset means the # client's header goes through verbatim, exactly as before: fine for an engine # with no key check of its own, or one shared key on purpose. UPSTREAM_API_KEY = os.environ.get("QWEN38_UPSTREAM_API_KEY", "") # Optional per-client identity: JSON {"": "