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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix: honor configured port in container startup and healthcheck (#2436)
natori1b7977cecd95
diff --git a/Dockerfile b/Dockerfileindex f38f0cd7c..fe7f4e3e6 100644--- a/Dockerfile+++ b/Dockerfile@@ -198,11 +198,15 @@ VOLUME ${RUNTIME_HOME}/.headroomEXPOSE 8787+# Shell form so ${HEADROOM_PORT} expands at probe time: `headroom deploy+# --port N` sets it in the container env, and an exec-form CMD would keep+# probing 8787 and report a working deployment as unhealthy (issue #2432).HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \- CMD ["curl", "--fail", "--silent", "http://127.0.0.1:8787/readyz"]+ CMD curl --fail --silent "http://127.0.0.1:${HEADROOM_PORT:-8787}/readyz"ENTRYPOINT ["headroom", "proxy"]-CMD ["--port", "8787"]+# Keep host and port defaults in the CLI so HEADROOM_HOST and HEADROOM_PORT+# remain authoritative for the published image.FROM ${DISTROLESS_IMAGE} AS runtime-slim@@ -223,11 +227,16 @@ ENV HEADROOM_HOST=127.0.0.1 \EXPOSE 8787+# This stage is distroless, so there is no shell to expand ${HEADROOM_PORT}.+# Resolve the port inside Python instead, keeping exec form (issue #2432).+# `or` rather than a get() default so an empty HEADROOM_PORT falls back the+# same way `${HEADROOM_PORT:-8787}` does in the shell-form stage above.HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \- CMD ["python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8787/readyz', timeout=5)"]+ CMD ["python3", "-c", "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:' + (os.environ.get('HEADROOM_PORT') or '8787') + '/readyz', timeout=5)"]ENTRYPOINT ["python3", "-m", "headroom.cli", "proxy"]-CMD ["--port", "8787"]+# Keep host and port defaults in the CLI so HEADROOM_HOST and HEADROOM_PORT+# remain authoritative for the published image.# Default published image remains python-slim runtimeFROM runtime-slim-base AS runtimediff --git a/headroom/cli/doctor.py b/headroom/cli/doctor.pyindex 3a7f6f667..b1cfae50a 100644--- a/headroom/cli/doctor.py+++ b/headroom/cli/doctor.py@@ -25,6 +25,7 @@ import clickfrom headroom._version import format_version_label, normalize_release_versionfrom headroom.install.health import probe_json+from headroom.install.models import DeploymentManifestfrom headroom.install.paths import (claude_settings_path,codex_config_path,@@ -53,6 +54,8 @@ WARN = "warn"FAIL = "fail"SKIP = "skip"+DEFAULT_PROXY_PORT = 8787+_LOOPBACK_URL_RE = re.compile(r"https?://(?:127\.0\.0\.1|localhost):(\d+)")_CODEX_BASE_URL_RE = re.compile(r'(?m)^[ \t]*base_url\s*=\s*"([^"\r\n]+)"')_CODEX_MODEL_PROVIDER_RE = re.compile(r'(?m)^[ \t]*model_provider\s*=\s*"([^"\r\n]+)"')@@ -1099,14 +1102,53 @@ def _render(checks: list[CheckResult], port: int, installed: str) -> None:console.print("\n[green bold]all checks passed[/green bold]")+def resolve_probe_port(+ requested: int | None,+ manifests: Sequence[DeploymentManifest],+) -> int:+ """Resolve the port `doctor` should probe.++ Precedence: an explicit ``--port`` (or ``HEADROOM_PORT``) wins, then the+ port a managed deployment recorded, then the built-in default.++ The manifest tier matters because ``headroom deploy --port N`` writes N+ into the deployment's own environment, not into the shell `doctor` later+ runs in. Without it a healthy non-default deployment is reported as+ unreachable, and the remediation hints point at the wrong port.++ A deployment is only consulted when it is unambiguous: the ``default``+ profile, or a lone profile under another name. With several named profiles+ and no explicit request there is no non-arbitrary choice, so the built-in+ default is used and the per-deployment section reports each one instead.++ Args:+ requested: Port supplied on the command line or via the environment.+ manifests: Deployment manifests to consider.++ Returns:+ The port to probe.+ """+ if requested is not None:+ return requested+ default_profile = next((m for m in manifests if m.profile == "default"), None)+ if default_profile is not None:+ return default_profile.port+ if len(manifests) == 1:+ return manifests[0].port+ return DEFAULT_PROXY_PORT++@main.command()@click.option("--port","-p",- default=8787,+ default=None,type=click.IntRange(1, 65535),envvar="HEADROOM_PORT",- help="Proxy port to check (default: 8787, env: HEADROOM_PORT)",+ help=(+ "Proxy port to check (env: HEADROOM_PORT). Defaults to the port of a "+ f"single managed deployment, else {DEFAULT_PROXY_PORT}."+ ),)@click.option("--json", "emit_json", is_flag=True, help="Emit JSON instead of formatted output.")@click.option(@@ -1125,7 +1167,12 @@ def _render(checks: list[CheckResult], port: int, installed: str) -> None:metavar="URL",help="Extra upstream URL to test with --network (repeatable), e.g. a custom gateway.",)-def doctor(port: int, emit_json: bool, network: bool, network_urls: tuple[str, ...]) -> None:+def doctor(+ port: int | None,+ emit_json: bool,+ network: bool,+ network_urls: tuple[str, ...],+) -> None:"""Check that the Headroom proxy and client routing are working.\b@@ -1134,13 +1181,14 @@ def doctor(port: int, emit_json: bool, network: bool, network_urls: tuple[str, .1 warnings only (working, but not optimally wired)2 at least one failure (proxy down / deployment down)"""+ manifests = list_manifests()+ port = resolve_probe_port(port, manifests)base_url = f"http://127.0.0.1:{port}"livez = probe_json(f"{base_url}/livez")readyz = probe_json(f"{base_url}/readyz", timeout=3.0) if livez else Nonehealth = probe_json(f"{base_url}/health", timeout=5.0) if livez else Nonestats = probe_json(f"{base_url}/stats", timeout=5.0) if livez else Noneinstalled = get_version()- manifests = list_manifests()live_elsewhere = Noneif livez is None:# Cheap, bounded: only ports Headroom recorded (HEADROOM_PORT, 8787,diff --git a/tests/test_cli/test_port_alignment.py b/tests/test_cli/test_port_alignment.pyindex 78f8f3b23..c0169452b 100644--- a/tests/test_cli/test_port_alignment.py+++ b/tests/test_cli/test_port_alignment.py@@ -565,7 +565,7 @@ class TestDoctorAdditions:monkeypatch.setattr(doctor_mod, "check_deployments", lambda manifests: None)monkeypatch.setattr(doctor_mod, "claude_settings_path", lambda: home / "settings.json")monkeypatch.setattr(doctor_mod, "savings_path", lambda: home / "savings.json")- result = CliRunner().invoke(main, ["doctor", "--json"])+ result = CliRunner().invoke(main, ["doctor", "--json", "--port", "8787"])payload = json.loads(result.output)assert payload["exit_code"] == 2 # still a failure at the probed portproxy = next(c for c in payload["checks"] if c["name"] == "proxy")diff --git a/tests/test_cli_doctor.py b/tests/test_cli_doctor.pyindex c40f5ce24..0b37c9975 100644--- a/tests/test_cli_doctor.py+++ b/tests/test_cli_doctor.py@@ -10,6 +10,7 @@ from click.testing import CliRunnerimport headroom.cli.doctor as doctor_modfrom headroom.cli.doctor import (+ DEFAULT_PROXY_PORT,FAIL,PASS,SKIP,@@ -25,6 +26,7 @@ from headroom.cli.doctor import (check_savings,check_shell_env,check_version_drift,+ resolve_probe_port,)from headroom.cli.main import mainfrom headroom.providers.claude.runtime import remote_control_gate_message@@ -804,6 +806,7 @@ class TestBudget:class _FakeManifest:profile: strhealth_url: str+ port: int = 8787class TestDeployments:@@ -822,6 +825,33 @@ class TestDeployments:assert "prod" in result.summary+class TestResolveProbePort:+ def test_explicit_port_wins_over_deployment(self):+ manifests = [_FakeManifest("default", "", port=8789)]+ assert resolve_probe_port(9000, manifests) == 9000++ def test_default_profile_deployment_port_is_preferred(self):+ manifests = [+ _FakeManifest("prod", "", port=9999),+ _FakeManifest("default", "", port=8789),+ ]+ assert resolve_probe_port(None, manifests) == 8789++ def test_single_non_default_deployment_is_used(self):+ assert resolve_probe_port(None, [_FakeManifest("prod", "", port=9999)]) == 9999++ def test_builtin_default_without_deployments(self):+ assert resolve_probe_port(None, []) == DEFAULT_PROXY_PORT++ def test_ambiguous_named_deployments_fall_back_to_the_default(self):+ """Several named profiles and no request: any pick would be arbitrary."""+ manifests = [+ _FakeManifest("prod", "", port=9998),+ _FakeManifest("staging", "", port=9999),+ ]+ assert resolve_probe_port(None, manifests) == DEFAULT_PROXY_PORT++class TestDoctorCommand:@pytest.fixturedef runner(self):@@ -938,6 +968,24 @@ class TestDoctorCommand:runner.invoke(main, ["doctor"], env={"HEADROOM_PORT": "9999"})assert "http://127.0.0.1:9999/livez" in seen+ def test_deployment_port_probed_when_shell_has_no_override(self, runner, isolated, monkeypatch):+ """`headroom deploy --port N` only sets HEADROOM_PORT inside the deployment."""+ seen: list[str] = []++ def recording_probe(url, timeout=2.0):+ seen.append(url)+ return None++ monkeypatch.setattr(+ doctor_mod,+ "list_manifests",+ lambda: [_FakeManifest("default", "http://127.0.0.1:8789/readyz", port=8789)],+ )+ monkeypatch.setattr(doctor_mod, "probe_json", recording_probe)+ runner.invoke(main, ["doctor"])+ assert "http://127.0.0.1:8789/livez" in seen+ assert not any("127.0.0.1:8787" in url for url in seen)+class TestCostTrackerBudgetKeys:def test_stats_exposes_budget_config(self):diff --git a/tests/test_docker_compose_persistence.py b/tests/test_docker_compose_persistence.pyindex f6f1e05b2..a8e440891 100644--- a/tests/test_docker_compose_persistence.py+++ b/tests/test_docker_compose_persistence.py@@ -138,4 +138,5 @@ def test_published_dockerfile_stages_default_to_loopback() -> None:dockerfile = (ROOT / "Dockerfile").read_text(encoding="utf-8")assert dockerfile.count("ENV HEADROOM_HOST=127.0.0.1") == 2- assert dockerfile.count('CMD ["--port", "8787"]') == 2+ assert 'CMD ["--port", "8787"]' not in dockerfile+ assert 'CMD ["--host", "0.0.0.0"]' not in dockerfilediff --git a/tests/test_docker_healthcheck_port.py b/tests/test_docker_healthcheck_port.pynew file mode 100644index 000000000..170910faa--- /dev/null+++ b/tests/test_docker_healthcheck_port.py@@ -0,0 +1,102 @@+"""Regression checks for port-aware container startup and healthchecks (#2432).++`headroom proxy --port` is a click option with `envvar="HEADROOM_PORT"`, and an+explicit CLI argument beats the envvar. So a baked `--port` in CMD and a+hardcoded probe port in HEALTHCHECK are two halves of the same defect: the+first makes HEADROOM_PORT unable to move the listener, the second makes the+probe unable to follow it.+"""++from __future__ import annotations++import re+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]++STAGE_RE = re.compile(r"^FROM\s+\S+\s+AS\s+(\S+)\s*$", re.IGNORECASE)+++def _stage_body(dockerfile: str, stage: str) -> str:+ """Return the lines belonging to a single named build stage."""++ body: list[str] = []+ collecting = False+ for line in dockerfile.splitlines():+ match = STAGE_RE.match(line.strip())+ if match:+ collecting = match.group(1) == stage+ continue+ if collecting:+ body.append(line)+ assert body, f"stage {stage!r} not found in Dockerfile"+ return "\n".join(body)+++def _healthcheck_directives(dockerfile: str) -> list[str]:+ """Collect every HEALTHCHECK directive, joining backslash continuations."""++ directives: list[str] = []+ lines = dockerfile.splitlines()+ for index, line in enumerate(lines):+ if not line.lstrip().startswith("HEALTHCHECK"):+ continue+ parts = [line.rstrip("\\").strip()]+ cursor = index+ while lines[cursor].rstrip().endswith("\\") and cursor + 1 < len(lines):+ cursor += 1+ parts.append(lines[cursor].rstrip("\\").strip())+ directives.append(" ".join(parts))+ return directives+++def test_dockerfile_defines_a_healthcheck_per_runtime_stage() -> None:+ directives = _healthcheck_directives((ROOT / "Dockerfile").read_text(encoding="utf-8"))++ assert len(directives) == 2+++def test_no_healthcheck_hardcodes_the_default_port() -> None:+ """A hardcoded probe port reports a working non-8787 deployment as unhealthy."""++ directives = _healthcheck_directives((ROOT / "Dockerfile").read_text(encoding="utf-8"))++ offenders = [d for d in directives if "127.0.0.1:8787" in d]+ assert offenders == []+++def test_every_healthcheck_resolves_the_port_from_the_environment() -> None:+ directives = _healthcheck_directives((ROOT / "Dockerfile").read_text(encoding="utf-8"))++ assert directives, "expected at least one HEALTHCHECK directive"+ for directive in directives:+ assert "HEADROOM_PORT" in directive+++def test_distroless_stage_healthcheck_stays_shell_free() -> None:+ """The distroless stage has no shell, so ${VAR} expansion is unavailable."""++ dockerfile = (ROOT / "Dockerfile").read_text(encoding="utf-8")+ directives = _healthcheck_directives(_stage_body(dockerfile, "runtime-slim"))++ assert len(directives) == 1+ assert "${HEADROOM_PORT" not in directives[0]+ # `or` and not a get() default, so an empty value falls back like `:-` does.+ assert "(os.environ.get('HEADROOM_PORT') or '8787')" in directives[0]+++def test_debian_stage_healthcheck_expands_the_port_variable() -> None:+ dockerfile = (ROOT / "Dockerfile").read_text(encoding="utf-8")+ directives = _healthcheck_directives(_stage_body(dockerfile, "runtime-slim-base"))++ assert len(directives) == 1+ assert "${HEADROOM_PORT:-8787}" in directives[0]+++def test_no_stage_bakes_a_port_into_cmd() -> None:+ """A baked `--port` outranks HEADROOM_PORT and pins the listener to 8787."""++ dockerfile = (ROOT / "Dockerfile").read_text(encoding="utf-8")+ cmds = [line for line in dockerfile.splitlines() if line.startswith("CMD ")]++ assert not any("--port" in cmd for cmd in cmds)