Files
headroom/tests/test_cli/test_proxy_port_discovery.py
02c4e922f7 fix(cli): resolve active proxy port for read commands (#3522)
## Description

`headroom wrap copilot` can intentionally start a dedicated proxy on
port 8788
(or fall forward when 8787 is busy), but read-only CLI commands
previously
defaulted directly to 8787. As a result, `headroom dashboard` could open
a dead
or unrelated dashboard even though the wrapped session reported its
proxy on
8788.

This change extends the shared `headroom/cli/port_discovery.py` resolver
(introduced by #3855) to include live wrap-client markers, preferring
the
newest healthy session while preserving explicit `--port` and
`HEADROOM_PORT`
overrides.

Closes: N/A (no matching open issue found)

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Extended the shared port discovery module from #3855 with live
wrap-client
marker validation (PID liveness and reuse checks), newest-session
ordering,
  and `/health` verification.
- Updated `dashboard`, `inspect`, and the runtime probe used by `learn`
to
  follow the newest healthy live wrap session after explicit and
  `HEADROOM_PORT` overrides.
- Kept `doctor`'s requested-port behavior; it now reports a healthy
proxy
  discovered from wrap-client markers elsewhere, with a `--port` hint.
- Added a warning when `dashboard` cannot reach the resolved port.
- Exported the actual proxy port as `HEADROOM_PORT` into every wrapped
agent
  environment.
- Reused #3855's port-discovery module rather than introducing a
parallel
  resolver.
- Added regression coverage for stale/recycled markers, multiple
sessions,
  explicit/environment overrides, dashboard output, doctor diagnostics,
  inspect/learn routing, and wrapped child environments.
- Documented automatic discovery and wrong-port troubleshooting.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ uv run pytest tests/test_cli/test_proxy_port_discovery.py \
    tests/test_cli/test_dashboard_port_discovery.py \
    tests/test_cli/test_port_alignment.py \
    tests/test_cli/test_wrap_helpers.py \
    tests/test_cli_doctor.py tests/test_cli_inspect.py tests/test_cli_learn.py -q
267 passed in 5.49s

$ uv run ruff check .
All checks passed!

$ uv run ruff format --check .
1677 files already formatted

$ uv run mypy headroom/cli/port_discovery.py headroom/cli/proxy.py \
    headroom/cli/doctor.py headroom/cli/inspect.py headroom/cli/learn.py
Success: no issues found in 5 source files

$ uv run pre-commit run --all-files
Sync plugin versions.....................................................Passed
Verify Ruff version alignment............................................Passed
check for merge conflicts................................................Passed
ruff (legacy alias)......................................................Passed
ruff format..............................................................Passed
mypy.....................................................................Passed
```

After the first rebase, `make ci-precheck` completed `cargo fmt --check`
and
`cargo clippy --workspace -- -D warnings`, then stalled in the existing
Rust
Magika/detection tests (multiple tests exceeded 60 seconds). The same
stall
recurred during the push hook; it was stopped after confirming the
affected
suite. The final rebase onto #3883 was followed by the Python/CLI
regression
suite and all repository pre-commit gates above, but not another Rust
test run.

## Real Behavior Proof

- Environment: Ubuntu 22.04.5 LTS x86_64; Python 3.10.12; uv 0.12.10;
Headroom proxy 0.40.0-dev, started on isolated port 18788 with an
isolated live-client marker.
- Exact command / steps: Started an isolated process that wrote its live
PID marker and launched `headroom proxy --port 18788` under a temporary
workspace, with `HEADROOM_PORT` unset; then ran `env -u HEADROOM_PORT -u
HEADROOM_PORT_DISCOVERY
HEADROOM_WORKSPACE_DIR=/tmp/headroom-port-discovery-proof-20260930/workspace
./.venv/bin/headroom dashboard --no-open` and curled
`http://127.0.0.1:18788/dashboard`.

```text
$ env -u HEADROOM_PORT -u HEADROOM_PORT_DISCOVERY \
    HEADROOM_WORKSPACE_DIR=/tmp/headroom-port-discovery-proof-20260930/workspace \
    ./.venv/bin/headroom dashboard --no-open
  Detected live proxy on port 18788
  Dashboard: http://127.0.0.1:18788/dashboard

$ curl --max-time 5 -sS -o /dev/null -w '%{http_code}\n' \
    http://127.0.0.1:18788/dashboard
200

# Proxy health before discovery returned:
service=headroom-proxy status=healthy ready=true
```

- Observed result: With `HEADROOM_PORT` unset, the CLI selected the
marker-associated healthy proxy on 18788, printed the matching dashboard
URL, and the endpoint returned HTTP 200. The earlier manual run with a
real wrapped Copilot session also confirmed discovery on 8788 before
this rebase.
- Not tested: Starting a new interactive `wrap copilot` session after
this rebase (avoided launching an agent); Windows/macOS PID-identity
behavior; multiple simultaneous real proxies; browser UI launch. Unit
tests cover marker ordering, PID reuse, and explicit/environment
overrides.

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: `dashboard`, `inspect`, and `learn`
now follow
the newest healthy live wrap proxy when no port override is set;
`doctor`
remains on the requested/default port and reports a live proxy
elsewhere.
- Kill switch / disable path: Pass `--port`, set `HEADROOM_PORT`, or set
  `HEADROOM_PORT_DISCOVERY=0` to bypass automatic discovery.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit; commands return to the fixed 8787
default.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from
  my Conventional Commit PR title

## Screenshots (if applicable)

N/A — terminal output above captures the behavior.

## Additional Notes

Port discovery is integrated into #3855's shared `port_discovery.py`;
candidates
are accepted only when `/health` identifies `service: headroom-proxy`,
so an
unrelated local JSON service cannot be mistaken for a Headroom proxy.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3522"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

### Maintainer current-main requalification

Exact head `e66a6393f83278aa07e9965f5b87fed820603677`, upstream main
`2d3ee51846435ef5b320eea4806af14e602b0d8c`.

Re-reviewed latest integration head 420c2d636 and current author
response, including isolated workspace/port fixtures and live-marker
ordering/pruning regressions. Clean integration with upstream/main
2d3ee51846. Explicit CLI ports and
HEADROOM_PORT retain precedence; discovery bounds candidate probes,
verifies Headroom health identity, prefers newest live wrap markers, and
preserves configured-agent discovery. No new PR-specific correctness
blocker found in scope.

All 436
dashboard/port/discovery/wrap/doctor/inspect/learn/release/version/MCP
tests pass. All 14 changed Python files pass Ruff check/format;
whitespace passes. Previous cached-read freeze-boundary failure was
independently reproduced on main and is not a contributor-code blocker.
Maintainers handle fresh exact-head qualification and distinguish
inherited failures; no contributor CI execution requested. Existing
native extension supported startup, not a fresh native build. No
contributor discovery logic rewritten; nothing merged.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-05 21:10:06 -06:00

297 lines
11 KiB
Python

"""Unit tests for live wrap-client port discovery.
`headroom wrap copilot` (isolated-subscription path) or a plain port-busy
fallback can start the proxy on a port other than 8787. Read-only commands
(`dashboard`, `doctor`, `inspect`, `learn`) need to find that real port from
the wrap-client marker files instead of blindly defaulting to 8787. These
tests pin the discovery/resolution contract directly.
"""
from __future__ import annotations
import json
from pathlib import Path
import click
import pytest
from headroom import paths as paths_mod
from headroom.cli import port_discovery as pd
@pytest.fixture
def clients_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""Redirect ``paths.workspace_dir()`` (and therefore ``proxy_clients_dir``,
which is built from it) into a throwaway tmp tree."""
workspace = tmp_path / "workspace"
monkeypatch.setattr(paths_mod, "workspace_dir", lambda: workspace)
monkeypatch.delenv("HEADROOM_PORT", raising=False)
monkeypatch.delenv("HEADROOM_PORT_DISCOVERY", raising=False)
monkeypatch.chdir(tmp_path)
return workspace / "clients"
def _write_marker(clients_root: Path, port: int, pid: int, *, started_at: float = 0.0) -> Path:
marker = clients_root / str(port) / f"{pid}.json"
marker.parent.mkdir(parents=True, exist_ok=True)
marker.write_text(json.dumps({"pid": pid, "started_at": started_at}))
return marker
# ---------------------------------------------------------------------------
# live_client_pids / live_client_proxy_ports
# ---------------------------------------------------------------------------
def test_no_markers_means_no_live_ports(clients_root: Path) -> None:
assert pd.live_client_proxy_ports() == []
assert pd.live_client_pids(8787) == []
def test_live_marker_is_discovered(clients_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
_write_marker(clients_root, 8788, pid=4242, started_at=100.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: pid == 4242)
assert pd.live_client_pids(8788) == [4242]
assert pd.live_client_proxy_ports() == [(8788, 100.0)]
def test_dead_marker_is_pruned_and_not_counted(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
marker = _write_marker(clients_root, 8788, pid=999, started_at=100.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: False)
assert pd.live_client_pids(8788) == []
assert pd.live_client_proxy_ports() == []
assert not marker.exists()
def test_recycled_pid_marker_is_pruned(clients_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
marker = _write_marker(clients_root, 8788, pid=999, started_at=100.0)
marker.write_text(
json.dumps(
{
"pid": 999,
"started_at": 100.0,
"start_src": "psutil",
"start_time": 1.0,
}
),
encoding="utf-8",
)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
monkeypatch.setattr(pd, "proc_identity", lambda pid: ("psutil", 100.0))
assert pd.live_client_pids(8788) == []
assert not marker.exists()
def test_multiple_ports_sorted_newest_first(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_write_marker(clients_root, 8787, pid=1, started_at=50.0)
_write_marker(clients_root, 8788, pid=2, started_at=200.0)
_write_marker(clients_root, 8790, pid=3, started_at=100.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
assert pd.live_client_proxy_ports() == [(8788, 200.0), (8790, 100.0), (8787, 50.0)]
def test_non_numeric_client_dirs_are_ignored(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
(clients_root / "not-a-port").mkdir(parents=True)
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
assert pd.live_client_proxy_ports() == [(8788, 1.0)]
# ---------------------------------------------------------------------------
# resolve_read_port
# ---------------------------------------------------------------------------
def test_explicit_port_always_wins(clients_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: True)
assert pd.resolve_read_port(9999) == (9999, "explicit")
def test_env_var_wins_over_discovery(clients_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: True)
monkeypatch.setenv("HEADROOM_PORT", "7000")
assert pd.resolve_read_port(None) == (7000, "env")
def test_no_markers_falls_back_to_default(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.delenv("HEADROOM_PORT", raising=False)
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: False)
assert pd.resolve_read_port(None) == (8787, "default")
def test_healthy_live_marker_is_discovered(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: port == 8788)
monkeypatch.delenv("HEADROOM_PORT", raising=False)
assert pd.resolve_read_port(None) == (8788, "discovered")
def test_unhealthy_marker_falls_back_to_default(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A live client marker with no proxy actually answering /health must not
be trusted — falls back to the historical default instead of a dead URL."""
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: False)
monkeypatch.delenv("HEADROOM_PORT", raising=False)
assert pd.resolve_read_port(None) == (8787, "default")
def test_newest_session_preferred_when_multiple_healthy(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_write_marker(clients_root, 8787, pid=1, started_at=50.0)
_write_marker(clients_root, 8788, pid=2, started_at=200.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: True)
monkeypatch.delenv("HEADROOM_PORT", raising=False)
assert pd.resolve_read_port(None) == (8788, "discovered")
def test_falls_through_to_next_candidate_when_newest_is_unhealthy(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""The newest session wins only if it is actually reachable; a stale/dead
newest candidate must not shadow an older but healthy one."""
_write_marker(clients_root, 8787, pid=1, started_at=50.0)
_write_marker(clients_root, 8788, pid=2, started_at=200.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: port == 8787)
monkeypatch.delenv("HEADROOM_PORT", raising=False)
assert pd.resolve_read_port(None) == (8787, "discovered")
def test_discovery_disabled_falls_back_to_default(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_write_marker(clients_root, 8788, pid=1, started_at=1.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: True)
monkeypatch.setenv("HEADROOM_PORT_DISCOVERY", "0")
assert pd.resolve_read_port(None) == (8787, "default")
def test_invalid_env_port_is_rejected(clients_root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("HEADROOM_PORT", "not-a-number")
with pytest.raises(click.ClickException, match="HEADROOM_PORT must be an integer"):
pd.resolve_read_port(None)
def test_out_of_range_env_port_is_rejected(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("HEADROOM_PORT", "70000")
with pytest.raises(click.ClickException, match="HEADROOM_PORT must be between 1 and 65535"):
pd.resolve_read_port(None)
# ---------------------------------------------------------------------------
# proxy_is_healthy
# ---------------------------------------------------------------------------
def test_proxy_is_healthy_true_when_health_reachable(monkeypatch: pytest.MonkeyPatch) -> None:
from headroom.install import health
monkeypatch.setattr(
health,
"probe_json",
lambda url, timeout=1.0: {"service": "headroom-proxy", "status": "healthy"},
)
assert pd.proxy_is_healthy(8787) is True
def test_proxy_is_healthy_false_when_unreachable(monkeypatch: pytest.MonkeyPatch) -> None:
from headroom.install import health
monkeypatch.setattr(health, "probe_json", lambda url, timeout=1.0: None)
assert pd.proxy_is_healthy(8787) is False
def test_proxy_is_healthy_rejects_unrelated_json_service(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from headroom.install import health
monkeypatch.setattr(
health,
"probe_json",
lambda url, timeout=1.0: {"service": "something-else", "status": "healthy"},
)
assert pd.proxy_is_healthy(8787) is False
def test_stale_markers_do_not_hide_healthy_deployment(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Many live-but-unhealthy wrap sessions must not evict a recorded deployment."""
from types import SimpleNamespace
from headroom.install import state
for offset in range(7):
_write_marker(clients_root, 8800 + offset, pid=100 + offset, started_at=float(offset))
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
monkeypatch.setattr(state, "list_manifests", lambda: [SimpleNamespace(port=9200)])
monkeypatch.setattr(pd, "proxy_is_healthy", lambda port, **_: port == 9200)
ports = pd.candidate_ports(8787, environ={}, cwd=clients_root.parent)
assert 9200 in ports
assert len([p for p in ports if 8800 <= p <= 8806]) == pd._MAX_CLIENT_MARKER_CANDIDATES
assert pd.resolve_read_port(None) == (9200, "discovered")
def test_marker_ports_are_probed_concurrently_once(
clients_root: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
import threading
_write_marker(clients_root, 8788, pid=1, started_at=300.0)
_write_marker(clients_root, 8789, pid=2, started_at=200.0)
_write_marker(clients_root, 8790, pid=3, started_at=100.0)
monkeypatch.setattr(pd, "pid_alive", lambda pid: True)
barrier = threading.Barrier(3, timeout=2)
calls: list[int] = []
def probe(port: int, **_: object) -> bool:
calls.append(port)
if port in {8788, 8789, 8790}:
barrier.wait() # deadlocks (BrokenBarrierError) unless probed concurrently
return port in {8789, 8790}
monkeypatch.setattr(pd, "proxy_is_healthy", probe)
assert pd.resolve_read_port(None) == (8789, "discovered")
assert sorted(calls) == [8788, 8789, 8790]