Skip to content
Merged
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
19 changes: 13 additions & 6 deletions python/src/mlxcel/_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,22 +220,29 @@ def __init__(
)
self.uds_path = path

@property
def _http_origin(self) -> str:
"""HTTP origin, bracketing IPv6 literals without altering the bind host."""
if self.uds_path is not None:
return "http://mlxcel"
assert self.host is not None and self.port is not None
host = self.host
if ":" in host and not host.startswith("["):
host = f"[{host}]"
return f"http://{host}:{self.port}"

@property
def base_url(self) -> str:
"""OpenAI base URL (with the ``/v1`` suffix) for this transport.

For a Unix socket the host portion is a placeholder; the actual routing
happens through the httpx ``uds`` transport.
"""
if self.uds_path is not None:
return "http://mlxcel/v1"
return f"http://{self.host}:{self.port}/v1"
return f"{self._http_origin}/v1"

@property
def _health_url(self) -> str:
if self.uds_path is not None:
return "http://mlxcel/health"
return f"http://{self.host}:{self.port}/health"
return f"{self._http_origin}/health"

def _build_command(self) -> List[str]:
"""Build the ``mlxcel serve`` argv.
Expand Down
10 changes: 9 additions & 1 deletion python/tests/fake_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import argparse
import json
import os
import socket
import sys
import time
from http.server import BaseHTTPRequestHandler
Expand Down Expand Up @@ -202,6 +203,10 @@ class ThreadingTCPServer(ThreadingMixIn, TCPServer):
allow_reuse_address = True


class ThreadingIPv6Server(ThreadingTCPServer):
address_family = socket.AF_INET6


def main() -> None:
global READY_AFTER, MODEL_ID

Expand Down Expand Up @@ -250,8 +255,11 @@ def main() -> None:
sys.stderr.write(f"Starting mlxcel server on unix:{uds}\n")
else:
host = args.host or "127.0.0.1"
if host.startswith("[") and host.endswith("]"):
host = host[1:-1]
port = args.port or 8080
server = ThreadingTCPServer((host, port), Handler)
server_type = ThreadingIPv6Server if ":" in host else ThreadingTCPServer
server = server_type((host, port), Handler)
sys.stderr.write(f"Starting mlxcel server on {host}:{port}\n")
sys.stderr.flush()

Expand Down
67 changes: 67 additions & 0 deletions python/tests/test_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import asyncio
import logging
import os
import socket
import stat
import sys
import tempfile
Expand Down Expand Up @@ -104,6 +105,72 @@ def test_managed_tcp_lifecycle(fake_binary: str) -> None:
assert server._proc is not None and server._proc.poll() is not None


@pytest.mark.parametrize(
"host", ["127.0.0.1", "localhost", "::1", "[::1]", "2001:db8::1", "[2001:db8::1]"]
)
def test_managed_tcp_urls_preserve_host_and_port(host: str) -> None:
server = ManagedServer("fake/model", binary=sys.executable, host=host, port=18080)
try:
for raw_url, path in [(server.base_url, "/v1"), (server._health_url, "/health")]:
url = httpx.URL(raw_url)
assert url.host == host.strip("[]")
assert url.port == 18080
assert url.path == path
# URL brackets must not change the address passed to the server CLI.
command = server._build_command()
assert command[command.index("--host") + 1] == host
finally:
server.close()


@pytest.fixture()
def ipv6_port() -> int:
if not socket.has_ipv6:
pytest.skip("IPv6 unavailable")
try:
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as probe:
probe.bind(("::1", 0))
return int(probe.getsockname()[1])
except OSError as exc:
pytest.skip(f"IPv6 loopback unavailable: {exc}")


@pytest.mark.parametrize("host", ["::1", "[::1]"])
def test_managed_ipv6_client(
fake_binary: str, ipv6_port: int, host: str, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("NO_PROXY", "*")
with mlxcel.LLM(
"fake/model", binary=fake_binary, host=host, port=ipv6_port, startup_timeout=10.0
) as client:
assert client.model == "fake-model"
assert client.generate("hi") == "hello world"
assert client._server is not None
proc = client._server._proc
assert proc is not None and proc.poll() is None
assert proc.poll() is not None


@pytest.mark.parametrize("host", ["::1", "[::1]"])
def test_async_managed_ipv6_client(
fake_binary: str, ipv6_port: int, host: str, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("NO_PROXY", "*")

async def go() -> None:
async with mlxcel.AsyncLLM(
"fake/model", binary=fake_binary, host=host, port=ipv6_port, startup_timeout=10.0
) as client:
assert await client.generate("hi") == "hello world"
assert client.model == "fake-model"
assert client._server is not None
proc = client._server._proc
assert proc is not None and proc.poll() is None
assert proc.poll() is not None

asyncio.run(go())


def test_early_exit_raises_with_stderr(fake_binary: str, tmp_path: Path) -> None:
sock = _short_socket(tmp_path)
server = ManagedServer(
Expand Down
Loading