Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(cli): say why the proxy failed to start (#4120)

Tejas Chopraf3d240bcae5f
diff --git a/headroom/cli/port_discovery.py b/headroom/cli/port_discovery.py
index 3b1b7f98a..ae4f9e0e0 100644
--- a/headroom/cli/port_discovery.py
+++ b/headroom/cli/port_discovery.py
@@ -120,16 +120,19 @@ def candidate_ports(
return seen[:_MAX_CANDIDATES]
-def probe_headroom_proxy(port: int, timeout: float = _PROBE_TIMEOUT_SECONDS) -> bool:
- """True when a Headroom proxy answers ``/livez`` on loopback ``port``.
+def probe_headroom_proxy(
+ port: int, timeout: float = _PROBE_TIMEOUT_SECONDS, *, host: str = "127.0.0.1"
+) -> bool:
+ """True when a Headroom proxy answers ``/livez`` on ``host:port`` (loopback by default).
Requires the ``service: headroom-proxy`` identity (or the legacy
``alive``+``version`` shape) so an unrelated local server on the port is
- never mistaken for Headroom.
+ never mistaken for Headroom. ``host`` is a numeric IPv4 or IPv6 address.
"""
from headroom.install.health import probe_json
- return is_headroom_livez(probe_json(f"http://127.0.0.1:{port}/livez", timeout=timeout))
+ netloc = f"[{host}]" if ":" in host else host
+ return is_headroom_livez(probe_json(f"http://{netloc}:{port}/livez", timeout=timeout))
def is_headroom_livez(payload: Mapping[str, Any] | None) -> bool:
diff --git a/headroom/cli/proxy.py b/headroom/cli/proxy.py
index 918397577..6ae7848be 100644
--- a/headroom/cli/proxy.py
+++ b/headroom/cli/proxy.py
@@ -1,8 +1,11 @@
"""Proxy server CLI commands."""
+import errno
+import ipaddress
import logging
import os
import platform
+import socket
import sys
import warnings
from importlib.util import find_spec
@@ -195,6 +198,99 @@ def _get_env_int(name: str, default: int) -> int:
return default if value is None else value
+def _tcp_port_in_use(host: str, port: int, *, workers: int) -> tuple[OSError, Any] | None:
+ """Return ``(EADDRINUSE error, busy address)`` uvicorn would hit binding ``host:port``.
+
+ Returns None when the bind would succeed.
+
+ Mirrors uvicorn's own bind so the probe never refuses a bind uvicorn would
+ accept: ``SO_REUSEADDR`` (both uvicorn paths set it on POSIX, so a port in
+ TIME_WAIT after a restart is not "in use"); a single process binds every
+ address ``host`` resolves to (asyncio ``create_server``), while
+ ``--workers > 1`` binds one AF_INET/AF_INET6 socket in the parent.
+ Windows ``SO_REUSEADDR`` semantics differ, so Windows is left to uvicorn,
+ as is any error other than EADDRINUSE (unresolvable host, address not on
+ this machine); uvicorn reports those as before.
+ """
+ if sys.platform == "win32":
+ return None
+ if workers > 1:
+ family = socket.AF_INET6 if ":" in host else socket.AF_INET
+ targets: list[tuple[Any, Any]] = [(family, (host, port))]
+ else:
+ try:
+ infos = socket.getaddrinfo(
+ host or None, port, type=socket.SOCK_STREAM, flags=socket.AI_PASSIVE
+ )
+ except (OSError, UnicodeError):
+ return None
+ targets = [(info[0], info[4]) for info in infos]
+ for family, address in targets:
+ try:
+ with socket.socket(family, socket.SOCK_STREAM) as probe:
+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ if family == socket.AF_INET6 and workers <= 1:
+ # asyncio binds v4 and v6 separately; match it.
+ probe.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
+ probe.bind(address)
+ except OSError as exc:
+ if exc.errno == errno.EADDRINUSE:
+ return exc, address
+ return None
+
+
+_WILDCARD_PROBE_HOSTS = {"": "127.0.0.1", "0.0.0.0": "127.0.0.1", "::": "::1"}
+
+
+def _probe_host_for(address: Any) -> str | None:
+ """The numeric address to ask "is this Headroom?", or None when it can't be targeted.
+
+ A wildcard bind is reached through loopback of the same family. A
+ hostname (the ``--workers > 1`` path binds it unresolved) is resolved for
+ IPv4. A scoped IPv6 address cannot go in a probe URL.
+ """
+ host = str(address[0])
+ if host in _WILDCARD_PROBE_HOSTS:
+ return _WILDCARD_PROBE_HOSTS[host]
+ if "%" in host:
+ return None
+ try:
+ ipaddress.ip_address(host)
+ except ValueError:
+ try:
+ infos = socket.getaddrinfo(host, None, socket.AF_INET, socket.SOCK_STREAM)
+ except (OSError, UnicodeError):
+ return None
+ return str(infos[0][4][0]) if infos else None
+ return host
+
+
+def _refuse_busy_port(host: str, port: int, *, workers: int) -> None:
+ """Fail before the banner when ``host:port`` is already taken.
+
+ Without this the banner prints "Press Ctrl+C to stop", then uvicorn's bind
+ error is buried among startup and shutdown log lines.
+ """
+ busy = _tcp_port_in_use(host, port, workers=workers)
+ if busy is None:
+ return
+ error, address = busy
+ from headroom.cli.port_discovery import probe_headroom_proxy
+
+ reason = error.strerror or str(error)
+ probe_host = _probe_host_for(address)
+ if probe_host is None:
+ holder = f"({reason})"
+ elif probe_headroom_proxy(port, host=probe_host):
+ holder = "by a running Headroom proxy (reuse it, or stop it first)"
+ else:
+ holder = f"by another process ({reason})"
+ raise click.ClickException(
+ f"Port {port} on {host} is already in use {holder}. "
+ "Start this proxy on another port with --port N (env: HEADROOM_PORT)."
+ )
+
+
@main.command()
@click.option(
"--port",
@@ -1685,6 +1781,8 @@ Memory (Multi-Provider):
_bind = evaluate_bind_policy(config.host, config.proxy_token)
if _bind.refused:
raise click.ClickException(_bind.message())
+ if not config.uds:
+ _refuse_busy_port(config.host, config.port, workers=workers)
_auth_on = _bind.token_configured
_open_bind_note = (
f" · WARNING open bind, /v1/* UNAUTHENTICATED (acknowledged via {OPEN_BIND_ACK_ENV}=1)"
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index 3edf9703e..abf824b72 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -695,6 +695,57 @@ def _get_proxy_stdio_log_path(port: int | None = None) -> Path:
return _get_log_path(port).with_name(_paths.proxy_stdio_log_path(port).name)
+# A proxy that dies during startup logs its shutdown summary after the error,
+# so the end of the log is the summary box, not the cause. Quote from the first
+# error-looking line instead.
+# Click's own failures (``click.ClickException``) print ``Error: ...`` at the
+# start of a line.
+_PROXY_STARTUP_ERROR_RE = re.compile(
+ r"\b(?:ERROR|CRITICAL)\b|Traceback \(most recent call last\)|^Error: ", re.MULTILINE
+)
+_PROXY_STARTUP_EXCERPT_CHARS = 500
+# Never read a runaway log whole: look at most at the first and the last 64 KiB
+# of this run's output. The error usually comes early, before the shutdown
+# summary; the tail catches one that follows a long burst of startup output.
+_PROXY_STARTUP_READ_BYTES = 64 * 1024
+
+
+def _proxy_startup_failure_excerpt(stdio_log_path: Path, start: int) -> str:
+ """Return the part of this run's stdio log that best explains a startup exit.
+
+ Reads only what was written after byte offset ``start`` (the log is shared
+ across runs): the first ``_PROXY_STARTUP_READ_BYTES`` of it and, when the run
+ wrote more and the head has no error, the last ``_PROXY_STARTUP_READ_BYTES``.
+ Prefers the first ERROR/CRITICAL/Traceback/``Error:`` line onwards, and falls
+ back to the last few hundred characters of the first non-blank window.
+ """
+ try:
+ with open(stdio_log_path, "rb") as fh:
+ fh.seek(start)
+ windows = [fh.read(_PROXY_STARTUP_READ_BYTES)]
+ end = fh.seek(0, os.SEEK_END)
+ tail_start = max(start + _PROXY_STARTUP_READ_BYTES, end - _PROXY_STARTUP_READ_BYTES)
+ if end > tail_start and not _PROXY_STARTUP_ERROR_RE.search(
+ windows[0].decode("utf-8", errors="replace")
+ ):
+ fh.seek(tail_start)
+ windows.append(fh.read(_PROXY_STARTUP_READ_BYTES))
+ except OSError:
+ return "(no log output)"
+ texts = [raw.decode("utf-8", errors="replace").strip() for raw in windows]
+ for output in texts:
+ match = _PROXY_STARTUP_ERROR_RE.search(output)
+ if match is not None:
+ line_start = output.rfind("\n", 0, match.start()) + 1
+ return output[line_start : line_start + _PROXY_STARTUP_EXCERPT_CHARS]
+ # No recognised error: quote the end of the first non-blank window, the head
+ # when it has text (the startup output), otherwise the tail.
+ for output in texts:
+ if output:
+ return output[-_PROXY_STARTUP_EXCERPT_CHARS:]
+ return "(no log output)"
+
+
def _start_proxy(
port: int,
*,
@@ -776,6 +827,12 @@ def _start_proxy(
timeout_seconds = _resolve_wrap_proxy_timeout_seconds()
log_path = _get_log_path(port)
stdio_log_path = _get_proxy_stdio_log_path(port)
+ # The stdio log is appended to across runs; remember where this run starts
+ # so a startup failure quotes this run's output, not an earlier one.
+ try:
+ stdio_log_start = stdio_log_path.stat().st_size
+ except OSError:
+ stdio_log_start = 0
stdio_log_file = open(stdio_log_path, "a", encoding="utf-8") # noqa: SIM115
# Ensure proxy subprocess uses UTF-8 (Windows defaults to cp1252)
@@ -896,17 +953,17 @@ def _start_proxy(
return proc
# Check if process died
if proc.poll() is not None:
- # Read last few lines of log for error context
- try:
- tail = _read_text(stdio_log_path)[-500:]
- except Exception:
- tail = "(no log output)"
- raise RuntimeError(f"Proxy exited with code {proc.returncode}: {tail}")
+ excerpt = _proxy_startup_failure_excerpt(stdio_log_path, stdio_log_start)
+ raise RuntimeError(
+ f"Proxy exited with code {proc.returncode}: {excerpt}\n"
+ f" Full log: {stdio_log_path}"
+ )
proc.kill()
raise RuntimeError(
f"Proxy failed to start on port {port} within {timeout_seconds} seconds. "
- f"Set {_WRAP_PROXY_TIMEOUT_ENV} to a larger number of seconds for slow startup."
+ f"Set {_WRAP_PROXY_TIMEOUT_ENV} to a larger number of seconds for slow startup.\n"
+ f" Full log: {stdio_log_path}"
)
finally:
stdio_log_file.close()
diff --git a/pyproject.toml b/pyproject.toml
index 92679bf00..e36a646ad 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -534,6 +534,7 @@ markers = [
"real_llm: tests that hit real LLM APIs; skipped unless explicitly enabled",
"live: opt-in multi-turn tests that hit real upstream APIs; require provider keys",
"proxy_dependency_gate: exercises ensure_proxy_dependencies() without mocking",
+ "proxy_port_preflight: exercises the proxy busy-port check against real sockets",
"windows_newline: newline-contract tests (#3698); also run on windows-latest in CI",
]
diff --git a/tests/conftest.py b/tests/conftest.py
index cf09e399d..23d46bc65 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -63,6 +63,22 @@ def _skip_proxy_dependency_gate_unless_exercised(
monkeypatch.setattr(proxy, "ensure_proxy_dependencies", lambda: None)
+# `headroom proxy` refuses to start when its port is already bound. Tests that
+# invoke it with a stubbed run_server use the default 8787, which a developer's
+# own running proxy holds, so the check is off unless a test exercises it.
[email protected](autouse=True)
+def _skip_proxy_port_preflight_unless_exercised(
+ request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ if request.node.get_closest_marker("proxy_port_preflight") is not None:
+ return
+ try:
+ from headroom.cli import proxy
+ except ModuleNotFoundError:
+ return
+ monkeypatch.setattr(proxy, "_refuse_busy_port", lambda *args, **kwargs: None)
+
+
@pytest.fixture(autouse=True)
def _scrub_developer_headroom_env(monkeypatch, tmp_path):
for key in list(os.environ):
diff --git a/tests/test_cli/test_proxy_port_preflight.py b/tests/test_cli/test_proxy_port_preflight.py
new file mode 100644
index 000000000..74626df0a
--- /dev/null
+++ b/tests/test_cli/test_proxy_port_preflight.py
@@ -0,0 +1,145 @@
+"""`headroom proxy` refuses a busy port before printing its banner.
+
+Without the check the banner ends "Press Ctrl+C to stop", then uvicorn's bind
+error is buried among startup and shutdown log lines.
+"""
+
+from __future__ import annotations
+
+import json
+import socket
+import sys
+import threading
+from collections.abc import Iterator
+from contextlib import contextmanager
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from unittest.mock import patch
+
+import pytest
+from click.testing import CliRunner
+
+from headroom.cli.main import main
+
+pytestmark = [
+ pytest.mark.proxy_port_preflight,
+ pytest.mark.skipif(sys.platform == "win32", reason="the check is POSIX-only"),
+]
+
+
+@contextmanager
+def _listening(host: str = "127.0.0.1") -> Iterator[int]:
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.bind((host, 0))
+ sock.listen(1)
+ try:
+ yield sock.getsockname()[1]
+ finally:
+ sock.close()
+
+
+def _free_port() -> int:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.bind(("127.0.0.1", 0))
+ return sock.getsockname()[1]
+
+
+def _invoke_proxy(*args: str) -> tuple[object, list[object]]:
+ calls: list[object] = []
+ with (
+ patch("headroom.proxy.server.run_server", lambda config, **kw: calls.append(config)),
+ patch("headroom.cli.port_discovery.probe_headroom_proxy", return_value=False),
+ ):
+ result = CliRunner().invoke(main, ["proxy", *args])
+ return result, calls
+
+
[email protected]("workers", ["1", "2"])
+def test_busy_port_fails_before_banner_with_actionable_message(workers: str) -> None:
+ with _listening() as port:
+ result, calls = _invoke_proxy("--port", str(port), "--workers", workers)
+
+ assert result.exit_code == 1, result.output
+ assert f"Port {port} on 127.0.0.1 is already in use by another process" in result.output
+ assert "--port N" in result.output
+ assert "HEADROOM PROXY" not in result.output
+ assert calls == []
+
+
+def test_busy_port_held_by_headroom_says_so() -> None:
+ with _listening() as port:
+ with (
+ patch("headroom.proxy.server.run_server", lambda config, **kw: None),
+ patch("headroom.cli.port_discovery.probe_headroom_proxy", return_value=True),
+ ):
+ result = CliRunner().invoke(main, ["proxy", "--port", str(port)])
+
+ assert result.exit_code == 1, result.output
+ assert "already in use by a running Headroom proxy" in result.output
+
+
+def test_free_port_starts_normally() -> None:
+ port = _free_port()
+ result, calls = _invoke_proxy("--port", str(port))
+
+ assert result.exit_code == 0, result.output
+ assert "HEADROOM PROXY" in result.output
+ assert len(calls) == 1
+
+
+def _ipv6_loopback_available() -> bool:
+ try:
+ with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
+ sock.bind(("::1", 0))
+ except OSError:
+ return False
+ return True
+
+
+class _HeadroomLivez(BaseHTTPRequestHandler):
+ def do_GET(self) -> None: # noqa: N802 - http.server API
+ body = json.dumps({"service": "headroom-proxy", "alive": True}).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+
[email protected](not _ipv6_loopback_available(), reason="needs IPv6 loopback")
+def test_ipv6_conflict_is_identified_on_the_requested_host() -> None:
+ """A Headroom proxy on 127.0.0.1:P must not be reported as the owner of [::1]:P."""
+ headroom_v4 = HTTPServer(("127.0.0.1", 0), _HeadroomLivez)
+ port = headroom_v4.server_address[1]
+ threading.Thread(target=headroom_v4.serve_forever, daemon=True).start()
+ other_v6 = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
+ try:
+ other_v6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
+ other_v6.bind(("::1", port))
+ other_v6.listen(1)
+ with patch("headroom.proxy.server.run_server", lambda config, **kw: None):
+ v6 = CliRunner().invoke(main, ["proxy", "--host", "::1", "--port", str(port)])
+ finally:
+ other_v6.close()
+ headroom_v4.shutdown()
+ headroom_v4.server_close()
+
+ assert v6.exit_code == 1, v6.output
+ assert f"Port {port} on ::1 is already in use by another process" in v6.output
+ assert "Headroom proxy" not in v6.output
+
+
+def test_unprobeable_host_gets_the_generic_message() -> None:
+ with _listening() as port:
+ with (
+ patch("headroom.proxy.server.run_server", lambda config, **kw: None),
+ patch("headroom.cli.proxy._probe_host_for", return_value=None),
+ patch("headroom.cli.port_discovery.probe_headroom_proxy", return_value=True),
+ ):
+ result = CliRunner().invoke(main, ["proxy", "--port", str(port)])
+
+ assert result.exit_code == 1, result.output
+ assert f"Port {port} on 127.0.0.1 is already in use (" in result.output
+ assert "Headroom proxy" not in result.output
diff --git a/tests/test_cli_proxy_env.py b/tests/test_cli_proxy_env.py
index c0d50e86d..ec0754290 100644
--- a/tests/test_cli_proxy_env.py
+++ b/tests/test_cli_proxy_env.py
@@ -203,10 +203,15 @@ class TestCLIWrapProxyTimeout:
monkeypatch.setattr(wrap_mod, "_get_log_path", lambda port=None: tmp_path / "proxy.log")
monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: False)
monkeypatch.setattr(wrap_mod.time, "sleep", lambda _seconds: None)
- monkeypatch.setattr(wrap_mod.subprocess, "Popen", lambda *args, **kwargs: fake_proc)
+
+ def popen_writing_stdio(*args, **kwargs):
+ kwargs["stdout"].write("proxy stdio startup output\n")
+ kwargs["stdout"].flush()
+ return fake_proc
+
+ monkeypatch.setattr(wrap_mod.subprocess, "Popen", popen_writing_stdio)
(tmp_path / "proxy.log").write_text("canonical runtime log output")
- (tmp_path / "proxy-stdio-8787.log").write_text("proxy stdio startup output")
with pytest.raises(RuntimeError) as excinfo:
wrap_mod._start_proxy(8787, agent_type="codex")
@@ -216,6 +221,137 @@ class TestCLIWrapProxyTimeout:
assert "proxy stdio startup output" in message
assert "canonical runtime log output" not in message
+ def test_start_proxy_exit_quotes_this_runs_error_not_summary_or_old_runs(
+ self, monkeypatch, tmp_path
+ ):
+ """The startup error names the cause and the log path.
+
+ The proxy logs its shutdown summary after the error, and the stdio log
+ is appended across runs, so the old ``[-500:]`` tail quoted the summary
+ box (or an earlier run) and never said where the full log was.
+ """
+ fake_proc = _FakeProxyProcess()
+ fake_proc.returncode = 1
+ fake_proc.poll = lambda: fake_proc.returncode
+
+ monkeypatch.setenv(wrap_mod._WRAP_PROXY_TIMEOUT_ENV, "2")
+ monkeypatch.setattr(wrap_mod, "_get_log_path", lambda port=None: tmp_path / "proxy.log")
+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: False)
+ monkeypatch.setattr(wrap_mod.time, "sleep", lambda _seconds: None)
+
+ stdio_log = tmp_path / "proxy-stdio-8787.log"
+ stdio_log.write_text("ERROR: stale failure from an earlier run\n")
+ summary = "".join(
+ f"2026-10-09 16:19:23,665 - headroom.proxy - INFO - Summary line {i}: 0\n"
+ for i in range(20)
+ )
+
+ def popen_failing_to_bind(*args, **kwargs):
+ kwargs["stdout"].write(
+ "2026-10-09 16:19:23,659 - headroom.proxy - INFO - Local telemetry: DISABLED\n"
+ "ERROR: [Errno 48] error while attempting to bind on address "
+ "('127.0.0.1', 8787): address already in use\n" + summary
+ )
+ kwargs["stdout"].flush()
+ return fake_proc
+
+ monkeypatch.setattr(wrap_mod.subprocess, "Popen", popen_failing_to_bind)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ wrap_mod._start_proxy(8787, agent_type="codex")
+
+ message = str(excinfo.value)
+ assert "Proxy exited with code 1" in message
+ assert "[Errno 48] error while attempting to bind" in message
+ assert "stale failure from an earlier run" not in message
+ assert "Local telemetry" not in message
+ assert f"Full log: {stdio_log}" in message
+
+ def test_startup_excerpt_reads_at_most_64_kib_of_this_run(self, monkeypatch, tmp_path):
+ """A runaway stdio log is never read whole: this run's first and last 64 KiB
+ at most, so an error after a long burst of output is still quoted."""
+ stdio_log = tmp_path / "proxy-stdio-8787.log"
+ earlier = "ERROR: an earlier run\n" * 1000
+ noise = "INFO noise line\n" * 16000 # ~256 KiB, no error line
+ late = "ERROR: late startup failure\n"
+ # Bytes, not text: the offset is a byte offset, and write_text would turn
+ # "\n" into "\r\n" on Windows.
+ stdio_log.write_bytes((earlier + noise + late + "INFO shutdown summary\n").encode())
+ read_sizes: list[int] = []
+ real_open = open
+
+ def tracking_open(*args, **kwargs):
+ handle = real_open(*args, **kwargs)
+ real_read = handle.read
+
+ def read(size=-1):
+ data = real_read(size)
+ read_sizes.append(len(data))
+ return data
+
+ handle.read = read
+ return handle
+
+ monkeypatch.setattr(wrap_mod, "open", tracking_open, raising=False)
+
+ excerpt = wrap_mod._proxy_startup_failure_excerpt(stdio_log, len(earlier.encode()))
+
+ assert "earlier run" not in excerpt
+ assert excerpt.startswith("ERROR: late startup failure")
+ assert sum(read_sizes) <= 2 * wrap_mod._PROXY_STARTUP_READ_BYTES
+
+ def test_startup_excerpt_prefers_an_error_in_the_first_64_kib(self, tmp_path):
+ stdio_log = tmp_path / "proxy-stdio-8787.log"
+ noise = "INFO noise line\n" * 16000
+ stdio_log.write_bytes(("ERROR: early failure\n" + noise + "ERROR: later echo\n").encode())
+
+ excerpt = wrap_mod._proxy_startup_failure_excerpt(stdio_log, 0)
+
+ assert excerpt.startswith("ERROR: early failure")
+
+ def test_startup_excerpt_without_error_quotes_the_end_of_the_head(self, tmp_path):
+ """No recognised error line: quote the end of this run's first 64 KiB,
+ even when the tail window is blank."""
+ stdio_log = tmp_path / "proxy-stdio-8787.log"
+ head = "INFO noise line\n" * 3000 + "INFO last startup line\n" # < 64 KiB
+ stdio_log.write_bytes((head + " \n" * 70000).encode())
+
+ excerpt = wrap_mod._proxy_startup_failure_excerpt(stdio_log, 0)
+
+ assert excerpt.endswith("INFO last startup line")
+
+ def test_startup_excerpt_falls_back_to_a_useful_tail_after_a_blank_head(self, tmp_path):
+ """A whitespace-only head must not hide a useful tail line."""
+ stdio_log = tmp_path / "proxy-stdio-8787.log"
+ stdio_log.write_bytes(b" " * (192 * 1024) + b"initialization could not bind the port\n")
+
+ excerpt = wrap_mod._proxy_startup_failure_excerpt(stdio_log, 0)
+
+ assert excerpt == "initialization could not bind the port"
+
+ def test_startup_excerpt_quotes_click_error_before_a_blank_tail(self, tmp_path):
+ """A Click ``Error:`` line followed by a whitespace-only tail is quoted,
+ not reported as "(no log output)"."""
+ stdio_log = tmp_path / "proxy-stdio-8787.log"
+ stdio_log.write_bytes(("Error: address already in use\n" + " " * (192 * 1024)).encode())
+
+ excerpt = wrap_mod._proxy_startup_failure_excerpt(stdio_log, 0)
+
+ assert excerpt == "Error: address already in use"
+
+ def test_startup_excerpt_starts_at_a_click_style_error_line(self, tmp_path):
+ stdio_log = tmp_path / "proxy-stdio-8787.log"
+ stdio_log.write_bytes(
+ b"INFO starting\nINFO loading config\n"
+ b"Error: Port 8787 on 127.0.0.1 is already in use by another process.\n"
+ b"INFO shutdown summary\n"
+ )
+
+ excerpt = wrap_mod._proxy_startup_failure_excerpt(stdio_log, 0)
+
+ assert excerpt.startswith("Error: Port 8787 on 127.0.0.1 is already in use")
+ assert "INFO starting" not in excerpt
+
def test_timeout_error_names_configured_timeout_and_env_var(self, monkeypatch, tmp_path):
fake_proc = _FakeProxyProcess()
@@ -231,6 +367,7 @@ class TestCLIWrapProxyTimeout:
message = str(excinfo.value)
assert "within 2 seconds" in message
assert wrap_mod._WRAP_PROXY_TIMEOUT_ENV in message
+ assert f"Full log: {tmp_path / 'proxy-stdio-8787.log'}" in message
assert fake_proc.killed is True