Files
alzeo/tests/test_proxy_guard.py
T
Hasan BasbunarandClaude Opus 5 f0034de5ca v1.10.2: the window the model actually has
The flash lane serves 262,144 tokens and opencode was allowed 175,000 of them.
The ceiling that capped it was not wrong, it was stale: it came from the v1.5
engine, whose PLE mapping faulted in whole page-cache folios and made a long
prefill cost ~0.27 GiB per 1k tokens past 90k. v1.8 serves an engine that trims
that, and nobody re-measured.

Measured now, MemAvailable sampled through every prefill, engine up 19 h with
the PLE budget filled: 195,784 tokens cost 1.16 GiB and 94.7 s; 225,051 cost
1.57 GiB and 111.3 s; 249,500 cost 1.52 GiB and 126.1 s with the floor at 6.9
GiB. Needle 3/3 exact at 200,058 / 230,231 / 249,838. Flat past 200k, an order
of magnitude under the v1.5 engine. Memory is no longer what caps this lane;
max_req_input_len (262,138) is.

- The one-prompt ceiling is 250,000, leaving 12,138 tokens under the engine's
  wall. The flash context tier becomes 225,000 / 32,000. Compaction fires at
  205,000 instead of 155,000 and the chain still closes on the measured worst
  step: 225,000 - 20,000 + 43,863 = 248,863 <= 250,000. Verified live: a
  248,796-token prompt served through the proxy in 136 s, one above the ceiling
  still refused with code context_length_exceeded.
- --allow-auto-truncate is gone from the launcher and gated out of every lane.
  It was undocumented. A probe asked for a prompt above the window and got back
  prompt_tokens exactly equal to max_req_input_len with a confident answer, the
  needle gone, and no warning: the engine had quietly cut the context. The proxy
  already refuses above the ceiling, so the flag bought nothing and cost the one
  failure worse than a refusal. Takes effect on the next engine start.
- Compaction stops throwing the window away. opencode's preserve_recent_tokens
  default is min(15000, max(2000, threshold/4)), and that cap was chosen for
  128K models: here a compaction at 205,000 would keep 15,000 and summarise
  190,000. The installed value is a quarter of the threshold (51,000), sized by
  oc-limits.sh --preserve and rewritten by every install and switch, with prune
  on so stale tool output is cleared instead of the conversation summarised.
- A switch now reaches the server that reads the numbers. opencode serve parses
  opencode.json once at startup and never again: with 225,000 on disk the
  running server still answered 175,000 on /config, so every switch left the
  Agent tab compacting against the previous lane's window. install.sh and
  switch-model.sh restart opencode-web.service after the last config write.
- An image the guard cannot parse is charged its geometric ceiling (16,386), not
  the flat budget: a 3840x2160 screenshot really costs 8,162, so the flat 4,096
  under-counted it, which is the direction that lets an oversize prompt through.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 13:59:11 +02:00

861 lines
42 KiB
Python

"""Offline tests for the keepalive proxy's oversize guard (v6.8): body shapes
are converted for the engine's /tokenize endpoint and the count is trusted
over the size estimate. A tiny fake /tokenize server stands in for SGLang."""
import http.server
import importlib.util
import json
import os
import sys
import threading
import time
import unittest
import urllib.error
import urllib.request
from pathlib import Path
HERE = Path(__file__).resolve()
SPEC = importlib.util.spec_from_file_location("kproxy", HERE.parents[1] / "keepalive-proxy.py")
class FakeTokenize(http.server.BaseHTTPRequestHandler):
seen = []
def log_message(self, *a):
pass
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
FakeTokenize.seen.append((self.path, body))
if self.path != "/tokenize":
self.send_response(404); self.end_headers(); return
if body.get("model") in ("__503__", "__400__"): # engine loading / body rejected
self.send_response(int(body["model"].strip("_"))); self.end_headers(); return
def flat(c):
if isinstance(c, list):
return " ".join(str(p.get("text", "")) if isinstance(p, dict) else str(p) for p in c)
return str(c)
text = body.get("prompt") or " ".join(flat(m.get("content", "")) for m in body.get("messages", []))
out = json.dumps({"tokens": [], "count": len(str(text).split()), "max_model_len": 262144}).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out))); self.end_headers(); self.wfile.write(out)
class ProxyGuard(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.srv = http.server.HTTPServer(("127.0.0.1", 0), FakeTokenize)
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
os.environ["UPSTREAM"] = f"http://127.0.0.1:{cls.srv.server_port}"
cls.mod = importlib.util.module_from_spec(SPEC)
sys.argv = ["keepalive-proxy.py"]
SPEC.loader.exec_module(cls.mod)
cls.keyfile = Path.home() / ".config/qwen38/api-key"
cls.had_key = cls.keyfile.exists()
if not cls.had_key:
cls.keyfile.parent.mkdir(parents=True, exist_ok=True)
cls.keyfile.write_text("test-key\n")
@classmethod
def tearDownClass(cls):
cls.srv.shutdown()
if not cls.had_key:
cls.keyfile.unlink()
def test_openai_chat_counted_with_tools(self):
body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "one two three"}],
"tools": [{"type": "function", "function": {"name": "f"}}]}).encode()
self.assertEqual(self.mod.tokenize_count(body, "/v1/chat/completions"), 3)
path, sent = FakeTokenize.seen[-1]
self.assertEqual(path, "/tokenize")
self.assertIn("tools", sent)
def test_completions_prompt(self):
body = json.dumps({"model": "m", "prompt": "a b c d"}).encode()
self.assertEqual(self.mod.tokenize_count(body, "/v1/completions"), 4)
def test_anthropic_shape_converted(self):
body = json.dumps({"model": "m", "system": [{"type": "text", "text": "sys one"}],
"messages": [{"role": "user", "content": [{"type": "text", "text": "hello there"},
{"type": "tool_result", "tool_use_id": "x", "content": "ok"}]},
{"role": "assistant", "content": "fine"}]}).encode()
n = self.mod.tokenize_count(body, "/v1/messages")
_path, sent = FakeTokenize.seen[-1]
self.assertEqual([m["role"] for m in sent["messages"]], ["system", "user", "assistant"])
self.assertIn("sys one", sent["messages"][0]["content"])
self.assertIn("tool_result", sent["messages"][1]["content"]) # non-text blocks counted via their JSON
self.assertGreaterEqual(n, 5)
def test_tool_pattern_python_cannot_compile_is_dropped(self):
"""Claude Code's Artifact tool sends an ECMA-262 pattern with Unicode property
escapes; the engine validates schemas with Python's re and 400s the whole
session over it (09/09). The pattern goes, everything else stays."""
ecma = r'^(?!__.*__$)[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}"\\./[\]]{1,200}$'
body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}],
"tools": [{"name": "Artifact", "input_schema": {"type": "object", "properties": {
"field": {"type": "string", "pattern": ecma},
"doc_id": {"type": "string", "pattern": "^[A-Za-z0-9_-]{1,64}$"}}}}]}).encode()
out, dropped = self.mod.sanitize_tool_schemas(body, "/v1/messages")
self.assertEqual(dropped, [ecma])
props = json.loads(out)["tools"][0]["input_schema"]["properties"]
self.assertNotIn("pattern", props["field"])
self.assertIn("pattern", props["doc_id"]) # a pattern re accepts is kept
self.assertEqual(json.loads(out)["messages"], [{"role": "user", "content": "hi"}])
def test_openai_and_message_level_tools_are_reached(self):
ecma = r"^\p{L}+$"
body = json.dumps({"model": "m",
"tools": [{"type": "function", "function": {"name": "f", "parameters": {
"properties": {"a": {"pattern": ecma}}}}}],
"messages": [{"role": "system", "content": "s", "tools": [
{"name": "g", "input_schema": {"properties": {"b": {"pattern": ecma}}}}]}]}).encode()
out, dropped = self.mod.sanitize_tool_schemas(body, "/v1/chat/completions")
self.assertEqual(len(dropped), 2)
self.assertNotIn("pattern", out.decode())
def test_clean_body_is_forwarded_untouched(self):
"""No marker in the raw bytes: the body is not even parsed."""
body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}],
"tools": [{"name": "f", "input_schema": {"properties": {
"a": {"pattern": "^[a-z]+$"}}}}]}).encode()
out, dropped = self.mod.sanitize_tool_schemas(body, "/v1/messages")
self.assertIs(out, body)
self.assertEqual(dropped, [])
def test_user_content_quoting_a_bad_pattern_is_left_alone(self):
"""The guard walks tool schemas only: a prompt that happens to quote one of
these regexes must reach the engine byte for byte."""
text = r'why does [^\p{Cc}] fail? {"pattern": "\p{L}"}'
body = json.dumps({"model": "m", "messages": [{"role": "user", "content": text}]}).encode()
out, dropped = self.mod.sanitize_tool_schemas(body, "/v1/messages")
self.assertEqual(dropped, [])
self.assertEqual(json.loads(out)["messages"][0]["content"], text)
def test_malformed_and_bodyless_requests_survive(self):
self.assertEqual(self.mod.sanitize_tool_schemas(rb'{"tools": [broken \p{L}', "/v1/messages")[1], [])
self.assertEqual(self.mod.sanitize_tool_schemas(None, "/v1/messages"), (None, []))
self.assertEqual(self.mod.sanitize_tool_schemas(rb'\p{L}', "/health")[1], [])
def test_unknown_shapes_return_none(self):
self.assertIsNone(self.mod.tokenize_count(b"not json", "/v1/chat/completions"))
self.assertIsNone(self.mod.tokenize_count(json.dumps([1, 2]).encode(), "/v1/chat/completions"))
self.assertIsNone(self.mod.tokenize_count(json.dumps({"model": "m", "input": "embeddings"}).encode(), "/v1/embeddings"))
def test_engine_unreachable_raises(self):
# no engine at all (stopped, crashed, restarting): not a size problem, so not None
saved = self.mod.UPSTREAM
self.mod.UPSTREAM = "http://127.0.0.1:1"
try:
with self.assertRaises(self.mod.EngineUnreachable):
self.mod.tokenize_count(json.dumps({"messages": [{"role": "user", "content": "x"}]}).encode(), "/v1/chat/completions")
finally:
self.mod.UPSTREAM = saved
def test_engine_5xx_raises_4xx_counts_by_size(self):
body = {"model": "__503__", "messages": [{"role": "user", "content": "x"}]}
with self.assertRaises(self.mod.EngineUnreachable): # engine still loading
self.mod.tokenize_count(json.dumps(body).encode(), "/v1/chat/completions")
body["model"] = "__400__" # engine rejected this body
self.assertIsNone(self.mod.tokenize_count(json.dumps(body).encode(), "/v1/chat/completions"))
def test_openai_image_parts_counted_not_tokenized(self):
big = "A" * 400_000 # a base64 image is body size, not prompt text
body = json.dumps({"model": "m", "messages": [{"role": "user", "content": [
{"type": "text", "text": "describe this one"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64," + big}}]}]}).encode()
n = self.mod.tokenize_count(body, "/v1/chat/completions")
_path, sent = FakeTokenize.seen[-1]
self.assertNotIn("image_url", json.dumps(sent))
# No readable header in that filler, so the image gets the geometric
# ceiling rather than a flat guess, and never its base64 as text.
self.assertEqual(n, 3 + self.mod._image_ceiling())
def test_anthropic_image_block_counted_not_tokenized(self):
body = json.dumps({"model": "m", "messages": [{"role": "user", "content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "B" * 300_000}},
{"type": "text", "text": "two words"}]}]}).encode()
n = self.mod.tokenize_count(body, "/v1/messages")
_path, sent = FakeTokenize.seen[-1]
self.assertNotIn("BBBB", json.dumps(sent))
self.assertEqual(n, 2 + self.mod._image_ceiling())
# ---- media is priced, not guessed (v6.15) -----------------------------
# The engine's numbers below are measured on the reference box (2026-09-13,
# RadixArk/Qwen3.8-Flash-Next-NVFP4, patch 16 x merge 2): the formula matched
# the engine's own prompt_tokens exactly at all twelve sizes tried.
MEASURED = {(1280, 720): 882, (1400, 800): 1102, (1600, 900): 1402,
(1680, 950): 1562, (923, 2000): 1800, (2000, 2000): 3846,
(3840, 2160): 8162, (4000, 4000): 15627,
(64, 64): 66, (200, 150): 72, (390, 844): 314, (4500, 4500): 16386}
@staticmethod
def _png(w, h):
"""A PNG that is nothing but a valid header: the parser reads no further."""
import struct, zlib
ihdr = struct.pack(">II", w, h) + bytes([8, 2, 0, 0, 0])
return (b"\x89PNG\r\n\x1a\n"
+ struct.pack(">I", len(ihdr)) + b"IHDR" + ihdr
+ struct.pack(">I", zlib.crc32(b"IHDR" + ihdr)))
def test_image_tokens_match_the_engine_at_every_measured_size(self):
for (w, h), expected in self.MEASURED.items():
with self.subTest(size=f"{w}x{h}"):
self.assertEqual(self.mod._image_tokens(w, h), expected)
def test_image_dims_read_png_jpeg_gif_webp_headers(self):
import struct
self.assertEqual(self.mod._image_dims(self._png(1680, 950)), (1680, 950))
jpeg = (b"\xff\xd8"
+ b"\xff\xe0" + struct.pack(">H", 16) + b"JFIF\x00" + b"\x00" * 9
+ b"\xff\xc0" + struct.pack(">H", 17) + b"\x08" + struct.pack(">HH", 950, 1680)
+ b"\x03" + b"\x00" * 9)
self.assertEqual(self.mod._image_dims(jpeg), (1680, 950))
self.assertEqual(self.mod._image_dims(b"GIF89a" + struct.pack("<HH", 640, 480)), (640, 480))
webp = (b"RIFF" + b"\x00" * 4 + b"WEBPVP8X" + b"\x00" * 8
+ (1679).to_bytes(3, "little") + (949).to_bytes(3, "little"))
self.assertEqual(self.mod._image_dims(webp), (1680, 950))
def test_screenshot_costs_what_the_engine_charges_not_the_flat_budget(self):
"""The field failure of 2026-09-12: 24 screenshots in one conversation.
Charged flat, they were 98,304 tokens and the request was refused at
"200,684 prompt tokens"; the engine was serving 139,868. Counted from
their headers they are 37,488, and the same conversation fits.
"""
import base64
url = "data:image/png;base64," + base64.b64encode(self._png(1680, 950)).decode()
shots = [{"type": "image_url", "image_url": {"url": url}} for _ in range(24)]
body = json.dumps({"model": "m", "messages": [{"role": "user", "content":
[{"type": "text", "text": "one two three"}] + shots}]}).encode()
n = self.mod.tokenize_count(body, "/v1/chat/completions")
self.assertEqual(n, 3 + 24 * 1562)
self.assertLess(n, 24 * self.mod.TOKENS_PER_MEDIA)
def test_anthropic_image_block_priced_from_its_header(self):
import base64
body = json.dumps({"model": "m", "messages": [{"role": "user", "content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png",
"data": base64.b64encode(self._png(1280, 720)).decode()}},
{"type": "text", "text": "two words"}]}]}).encode()
self.assertEqual(self.mod.tokenize_count(body, "/v1/messages"), 2 + 882)
def test_an_unreadable_image_is_charged_its_geometric_ceiling(self):
"""Nothing is ever guessed downward.
A 3840x2160 screenshot really costs 8,162, so the old flat 4,096 would
UNDER-count an image it could not parse, which is the direction that
lets an oversize prompt through to the engine. An image is bounded by
the processor's max_pixels, so the fallback is that bound.
"""
for block in (
{"type": "image_url", "image_url": {"url": "https://example.invalid/a.png"}},
{"type": "image_url", "image_url": {"url": "data:image/heic;base64,AAAAAAAAAAAA"}},
{"type": "image", "source": {"type": "url", "url": "https://example.invalid/a.png"}},
):
with self.subTest(block=block["type"]):
self.assertEqual(self.mod._media_tokens(block), self.mod._image_ceiling())
self.assertGreater(self.mod._image_ceiling(), self.mod._image_tokens(3840, 2160))
def test_media_that_is_not_an_image_keeps_the_flat_budget(self):
"""Audio, video and documents have no geometry to bound them."""
for block in (
{"type": "input_audio", "input_audio": {"data": "AAAA", "format": "wav"}},
{"type": "document", "source": {"type": "base64", "data": "AAAA"}},
{"type": "video_url", "video_url": {"url": "https://example.invalid/a.mp4"}},
):
with self.subTest(block=block["type"]):
self.assertEqual(self.mod._media_tokens(block), self.mod.TOKENS_PER_MEDIA)
def test_prompt_limit_pool_share_and_ceiling(self):
saved = self.mod.PROMPT_CEILING_TOKENS
try:
self.mod.PROMPT_CEILING_TOKENS = 0
self.assertEqual(self.mod.prompt_limit(184384), 169633)
self.mod.PROMPT_CEILING_TOKENS = 135000
self.assertEqual(self.mod.prompt_limit(184384), 135000)
self.assertEqual(self.mod.prompt_limit(100000), 92000) # ceiling above the share: share wins
finally:
self.mod.PROMPT_CEILING_TOKENS = saved
def test_margin_default(self):
self.assertAlmostEqual(self.mod.OVERSIZE_MARGIN_FRAC, 0.08)
self.assertEqual(int(178560 * (1 - self.mod.OVERSIZE_MARGIN_FRAC)), 164275)
class LoadingEngine(http.server.BaseHTTPRequestHandler):
"""Answers /get_server_info (so the proxy knows the pool) but is still loading:
503 on /tokenize and on generations, like SGLang between 'Started' and 'ready'."""
def log_message(self, *a):
pass
def do_GET(self):
if self.path == "/get_server_info":
out = json.dumps({"max_total_num_tokens": 200000}).encode()
self.send_response(200); self.send_header("Content-Length", str(len(out)))
self.end_headers(); self.wfile.write(out); return
self.send_response(503); self.end_headers()
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length") or 0))
self.send_response(503); self.end_headers()
class ProxyInFrontOfLoadingEngine(unittest.TestCase):
"""v6.9: a body the size guard nominates must come back 503 engine_unavailable while the
engine is down, never 400 context_too_long (live on 2026-08-30 01:15: '~409k tokens' for a
68,626-token request during an engine restart)."""
@classmethod
def setUpClass(cls):
import socket, subprocess, sys, time
cls.eng = http.server.HTTPServer(("127.0.0.1", 0), LoadingEngine)
threading.Thread(target=cls.eng.serve_forever, daemon=True).start()
with socket.socket() as sk:
sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1]
# This class models a loading engine whose pool IS known (200000 via
# /get_server_info) while /tokenize still 503s. pool_tokens() needs the
# api-key file to ask, so provide one when the (possibly throwaway)
# HOME has none; without it the pool reads as unknown and the new
# warmup hold answers first (also 503, different type).
cls.keyfile = Path.home() / ".config/qwen38/api-key"
cls.had_key = cls.keyfile.exists()
if not cls.had_key:
cls.keyfile.parent.mkdir(parents=True, exist_ok=True)
cls.keyfile.write_text("test-key\n")
env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}")
cls.proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(100):
try:
socket.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break
except OSError:
time.sleep(0.05)
@classmethod
def tearDownClass(cls):
cls.proc.terminate(); cls.proc.wait(timeout=5); cls.eng.shutdown()
if not cls.had_key:
cls.keyfile.unlink()
def _post(self, body):
req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions", data=body,
headers={"Content-Type": "application/json"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=10) as r:
return r.status, dict(r.headers), r.read()
except urllib.error.HTTPError as e:
return e.code, dict(e.headers), e.read()
def test_big_body_is_503_engine_unavailable_not_400(self):
body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "word " * 300000}]}).encode()
self.assertGreater(len(body), 1_000_000)
status, headers, raw = self._post(body)
self.assertEqual(status, 503)
err = json.loads(raw)["error"]
self.assertEqual(err["type"], "engine_unavailable")
self.assertIn("NOT refused for its size", err["message"])
self.assertEqual(headers.get("Retry-After"), "30")
def test_small_body_is_503_too(self):
status, _headers, raw = self._post(json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}]}).encode())
self.assertEqual(status, 503)
self.assertEqual(json.loads(raw)["error"]["type"], "engine_unavailable")
class SmallPoolEngine(http.server.BaseHTTPRequestHandler):
"""A healthy engine with a tiny pool: it answers /get_server_info and counts
with /tokenize, so the guard has everything it needs to refuse on size."""
def log_message(self, *a):
pass
def do_GET(self):
if self.path == "/get_server_info":
out = json.dumps({"max_total_num_tokens": 20000}).encode()
self.send_response(200); self.send_header("Content-Length", str(len(out)))
self.end_headers(); self.wfile.write(out); return
self.send_response(404); self.end_headers()
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)))
if self.path == "/tokenize":
text = " ".join(str(m.get("content", "")) for m in body.get("messages", []))
out = json.dumps({"count": len(text.split()), "max_model_len": 262144}).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out))); self.end_headers()
self.wfile.write(out); return
self.send_response(404); self.end_headers()
class RefusalIsRecognisableAsOverflow(unittest.TestCase):
"""v6.15: a refusal a client cannot classify is a refusal it cannot recover from.
opencode (and every AI-SDK client) decides "this is a context overflow, compact
and retry" by matching the provider's message against a fixed vocabulary, or by
reading error.code == "context_length_exceeded". The v6.14 message matched
nothing in that vocabulary and carried no code, so the session resent the same
prompt and got the same 400: measured on this box 2026-09-12 23:18:00 and
23:18:03, two identical refusals 3 s apart, no compaction between them.
The regexes below are opencode 1.18.27's own list, read out of the binary."""
OPENCODE_OVERFLOW_VOCABULARY = [
r"prompt is too long", r"request_too_large", r"input is too long for requested model",
r"exceeds the context window", r"input token count.*exceeds the maximum",
r"tokens in request more than max tokens allowed", r"maximum prompt length is \d+",
r"reduce the length of the messages", r"maximum context length is \d+ tokens",
r"exceeds the limit of \d+", r"exceeds the available context size",
r"greater than the context length", r"context window exceeds limit",
r"exceeded model token limit", r"context[_ ]length[_ ]exceeded",
r"request entity too large", r"context length is only \d+ tokens",
r"input length.*exceeds.*context length", r"model_context_window_exceeded",
r"too many tokens", r"token limit exceeded",
]
# The same client refuses to treat these as overflow even when the rest matches.
OPENCODE_NOT_OVERFLOW = [r"^(throttling error|service unavailable):", r"rate limit", r"too many requests"]
@classmethod
def setUpClass(cls):
import socket, subprocess, sys, time
cls.eng = http.server.HTTPServer(("127.0.0.1", 0), SmallPoolEngine)
threading.Thread(target=cls.eng.serve_forever, daemon=True).start()
with socket.socket() as sk:
sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1]
cls.keyfile = Path.home() / ".config/qwen38/api-key"
cls.had_key = cls.keyfile.exists()
if not cls.had_key:
cls.keyfile.parent.mkdir(parents=True, exist_ok=True)
cls.keyfile.write_text("test-key\n")
env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}")
cls.proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(100):
try:
socket.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break
except OSError:
time.sleep(0.05)
@classmethod
def tearDownClass(cls):
cls.proc.terminate(); cls.proc.wait(timeout=5); cls.eng.shutdown()
if not cls.had_key:
cls.keyfile.unlink()
def _refusal(self):
body = json.dumps({"model": "m", "messages": [
{"role": "user", "content": "word " * 120000}]}).encode()
req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions", data=body,
headers={"Content-Type": "application/json"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=10) as r:
self.fail(f"an oversize body was relayed: {r.status}")
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read())["error"]
def test_the_refusal_matches_the_client_overflow_vocabulary(self):
import re
_status, err = self._refusal()
hits = [p for p in self.OPENCODE_OVERFLOW_VOCABULARY if re.search(p, err["message"], re.I)]
self.assertTrue(hits, f"no client would classify this as an overflow: {err['message']}")
for p in self.OPENCODE_NOT_OVERFLOW:
self.assertIsNone(re.search(p, err["message"], re.I),
f"{p!r} makes the client treat an overflow as a rate limit")
def test_the_refusal_carries_the_machine_readable_code(self):
status, err = self._refusal()
self.assertEqual(status, 400)
self.assertEqual(err["code"], "context_length_exceeded")
def test_the_refusal_keeps_its_own_type_for_needle_sh(self):
"""needle.sh reads error.type to tell a refusal from a missed needle."""
_status, err = self._refusal()
self.assertEqual(err["type"], "context_too_long")
def test_the_refusal_still_says_what_and_why(self):
_status, err = self._refusal()
self.assertIn("prompt tokens", err["message"])
self.assertIn("KV pool", err["message"])
class PoolCacheInvalidation(unittest.TestCase):
"""The cached pool must never outlive the engine that reported it.
The pool is a boot lottery and changes outright between lanes (about 863k on
the 27B lane, 184k on flash). Before this, pool_tokens() cached for 600 s and
dropped the value nowhere, so for ten minutes after an engine restart the
guard enforced the previous engine's limit: a prompt sized against a larger
stale pool would be relayed to a smaller one and wedge the scheduler, which
is the failure the guard exists to prevent."""
def setUp(self):
spec = importlib.util.spec_from_file_location(
"kproxy_pool", HERE.parents[1] / "keepalive-proxy.py")
self.m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(self.m)
def test_invalidate_drops_a_cached_pool(self):
self.m._POOL.update(tokens=913334, ts=self.m.time.time())
self.assertEqual(self.m.pool_tokens(), 913334, "fresh cache should be used")
self.m.invalidate_pool()
self.assertIsNone(self.m._POOL["tokens"], "invalidate must clear the value")
self.assertEqual(self.m._POOL["ts"], 0.0, "invalidate must clear the timestamp")
def test_failed_read_does_not_keep_a_stale_pool(self):
# No engine answers on this port, so the refresh read fails. The old
# behaviour returned the stale number; the guard would then size prompts
# against an engine that is not there any more.
self.m.UPSTREAM = "http://127.0.0.1:1"
self.m._POOL.update(tokens=913334, ts=0.0) # cached, but expired
self.assertIsNone(self.m.pool_tokens(),
"a failed refresh must not fall back on the previous engine's pool")
def test_a_smaller_pool_is_picked_up_after_invalidation(self):
# 27B pool cached, then the box switches to the flash lane. Whatever the
# cache said, the limit must follow the engine that is actually serving.
self.m._POOL.update(tokens=863398, ts=self.m.time.time())
big = self.m.prompt_limit(self.m.pool_tokens())
self.m.invalidate_pool()
self.m._POOL.update(tokens=184384, ts=self.m.time.time())
small = self.m.prompt_limit(self.m.pool_tokens())
self.assertLess(small, big, "the flash lane must not inherit the 27B limit")
class CorruptionRun(unittest.TestCase):
"""v6.11 tripwire: runs of token id 0 ("!") are a decode-state failure, not prose."""
@classmethod
def setUpClass(cls):
sys.argv = ["keepalive-proxy.py"]
cls.k = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(cls.k)
def setUp(self):
self.k = type(self).k
def test_a_run_grows_across_events(self):
run = 0
for _ in range(10):
run = self.k.marker_run("!", run)
self.assertEqual(run, 10)
def test_any_real_character_resets_the_run(self):
run = self.k.marker_run("!!!!", 0)
self.assertEqual(run, 4)
self.assertEqual(self.k.marker_run(" hello", run), 0)
def test_a_trailing_run_survives_its_own_event(self):
self.assertEqual(self.k.marker_run("wait!!!", 5), 3)
def test_prose_exclamations_never_reach_the_threshold(self):
run = 0
for word in ("Done", "!", " Great", "!", "!", " Ship it", "!"):
run = self.k.marker_run(word, run)
self.assertLess(run, self.k.CORRUPTION_RUN)
def test_delta_text_reads_both_dialects(self):
self.assertEqual(self.k.delta_text(
{"choices": [{"delta": {"content": "hi"}}]}), "hi")
self.assertEqual(self.k.delta_text(
{"choices": [{"delta": {"reasoning_content": "think"}}]}), "think")
self.assertEqual(self.k.delta_text(
{"type": "content_block_delta", "delta": {"text": "hey"}}), "hey")
self.assertEqual(self.k.delta_text({"choices": [{"delta": {}}]}), "")
def test_tool_arguments_are_not_scanned(self):
# a JSON blob of exclamation marks inside tool arguments is the model's
# business, not a decode failure
self.assertEqual(self.k.delta_text(
{"choices": [{"delta": {"tool_calls": [{"function": {"arguments": "!" * 80}}]}}]}), "")
def test_scan_trips_only_past_the_threshold(self):
h = self.k.H.__new__(self.k.H)
ev = b'data: {"choices":[{"delta":{"content":"!"}}]}\n\n'
fired = [h._scan_corruption(ev) for _ in range(self.k.CORRUPTION_RUN)]
self.assertEqual(fired.count(True), 1)
self.assertTrue(fired[-1])
self.assertFalse(any(fired[:-1]))
def test_scan_ignores_done_and_keepalive_events(self):
h = self.k.H.__new__(self.k.H)
self.assertFalse(h._scan_corruption(b"data: [DONE]\n\n"))
self.assertFalse(h._scan_corruption(
b'data: {"id":"keepalive","choices":[]}\n\n'))
self.assertEqual(getattr(h, "_crun", 0), 0)
def test_the_error_event_names_the_cause_in_both_dialects(self):
oa = self.k.sse_error_openai("boom").decode()
self.assertIn("corrupted_output", oa)
self.assertTrue(oa.startswith("data: "))
an = self.k.sse_error("boom").decode()
self.assertIn("event: error", an)
class CorruptingEngine(http.server.BaseHTTPRequestHandler):
"""Streams the failure this guard exists for: one "!" per SSE event, forever.
/abort_request records that the proxy asked it to stop."""
aborted = []
def log_message(self, *a):
pass
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(n) if n else b"{}"
if self.path == "/abort_request":
CorruptingEngine.aborted.append(json.loads(body or b"{}").get("rid"))
self.send_response(200); self.send_header("Content-Length", "2"); self.end_headers()
self.wfile.write(b"{}"); return
if self.path == "/tokenize":
out = json.dumps({"tokens": [1, 2, 3]}).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out))); self.end_headers()
self.wfile.write(out); return
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.end_headers()
first = json.dumps({"id": "rid-corrupt", "choices": [{"delta": {"content": "Here goes"}}]})
self.wfile.write(b"data: " + first.encode() + b"\n\n"); self.wfile.flush()
bang = json.dumps({"id": "rid-corrupt", "choices": [{"delta": {"content": "!"}}]})
try:
for _ in range(4000):
self.wfile.write(b"data: " + bang.encode() + b"\n\n"); self.wfile.flush()
except Exception:
pass
class CorruptionTripwireEndToEnd(unittest.TestCase):
"""The whole path: a stream that degenerates into token id 0 is cut, the client is told
why, and the engine is asked to stop generating."""
@classmethod
def setUpClass(cls):
import socket, subprocess, time
CorruptingEngine.aborted = []
cls.eng = http.server.ThreadingHTTPServer(("127.0.0.1", 0), CorruptingEngine)
threading.Thread(target=cls.eng.serve_forever, daemon=True).start()
with socket.socket() as sk:
sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1]
env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}",
CORRUPTION_RUN="48", PROMPT_CEILING_TOKENS="0")
cls.proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(100):
try:
socket.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break
except OSError:
time.sleep(0.05)
@classmethod
def tearDownClass(cls):
cls.proc.terminate(); cls.proc.wait(timeout=10)
cls.eng.shutdown(); cls.eng.server_close()
def test_the_stream_is_cut_and_the_client_is_told_why(self):
import time
body = json.dumps({"model": "m", "stream": True,
"messages": [{"role": "user", "content": "hi"}]}).encode()
req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions",
data=body, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=30) as r:
text = r.read().decode("utf-8", "ignore")
self.assertIn("corrupted_output", text)
self.assertIn("decode-state failure", text)
self.assertTrue(text.rstrip().endswith("data: [DONE]"), "the OpenAI stream must end with [DONE]")
# the guard cut the stream well before the engine's 4000 events
self.assertLess(text.count('"!"'), 400, "the wall of exclamation marks was relayed")
for _ in range(40): # the abort is fired on its own thread
if CorruptingEngine.aborted: break
time.sleep(0.05)
self.assertEqual(CorruptingEngine.aborted, ["rid-corrupt"])
class HardeningEngine(http.server.BaseHTTPRequestHandler):
"""Upstream for the v6.15 hardening gates: unknown pool (500 on
/get_server_info), a hanging metadata route, a fast one, and a small
SSE generation."""
def log_message(self, *a):
pass
def do_GET(self):
if self.path == "/get_server_info":
self.send_response(500); self.end_headers(); return
if self.path == "/hang":
time.sleep(5)
try:
self.send_response(200); self.send_header("Content-Length", "2")
self.end_headers(); self.wfile.write(b"{}")
except Exception:
pass
return
out = b'{"ok": true}'
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out))); self.end_headers()
self.wfile.write(out)
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
if n:
self.rfile.read(n)
if self.path == "/tokenize":
self.send_response(500); self.end_headers(); return
ev = b'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: [DONE]\n\n'
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Content-Length", str(len(ev))); self.end_headers()
self.wfile.write(ev)
class HardeningV615(unittest.TestCase):
"""v6.15: a lying Content-Length never allocates, a hanging metadata GET
never parks a thread, and a monster arriving during a restart waits
(503) instead of wedging the scheduler. Small requests still pass."""
@classmethod
def setUpClass(cls):
import socket, subprocess
cls.eng = http.server.ThreadingHTTPServer(("127.0.0.1", 0), HardeningEngine)
threading.Thread(target=cls.eng.serve_forever, daemon=True).start()
with socket.socket() as sk:
sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1]
env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}",
PROMPT_CEILING_TOKENS="200000", UPSTREAM_GET_TIMEOUT_S="1",
MAX_BODY_BYTES="1000000")
cls.proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(100):
try:
socket.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break
except OSError:
time.sleep(0.05)
cls.k = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(cls.k)
@classmethod
def tearDownClass(cls):
cls.proc.terminate(); cls.proc.wait(timeout=10)
cls.eng.shutdown(); cls.eng.server_close()
def _raw(self, head, body=b""):
import socket
sk = socket.create_connection(("127.0.0.1", self.port), timeout=10)
try:
sk.sendall(head + b"\r\n\r\n" + body)
sk.settimeout(10)
out = b""
while b"\r\n\r\n" not in out:
chunk = sk.recv(4096)
if not chunk:
break
out += chunk
return out
finally:
sk.close()
def test_non_numeric_content_length_is_400(self):
out = self._raw(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Length: abc\r\nConnection: close")
self.assertIn(b" 400 ", out.split(b"\r\n", 1)[0])
def test_negative_content_length_is_400(self):
out = self._raw(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Length: -5\r\nConnection: close")
self.assertIn(b" 400 ", out.split(b"\r\n", 1)[0])
def test_body_over_cap_is_413_before_any_read(self):
out = self._raw(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Length: 2000000\r\nConnection: close")
status = out.split(b"\r\n", 1)[0]
self.assertIn(b" 413 ", status)
def _post(self, body):
req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions", data=body,
headers={"Content-Type": "application/json"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=15) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def test_monster_with_unknown_pool_is_503_not_relayed(self):
body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "word " * 150000}]}).encode()
self.assertGreater(len(body), 500_000) # est ~300k tokens, over the 200k ceiling
status, raw = self._post(body)
self.assertEqual(status, 503)
err = json.loads(raw)["error"]
self.assertEqual(err["type"], "engine_warming")
def test_small_body_with_unknown_pool_is_relayed(self):
status, raw = self._post(json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}]}).encode())
self.assertEqual(status, 200)
self.assertIn(b"hi", raw)
def test_hanging_metadata_get_is_503(self):
try:
urllib.request.urlopen(f"http://127.0.0.1:{self.port}/hang", timeout=10)
self.fail("the hanging upstream should have been cut")
except urllib.error.HTTPError as e:
self.assertEqual(e.code, 503)
self.assertEqual(json.loads(e.read())["error"]["type"], "engine_unavailable")
def test_deep_schema_is_left_untouched_and_reported(self):
"""Patterns nested past the depth bound are not pruned (no crash, no
rewrite); the bound hit is reported instead of failing silently."""
node = {"type": "object"}
cur = node
for _ in range(40):
nxt = {"type": "object", "properties": {}}
cur["properties"] = {"x": nxt}
cur = nxt
cur["properties"] = {"a": {"type": "string", "pattern": r"^\p{L}+$"},
"b": {"type": "string", "pattern": r"^\p{N}+$"}}
body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}],
"tools": [{"type": "function", "function": {"name": "f", "parameters": node}}]}).encode()
out, dropped = self.k.sanitize_tool_schemas(body, "/v1/chat/completions")
self.assertIs(out, body)
self.assertEqual(dropped, [])
class HardeningUnits(unittest.TestCase):
"""The v6.15 decisions as pure units: parseable lengths, the read cap,
and the warmup hold, all without a socket."""
def setUp(self):
spec = importlib.util.spec_from_file_location(
"kproxy_units", HERE.parents[1] / "keepalive-proxy.py")
self.m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(self.m)
self.m.UPSTREAM = "http://127.0.0.1:1" # nothing answers: pool stays unknown
self.m.invalidate_pool()
def test_parse_body_length(self):
self.assertEqual(self.m.parse_body_length(None), 0)
self.assertEqual(self.m.parse_body_length(""), 0)
self.assertEqual(self.m.parse_body_length("0"), 0)
self.assertEqual(self.m.parse_body_length("12"), 12)
self.assertIsNone(self.m.parse_body_length("abc"))
self.assertIsNone(self.m.parse_body_length("-5"))
self.assertIsNone(self.m.parse_body_length("12.5"))
def test_body_over_cap(self):
self.m.MAX_BODY_BYTES = 100
self.assertFalse(self.m.body_over_cap(0))
self.assertFalse(self.m.body_over_cap(100))
self.assertTrue(self.m.body_over_cap(101))
self.m.MAX_BODY_BYTES = 0 # 0 disables the cap
self.assertFalse(self.m.body_over_cap(10 ** 12))
def test_warmup_hold_only_delays_monsters(self):
self.assertTrue(self.m.warmup_hold(262145, None))
self.assertFalse(self.m.warmup_hold(262144, None)) # boundary: strictly over
self.assertFalse(self.m.warmup_hold(10, None))
self.assertFalse(self.m.warmup_hold(10 ** 9, 467776)) # known pool: not this gate
self.m.PROMPT_CEILING_TOKENS = 200000
self.assertTrue(self.m.warmup_hold(200001, None))
self.assertFalse(self.m.warmup_hold(200000, None))
if __name__ == "__main__":
unittest.main()