Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
888 changes: 3 additions & 885 deletions apps/sandbox-executor/tests/test_local_llm.py

Large diffs are not rendered by default.

448 changes: 448 additions & 0 deletions apps/sandbox-executor/tests/test_local_llm_config.py

Large diffs are not rendered by default.

295 changes: 295 additions & 0 deletions apps/sandbox-executor/tests/test_local_llm_health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
import contextlib
import http.server
import json
import os
import unittest
from unittest.mock import patch

from sandbox_executor import local_llm

from tests.loopback_http import serve_on_loopback

# why: frozen fixtures for parser coverage only, not performance claims
HEALTH_OFF = {"status": "ok", "prefill_cache": {"enabled": False}, "effective_defaults": {"max_output_tokens": 8192}}
HEALTH_COLD = {
"status": "ok",
"prefill_cache": {"enabled": True, "entries": 0, "cached_tokens": 0, "memory_bytes": 0},
"memory": {"used_bytes": 1048576, "limit_bytes": 8589934592},
"effective_defaults": {"max_output_tokens": 8192},
}
HEALTH_WARM = {
"status": "ok",
"prefill_cache": {"enabled": True, "entries": 3, "cached_tokens": 41234, "memory_bytes": 536870912},
"memory": {"used_bytes": 2147483648, "limit_bytes": 8589934592},
"effective_defaults": {"max_output_tokens": 4096},
}
HEALTH_SMALL_PROMPT = {
"status": "ok",
"prefill_cache": {"enabled": True, "entries": 0},
"effective_defaults": {"max_output_tokens": 16384, "max_prompt_tokens": 32768},
}
HEALTH_MALFORMED = "<html>not json</html>"


def _fetcher(payload, calls=None):
def fetch(url, timeout):
if calls is not None:
calls.append((url, timeout))
return payload if isinstance(payload, str) else json.dumps(payload).encode()

return fetch


class TestHostGateways(unittest.TestCase):
def test_groups_providers_by_server_and_skips_unprobeable_endpoints(self):
host_config = {
"providers": {
"a": {"baseUrl": "http://127.0.0.1:8000/v1", "models": [{"id": "x"}]},
"b": {"baseUrl": "http://127.0.0.1:8000/anthropic", "models": [{"id": "y"}]},
"c": {"baseUrl": "http://gpu.lan:9000/v1", "models": [{"id": "z"}]},
"cloud": {"baseUrl": "https://api.example.com/v1", "models": [{"id": "w"}]},
}
}
allow_list = {"gpu.lan"}
config = local_llm.build_container_config(host_config, allow_list)
gateways = local_llm.host_gateways(host_config, config, {}, allow_list)
self.assertEqual(
gateways,
[
("http://127.0.0.1:8000/v1", frozenset({"a", "b"})),
("http://gpu.lan:9000/v1", frozenset({"c"})),
],
)

def test_synthesised_provider_maps_to_configured_base_url(self):
env = {"HOLON_LOCAL_BASE_URL": "http://localhost:11434/v1", "HOLON_LOCAL_MODELS": "m"}
with patch.dict(os.environ, env, clear=True):
config = local_llm.build_container_config(None)
gateways = local_llm.host_gateways(None, config, env)
self.assertEqual(gateways, [("http://localhost:11434/v1", frozenset(config["providers"]))])


class TestGatewayHealth(unittest.TestCase):
def test_off_cold_warm_classification(self):
for payload, expected in ((HEALTH_OFF, "off"), (HEALTH_COLD, "cold"), (HEALTH_WARM, "warm")):
with self.subTest(expected=expected):
health = local_llm.probe_gateway_health("http://localhost:8081/v1", fetch=_fetcher(payload))
self.assertEqual(health.prefill_cache, expected)
self.assertTrue(health.cache_line().startswith(f"prefill_cache={expected}"))

def test_memory_figures_and_output_default(self):
health = local_llm.probe_gateway_health("http://localhost:8081/v1", fetch=_fetcher(HEALTH_WARM))
self.assertEqual(health.max_output_tokens, 4096)
self.assertEqual(health.memory["memory_used_bytes"], 2147483648)
self.assertEqual(health.memory["cache_memory_bytes"], 536870912)
self.assertIn("memory_limit_bytes=8589934592", health.cache_line())

def test_malformed_response_is_unknown(self):
health = local_llm.probe_gateway_health("http://localhost:8081/v1", fetch=_fetcher(HEALTH_MALFORMED))
self.assertEqual(health.prefill_cache, "unknown")
self.assertEqual(local_llm.parse_gateway_health("u", ["list"]).prefill_cache, "unknown")
self.assertEqual(local_llm.parse_gateway_health("u", {"status": "ok"}).prefill_cache, "unknown")

def test_network_failure_is_unknown(self):
def failing(url, timeout):
raise OSError("connection refused")

health = local_llm.probe_gateway_health("http://127.0.0.1:8081/v1", fetch=failing)
self.assertEqual(health.prefill_cache, "unknown")
self.assertIn("connection refused", health.cache_line())

def test_malformed_http_response_is_unknown(self):
import http.client

for exc in (http.client.BadStatusLine("garbage"), http.client.IncompleteRead(b"{")):
with self.subTest(exc=type(exc).__name__):

def failing(url, timeout, exc=exc):
raise exc

health = local_llm.probe_gateway_health("http://127.0.0.1:8081/v1", fetch=failing)
self.assertEqual(health.prefill_cache, "unknown")
self.assertIn("health probe failed", health.cache_line())

def test_probe_targets_health_path_with_short_timeout(self):
calls = []
local_llm.probe_gateway_health("http://localhost:8081/v1", fetch=_fetcher(HEALTH_OFF, calls))
self.assertEqual(calls, [("http://localhost:8081/health", 2.0)])

def test_never_probes_remote_or_gateway_hosts(self):
calls = []
for url in ("https://api.example.com/v1", "http://192.168.1.20:8081/v1", "http://host.docker.internal:8081/v1"):
with self.subTest(url=url):
self.assertIsNone(local_llm.probe_gateway_health(url, fetch=_fetcher(HEALTH_OFF, calls)))
self.assertEqual(calls, [])
allowed = local_llm.probe_gateway_health(
"http://192.168.1.20:8081/v1", fetch=_fetcher(HEALTH_OFF, calls), allow_list={"192.168.1.20"}
)
self.assertEqual(allowed.prefill_cache, "off")

def test_probe_url_drops_userinfo(self):
calls = []
url = "http://user:s3cret@localhost:8081/v1"
health = local_llm.probe_gateway_health(url, fetch=_fetcher(HEALTH_OFF, calls))
self.assertEqual(calls, [("http://localhost:8081/health", 2.0)])
self.assertNotIn("s3cret", health.url)
self.assertEqual(local_llm.health_url("http://[::1]:8081/v1"), "http://[::1]:8081/health")

def test_redact_url_drops_userinfo_query_and_fragment(self):
# why: probe credentials are built at runtime rather than written as literals
sample = "pw-" + "x" * 8
url = f"http://someone:{sample}@gpu.example.com:8000/v1?key={sample}#{sample}"
self.assertEqual(local_llm.redact_url(url), "http://***@gpu.example.com:8000/v1")
self.assertEqual(local_llm.redact_url("http://localhost:11434/v1"), "http://localhost:11434/v1")
unparseable = f"http://someone:{sample}@[::1/v1?key={sample}"
self.assertNotIn(sample, local_llm.redact_url(unparseable))
with self.assertRaises(ValueError) as caught:
local_llm._default_fetch(f"file://someone:{sample}@localhost/etc", 1.0)
self.assertNotIn(sample, str(caught.exception))

def test_redact_url_drops_userinfo_with_unencoded_delimiters(self):
# why: urlsplit ends the authority at the first / ? or #, so the host after it cannot be trusted
sample = "pw-" + "x" * 8
head = "hd-" + "q" * 5
for sep in ("/", "?", "#"):
for prefix in ("http://", "//", ""):
url = f"{prefix}someone:{head}{sep}{sample}@gpu.example.com:8000/v1?key={sample}#{sample}"
with self.subTest(sep=sep, prefix=prefix):
redacted = local_llm.redact_url(url)
self.assertEqual(redacted, f"{prefix}***")
for fragment in (sample, head, "someone", "gpu.example.com"):
self.assertNotIn(fragment, redacted)
bracketed = f"http://someone:{head}/{sample}@[::1]:8081/v1"
self.assertEqual(local_llm.redact_url(bracketed), "http://***")
plain = f"http://someone:{head}{sample}@[::1]:8081/v1"
self.assertEqual(local_llm.redact_url(plain), "http://***@[::1]:8081/v1")

def test_redact_url_keeps_credential_free_urls_readable(self):
for url in (
"http://localhost:11434/v1",
"https://gpu.example.com:8443/api/v1/",
"http://[::1]:8081/v1",
"host.docker.internal:8000/v1",
):
with self.subTest(url=url):
self.assertEqual(local_llm.redact_url(url), url)
self.assertEqual(local_llm.redact_url("http://[::1/v1"), "http://***")
self.assertEqual(local_llm.redact_url("HTTP://Host.Example:80/a/b"), "HTTP://Host.Example:80/a/b")
self.assertEqual(local_llm.redact_url("http://localhost:8000/v1?key=k#f"), "http://localhost:8000/v1")
# why: withholding the host beats presenting a believable wrong one
other = "other" + ".example.net"
for url in (
"http://localhost:8000/v1/@scope/models",
"http://localhost:8000/v1?owner=a@",
f"http://gpu.lan:8000/v1?owner=ops@{other}",
f"http://gpu.lan:8000/v1#ops@{other}",
f"http://gpu.lan:8000/v1/ops@{other}/x",
):
with self.subTest(url=url):
self.assertEqual(local_llm.redact_url(url), "http://***")
self.assertEqual(local_llm.redact_url(f"//gpu.lan/v1?owner=ops@{other}"), "//***")
self.assertEqual(local_llm.redact_url(f"gpu.lan:8000/v1?owner=ops@{other}"), "***")

def test_redact_url_never_leaks_userinfo_over_probe_matrix(self):
# why: the strip up to the last @ is unconditional, so no host shape may gate it
head = "hd-" + "q" * 5
sample = "pw-" + "x" * 8
name = "some" + "one"
hosts = (
"gpu.example.com:8000/v1",
"[::1]:8081/v1",
"127.0.0.1:59999/v1",
"gpu.example.com:abc/v1",
"h\u00f4st.example/v1",
"[::1/v1",
"/v1",
"",
"gpu example.com/v1",
)
validated = {"gpu.example.com:8000/v1", "[::1]:8081/v1", "127.0.0.1:59999/v1"}
for sep in ("", "/", "?", "#", "@", ":", "%", "%2F"):
for userinfo in (f"{name}:{head}{sep}{sample}", f"{head}{sep}{sample}"):
for host in hosts:
for prefix in ("http://", "//", ""):
url = f"{prefix}{userinfo}@{host}?key={sample}#{sample}"
with self.subTest(url=url):
redacted = local_llm.redact_url(url)
ambiguous = any(c in userinfo for c in "/?#")
# why: #96 message rule: a host that does not validate is withheld
withheld = ambiguous or host not in validated
expected = f"{prefix}***" if withheld else f"{prefix}***@{host}"
self.assertEqual(redacted, expected)
for fragment in (head, sample, name):
self.assertNotIn(fragment, redacted)

def test_config_error_and_logs_never_echo_userinfo(self):
sample = "pw-" + "y" * 8
env = {
"HOLON_LOCAL_BASE_URL": f"http://someone:{sample}@gpu.example.com:8000/v1?key={sample}",
"HOLON_LOCAL_MODELS": "m",
}
with patch.dict(os.environ, env, clear=True), self.assertRaises(local_llm.LocalLLMConfigError) as caught:
local_llm.build_container_config(None)
self.assertNotIn(sample, str(caught.exception))
self.assertIn("(host gpu.example.com:8000)", str(caught.exception))
host_config = {"providers": {"p": {"baseUrl": f"http://someone:{sample}@localhost:8081/v1", "models": []}}}
with self.assertLogs(local_llm.logger, level="INFO") as logs:
local_llm.build_container_config(host_config)
local_llm.rewrite_authority(f"http://someone:{sample}@localhost:bad/v1")
self.assertTrue(logs.output)
self.assertFalse(any(sample in line for line in logs.output))

def test_only_http_and_https_are_probed(self):
calls = []
for url in ("file://localhost/etc", "ftp://127.0.0.1:21/x", "gopher://localhost:70/x"):
with self.subTest(url=url):
self.assertIsNone(local_llm.health_url(url))
self.assertIsNone(local_llm.probe_gateway_health(url, fetch=_fetcher(HEALTH_OFF, calls)))
self.assertEqual(calls, [])
self.assertEqual(local_llm.health_url("HTTPS://localhost:8443/v1"), "https://localhost:8443/health")
with self.assertRaises(ValueError):
local_llm._default_fetch("file:///etc/hosts", 1.0)

def test_default_fetch_caps_the_response_read(self):
size = local_llm.HEALTH_MAX_BYTES * 3

class Flood(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Length", str(size))
self.end_headers()
# why: the client hangs up at the cap, so the rest of the write may fail
with contextlib.suppress(OSError):
self.wfile.write(b"x" * size)

def log_message(self, *args):
pass

port = serve_on_loopback(self, Flood)
with self.assertRaises(ValueError):
local_llm._default_fetch(f"http://127.0.0.1:{port}/health", 2.0)
health = local_llm.probe_gateway_health(f"http://127.0.0.1:{port}/v1")
self.assertEqual(health.prefill_cache, "unknown")
self.assertIn("exceeds", health.error)

def test_default_fetch_refuses_redirects(self):
class Redirector(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(302)
self.send_header("Location", "http://198.51.100.7/health")
self.end_headers()

def log_message(self, *args):
pass

port = serve_on_loopback(self, Redirector)
health = local_llm.probe_gateway_health(f"http://127.0.0.1:{port}/v1")
self.assertEqual(health.prefill_cache, "unknown")
self.assertIn("redirect refused", health.error)

def test_max_prompt_tokens_parsed_from_defaults_or_top_level(self):
nested = {"effective_defaults": {"max_output_tokens": 16384, "max_prompt_tokens": 262144}}
self.assertEqual(local_llm.parse_gateway_health("u", nested).max_prompt_tokens, 262144)
top = {"effective_defaults": {"max_output_tokens": 16384}, "max_prompt_tokens": 32768}
self.assertEqual(local_llm.parse_gateway_health("u", top).max_prompt_tokens, 32768)
self.assertIsNone(local_llm.parse_gateway_health("u", HEALTH_OFF).max_prompt_tokens)
Loading
Loading