Handle busy ports and stop orphaning mlx_lm.server

On a Mac with port 8000 already taken, the proxy failed to bind after
mlx_lm.server had started, leaving an orphan each time launchd retried.
- setup now stops our own services, then moves the API/dashboard to the
  next free ports (or errors if a port was given explicitly)
- the MLX service binds its port before starting mlx_lm.server, always
  stops the child on exit, and cleans up leftovers from earlier crashes
- drop the nonexistent huggingface_hub[cli] extra

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
This commit is contained in:
neil 2026-11-02 04:45:36 -08:00
parent d2ab08a5f5
commit 16f096714e
2 changed files with 100 additions and 12 deletions

View file

@ -32,7 +32,7 @@ def install(hw, log=print):
subprocess.run([u, "venv", "--managed-python", "--python", "3.12", str(VENV)], check=True)
spec = os.environ.get("LLMHOST_MLX_SPEC", "mlx-lm")
log(f"$ uv pip install {spec}")
subprocess.run([u, "pip", "install", "--python", str(PY), spec, "huggingface_hub[cli]"], check=True)
subprocess.run([u, "pip", "install", "--python", str(PY), spec, "huggingface_hub"], check=True)
return {}
@ -174,10 +174,39 @@ def make_handler(inner_port, served_name, context, key, stats):
return Proxy
def _kill_stale_servers(inner_port):
"""Stop mlx_lm.server processes left behind by an earlier crash of this service.
Only processes running from our own venv are touched."""
out = subprocess.run(["lsof", "-nP", f"-iTCP:{inner_port}", "-sTCP:LISTEN", "-t"],
capture_output=True, text=True).stdout.split()
for pid in out:
cmd = subprocess.run(["ps", "-o", "command=", "-p", pid], capture_output=True, text=True).stdout
if str(VENV) in cmd and "mlx_lm" in cmd:
print(f"llm-host: stopping leftover mlx_lm.server (pid {pid}) on port {inner_port}", flush=True)
try:
os.kill(int(pid), signal.SIGTERM)
except OSError:
pass
if out:
time.sleep(2)
def run_server(cfg, entry, choice, args):
"""Start mlx_lm.server as a child on api_port+1 and the auth proxy on api_port."""
"""Start the auth proxy on api_port, then mlx_lm.server as a child on api_port+1."""
port = cfg["api_port"]
inner = port + 1
# Claim the public port first: if it's taken, fail before starting (and orphaning) a child.
stats = Stats()
try:
srv = ThreadingHTTPServer(("0.0.0.0", port),
make_handler(inner, entry["name"], choice.get("est_context", entry["context"]),
paths.api_key(), stats))
except OSError as e:
print(f"llm-host: can't listen on port {port} ({e.strerror}). Another program is using it; "
f"pick a free port with: llmhost setup --api-port <port>", flush=True)
sys.exit(1)
_kill_stale_servers(inner)
exe = str(VENV / "bin/mlx_lm.server")
child = subprocess.Popen([exe, *args])
@ -191,13 +220,13 @@ def run_server(cfg, entry, choice, args):
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
stats = Stats()
srv = ThreadingHTTPServer(("0.0.0.0", port),
make_handler(inner, entry["name"], choice.get("est_context", entry["context"]),
paths.api_key(), stats))
threading.Thread(target=srv.serve_forever, daemon=True).start()
print(f"llm-host: proxy on :{port} -> mlx_lm.server on 127.0.0.1:{inner}", flush=True)
rc = child.wait()
print(f"llm-host: mlx_lm.server exited with {rc}", flush=True)
try:
threading.Thread(target=srv.serve_forever, daemon=True).start()
print(f"llm-host: proxy on :{port} -> mlx_lm.server on 127.0.0.1:{inner}", flush=True)
rc = child.wait()
print(f"llm-host: mlx_lm.server exited with {rc}", flush=True)
finally:
if child.poll() is None:
child.terminate()
time.sleep(1)
os._exit(rc or 1)