mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-12-03 10:27:23 +08:00
## Description A wrap that cannot reuse the proxy on its port starts a dedicated proxy from the shell environment alone. That happens for every Copilot subscription seed (`headroom wrap vscode`, `wrap copilot --subscription`) and for a persistent deployment with other routing: `_ensure_proxy_unlocked` prints "starting a dedicated local proxy instance" and `_start_proxy` spawns `python -m headroom.cli proxy --port N` with `os.environ.copy()` only. An enterprise install enables its savings sinks on the shared proxy as `--proxy-extension control_plane,observability,...` (`headroom start --daemon`, `headroom-start.sh`). Nothing forwarded that flag, so the dedicated proxy came up with no extensions: the local dashboard filled while the team's dashboard stayed empty, with no error anywhere. This is the shape a customer on VS Code Copilot Enterprise reported this week, and one of the explanations for #3716. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature - [ ] Breaking change - [ ] Documentation update ## Changes Made - `headroom/proxy/server.py`: the loopback `/health` config block now lists `proxy_extensions` (the enabled names only, sorted; no plugin state). - `headroom/cli/wrap.py`: - `_dedicated_proxy_extensions(port, manifest)` reads the extension set of the proxy that owns the requested port: the running proxy's `/health` first, else the `HEADROOM_PROXY_EXTENSIONS` recorded in the persistent manifest's `base_env` (`_manifest_proxy_extensions`; the installer has no extension flag, so that is the only form a manifest records). A running proxy that predates the field falls through to the manifest, and a manifest without the entry is unknown rather than empty (the deployment's runtime env layers on the launch environment). Returns `[]` only for a non-Headroom port holder, a live `/health` reporting an empty list, or an explicitly empty manifest value; `None` otherwise, which triggers the warning. - At the dedicated start, whenever this start leaves a running proxy on the port in place (one `replaces_running_proxy` flag: Copilot seed isolation, persistent routing mismatch, the attached non-persistent routing mismatch, and the unknown-config branch) and `HEADROOM_PROXY_EXTENSIONS` is absent from the environment (an empty value counts as set: it is the way to start a bare dedicated proxy, and click lets the flag outrank the envvar, so wrap must not pass the flag then), the carried set is passed to `_start_proxy(proxy_extensions=...)`, which adds `--proxy-extension <csv>`. The banner prints `Extensions carried over from the proxy on port N: ...`, or one `Warning:` line with the remedy (`HEADROOM_PROXY_EXTENSIONS=<names>`) when the set could not be read. - An explicit `HEADROOM_PROXY_EXTENSIONS` in the environment is inherited by the subprocess and wins; nothing changes when no proxy owns the port. - Tests: `tests/test_cli/test_wrap_persistent.py` (carry-over from `/health`, env wins for both a value and an empty string, warning when unreadable, no warning for a foreign port holder, manifest fallback, older proxy falling through to the manifest, older proxy with a silent manifest warning, explicitly empty manifest value trusted, the attached routing-mismatch branch, plain start unchanged; the two existing isolated-seed tests now stub `_query_proxy_health` so they stay hermetic), `tests/test_cli/test_wrap_helpers.py` (`_start_proxy` emits the flag), `tests/test_proxy_healthchecks.py` (`/health` reports the names). ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for the fix - [x] Manual testing performed (live run below) ### Test Output ```text $ pytest -q tests/test_cli/test_wrap_persistent.py tests/test_cli/test_wrap_helpers.py \ tests/test_proxy_healthchecks.py tests/test_cli/test_wrap_vscode.py \ tests/test_cli/test_wrap_copilot.py tests/test_proxy_extensions.py 4 failed, 193 passed in 7.25s # The 4 failures are on clean main too (same files, patch reverted): # tests/test_cli/test_wrap_persistent.py::test_{ensure_proxy_recovers_matching_persistent_deployment, # ensure_proxy_recovers_persistent_deployment_when_socket_is_bound, # recover_persistent_proxy_reuses_healthy_deployment,recover_persistent_proxy_warns_for_task_deployment} # AttributeError: '_Manifest' object has no attribute 'runtime_kind' (install/runtime.py:241, since #4123) $ uvx ruff@0.16.8 check <touched files> && uvx ruff@0.16.8 format --check <touched files> All checks passed! / 5 files already formatted $ mypy headroom/cli/wrap.py headroom/proxy/server.py --ignore-missing-imports Success: no issues found in 2 source files ``` ## Real Behavior Proof - Environment: macOS, Python 3.12, repo venv with the branch on `PYTHONPATH`, native core present, `HEADROOM_WORKSPACE_DIR` pointed at a scratch directory so the developer's `settings.json` (which already enables `teams`) and client markers stay out of the run. No credentials involved; nothing redacted. - Exact command / steps: ```text # 1. shared proxy with two extensions (the shape `headroom start --daemon` / headroom-start.sh produce) $ python -m headroom.cli proxy --port 18903 --proxy-extension skill_search,lossless_guard --workers 1 Extensions: ENABLED lossless_guard,skill_search (available: foresight,kiro,lossless_guard,output_pro,routemegood,skill_search,teams,tool_search) $ curl -s 127.0.0.1:18903/health # config excerpt { "backend": "anthropic", "openai_api_url": null, "proxy_extensions": ["lossless_guard", "skill_search"], "pid": 81870 } # 2. another wrap client attached to it (marker under <workspace>/clients/18903/<pid>.json) $ python -c "import time; from headroom.cli.wrap import _register_proxy_client; _register_proxy_client(18903); time.sleep(400)" & # 3. a wrap that requests a different backend -> attached routing mismatch -> dedicated proxy $ HEADROOM_BACKEND=openai python -m headroom.cli wrap cursor --port 18903 Proxy on port 18903 has incompatible routing config (backend), but live session(s) are attached. Starting a dedicated proxy on a different port instead of reusing or disrupting it. Port 18903 is in use, using port 18904 instead. Extensions carried over from the proxy on port 18903: lossless_guard,skill_search Starting Headroom proxy on port 18904... Proxy ready — dashboard: http://127.0.0.1:18904/dashboard $ curl -s 127.0.0.1:18904/health # config excerpt { "backend": "openai", "openai_api_url": null, "proxy_extensions": ["lossless_guard", "skill_search"], "pid": 82266 } ``` - Observed result: the dedicated proxy on the next port runs the same two extensions as the shared proxy it was started beside, and the wrap banner says so. The shared proxy was neither restarted nor killed. - Control run worth knowing about: the same flow with the developer's real `settings.json` (which stores `proxy_extensions: "teams"`) showed no "carried over" line and the dedicated proxy ran `teams`: `settings.json` is applied to the environment before the guard, so a persisted `HEADROOM_PROXY_EXTENSIONS` takes the env-wins path by design. - Unit coverage adds the Copilot-seed, persistent-manifest, older-proxy and env-wins cases that the live run did not exercise. - Live Copilot run (2026-10-13, Copilot Business seat, branch merged with #4155 on current `main`): a shared proxy on 8898 with `--proxy-extension e2e_probe` (a probe extension recording which proxy loaded it and every request it saw, standing in for `control_plane`), then `headroom wrap vscode -p 8898`. Banner: `Extensions carried over from the proxy on port 8898: e2e_probe`; dedicated proxy args `--port 8899 --openai-api-url https://api.business.githubcopilot.com --proxy-extension e2e_probe`. The probe saw every request on the dedicated proxy: a 36-request model sweep plus real VS Code chat, Claude, and Agent-mode turns, all 200. Same scenario with `main`'s `wrap.py`: dedicated proxy args have no `--proxy-extension`, `/health` `proxy_extensions: []`. Also checked live: `HEADROOM_PROXY_EXTENSIONS=` → bare proxy; `HEADROOM_PROXY_EXTENSIONS=control_plane` → env wins; shared proxy with no extensions → none, no warning; no shared proxy → wrap owns the port, nothing carried. - Not tested: the portal heartbeat leg (`headroom login` + `control_plane` reporting to the dashboard). The 4 pre-existing `_Manifest` test failures named under Testing are unrelated. ## Runtime Rollout Safety - Rollout-managed feature(s): none. - Minimum rollout channel: stable. - Stable/default behavior changed: a dedicated proxy started beside a shared one now starts with that proxy's extensions instead of none. A user who wanted a bare dedicated proxy sets `HEADROOM_PROXY_EXTENSIONS=` explicitly. - Kill switch / disable path: `HEADROOM_PROXY_EXTENSIONS=` (empty) starts a bare dedicated proxy; revert the commit. - Unsafe override required: no. - Qualification impact: wrap proxy-lifecycle and health suites. - Rollback path: revert. ## 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 added tests that prove my fix is effective - [x] New and existing unit tests pass locally with my changes (except the 4 pre-existing failures named above) - [x] I did **not** edit `CHANGELOG.md` Refs #3716 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
354 lines
12 KiB
Python
354 lines
12 KiB
Python
import os
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
pytest.importorskip("fastapi")
|
|
pytest.importorskip("httpx")
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
from headroom.proxy.server import ProxyConfig, __version__, create_app
|
|
|
|
|
|
@pytest.fixture
|
|
def client(monkeypatch):
|
|
# Skip the live upstream connectivity probe in unit tests — tests verify
|
|
# the check logic separately (see test_readyz_upstream_check_* below).
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
)
|
|
app = create_app(config)
|
|
# Loopback client/Host: /health serves the `config` block only to loopback
|
|
# callers (network callers get the /readyz-shape body, no config).
|
|
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345)) as test_client:
|
|
yield test_client
|
|
|
|
|
|
def test_livez_reports_process_health(client):
|
|
response = client.get("/livez")
|
|
|
|
assert response.status_code == 200
|
|
data = response.json()
|
|
assert data["service"] == "headroom-proxy"
|
|
assert data["status"] == "healthy"
|
|
assert data["alive"] is True
|
|
assert data["version"] == __version__
|
|
assert data["uptime_seconds"] >= 0
|
|
|
|
|
|
def test_readyz_reports_core_subsystem_checks(client):
|
|
response = client.get("/readyz")
|
|
|
|
assert response.status_code == 200
|
|
data = response.json()
|
|
assert data["ready"] is True
|
|
assert data["status"] == "healthy"
|
|
assert "config" not in data
|
|
assert data["checks"]["startup"]["status"] == "healthy"
|
|
assert data["checks"]["http_client"]["status"] == "healthy"
|
|
assert data["checks"]["cache"]["status"] == "disabled"
|
|
assert data["checks"]["rate_limiter"]["status"] == "disabled"
|
|
assert data["checks"]["memory"]["status"] == "disabled"
|
|
runtime = data["runtime"]
|
|
assert runtime["anthropic_pre_upstream"]["resolved_concurrency"] == max(
|
|
2, min(8, os.cpu_count() or 4)
|
|
)
|
|
assert runtime["anthropic_pre_upstream"]["source"] == "auto"
|
|
assert runtime["anthropic_pre_upstream"]["acquire_timeout_seconds"] == 15.0
|
|
assert runtime["anthropic_pre_upstream"]["compression_timeout_seconds"] == 30.0
|
|
assert runtime["anthropic_pre_upstream"]["memory_context_timeout_seconds"] == 2.0
|
|
assert runtime["anthropic_pre_upstream"]["codex_ws_gated"] is False
|
|
assert runtime["websocket_sessions"]["active_sessions"] == 0
|
|
assert runtime["websocket_sessions"]["active_relay_tasks"] == 0
|
|
|
|
|
|
def test_health_preserves_backwards_compatible_config_payload(client):
|
|
response = client.get("/health")
|
|
|
|
assert response.status_code == 200
|
|
data = response.json()
|
|
assert data["status"] == "healthy"
|
|
assert data["ready"] is True
|
|
assert data["version"] == __version__
|
|
config = data["config"]
|
|
assert config["backend"] == "anthropic"
|
|
assert config["optimize"] is False
|
|
assert config["cache"] is False
|
|
assert config["rate_limit"] is False
|
|
assert config["memory"] is False
|
|
assert config["learn"] is False
|
|
assert config["code_graph"] is False
|
|
assert config["savings_profile"] is None
|
|
assert config["target_ratio"] is None
|
|
assert config["max_items_after_crush"] == 50
|
|
assert config["smart_crusher_with_compaction"] is None
|
|
assert isinstance(config["pid"], int)
|
|
# `headroom wrap` reads this on proxy reuse to warn on a mode mismatch.
|
|
assert config["mode"] in ("token", "cache")
|
|
|
|
|
|
def test_health_reports_agent_savings_config():
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
savings_profile="agent-90",
|
|
target_ratio=0.10,
|
|
compress_user_messages=True,
|
|
compress_system_messages=True,
|
|
protect_recent=2,
|
|
protect_analysis_context=True,
|
|
min_tokens_to_crush=120,
|
|
max_items_after_crush=8,
|
|
smart_crusher_with_compaction=False,
|
|
accuracy_guard="strict",
|
|
)
|
|
app = create_app(config)
|
|
|
|
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345)) as client:
|
|
response = client.get("/health")
|
|
|
|
assert response.status_code == 200
|
|
reported = response.json()["config"]
|
|
assert reported["savings_profile"] == "agent-90"
|
|
assert reported["target_ratio"] == 0.10
|
|
assert reported["compress_user_messages"] is True
|
|
assert reported["compress_system_messages"] is True
|
|
assert reported["protect_recent"] == 2
|
|
assert reported["protect_analysis_context"] is True
|
|
assert reported["min_tokens_to_crush"] == 120
|
|
assert reported["max_items_after_crush"] == 8
|
|
assert reported["smart_crusher_with_compaction"] is False
|
|
assert reported["accuracy_guard"] == "strict"
|
|
|
|
|
|
def test_health_includes_deployment_metadata_when_present(monkeypatch):
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
monkeypatch.setenv("HEADROOM_DEPLOYMENT_PROFILE", "default")
|
|
monkeypatch.setenv("HEADROOM_DEPLOYMENT_PRESET", "persistent-service")
|
|
monkeypatch.setenv("HEADROOM_DEPLOYMENT_RUNTIME", "python")
|
|
monkeypatch.setenv("HEADROOM_DEPLOYMENT_SUPERVISOR", "service")
|
|
monkeypatch.setenv("HEADROOM_DEPLOYMENT_SCOPE", "user")
|
|
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
)
|
|
app = create_app(config)
|
|
|
|
with TestClient(app) as client:
|
|
response = client.get("/health")
|
|
|
|
assert response.status_code == 200
|
|
assert response.json()["deployment"] == {
|
|
"profile": "default",
|
|
"preset": "persistent-service",
|
|
"runtime": "python",
|
|
"supervisor": "service",
|
|
"scope": "user",
|
|
}
|
|
|
|
|
|
def test_health_remains_200_when_proxy_is_not_ready(client):
|
|
client.app.state.ready = False
|
|
|
|
response = client.get("/health")
|
|
|
|
assert response.status_code == 200
|
|
assert response.json()["ready"] is False
|
|
|
|
|
|
def test_readyz_reports_memory_backend_when_enabled(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
memory_enabled=True,
|
|
memory_backend="local",
|
|
memory_db_path=str(tmp_path / "headroom_memory.db"),
|
|
memory_inject_tools=True,
|
|
memory_inject_context=True,
|
|
)
|
|
app = create_app(config)
|
|
|
|
with TestClient(app) as client:
|
|
response = client.get("/readyz")
|
|
|
|
assert response.status_code == 200
|
|
data = response.json()
|
|
assert data["checks"]["memory"]["status"] == "healthy"
|
|
assert data["checks"]["memory"]["backend"] == "local"
|
|
assert data["checks"]["memory"]["initialized"] is True
|
|
|
|
|
|
def test_readyz_initializes_qdrant_memory_backend(monkeypatch):
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
from headroom.memory.backends import direct_mem0
|
|
|
|
init_calls: list[str] = []
|
|
|
|
class FakeDirectMem0Adapter:
|
|
def __init__(self, config):
|
|
self.config = config
|
|
|
|
async def ensure_initialized(self):
|
|
init_calls.append("initialized")
|
|
|
|
monkeypatch.setattr(direct_mem0, "DirectMem0Adapter", FakeDirectMem0Adapter)
|
|
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
memory_enabled=True,
|
|
memory_backend="qdrant-neo4j",
|
|
)
|
|
app = create_app(config)
|
|
|
|
with TestClient(app) as client:
|
|
response = client.get("/readyz")
|
|
|
|
assert response.status_code == 200
|
|
data = response.json()
|
|
assert init_calls == ["initialized"]
|
|
assert data["checks"]["memory"]["status"] == "healthy"
|
|
assert data["checks"]["memory"]["backend"] == "qdrant-neo4j"
|
|
assert data["checks"]["memory"]["initialized"] is True
|
|
|
|
|
|
def test_shutdown_tolerates_stubbed_memory_handler(monkeypatch):
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
)
|
|
app = create_app(config)
|
|
|
|
with TestClient(app) as client:
|
|
client.app.state.proxy.memory_handler = SimpleNamespace(
|
|
health_status=lambda: {
|
|
"enabled": False,
|
|
"backend": None,
|
|
"initialized": False,
|
|
"native_tool": False,
|
|
"bridge_enabled": False,
|
|
}
|
|
)
|
|
response = client.get("/health")
|
|
|
|
assert response.status_code == 200
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Upstream connectivity check tests
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_readyz_upstream_check_disabled_by_env_var(monkeypatch):
|
|
"""HEADROOM_SKIP_UPSTREAM_CHECK=1 suppresses the probe and reports ready."""
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
)
|
|
app = create_app(config)
|
|
|
|
with TestClient(app) as test_client:
|
|
response = test_client.get("/readyz")
|
|
|
|
assert response.status_code == 200
|
|
data = response.json()
|
|
assert data["ready"] is True
|
|
# When the check is skipped the component is reported as "disabled"
|
|
assert data["checks"]["upstream"]["enabled"] is False
|
|
assert data["checks"]["upstream"]["ready"] is True
|
|
|
|
|
|
def test_readyz_upstream_check_failure_returns_503(monkeypatch):
|
|
"""A failed upstream probe makes /readyz return HTTP 503."""
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import httpx
|
|
|
|
monkeypatch.delenv("HEADROOM_SKIP_UPSTREAM_CHECK", raising=False)
|
|
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
)
|
|
app = create_app(config)
|
|
|
|
# Patch the proxy's shared http_client.head so the probe uses the same
|
|
# client as real traffic (which also means TLS/CA config is consistent).
|
|
with TestClient(app) as test_client:
|
|
with patch.object(
|
|
test_client.app.state.proxy.http_client,
|
|
"head",
|
|
new=AsyncMock(side_effect=httpx.ConnectError("connection refused (test)")),
|
|
):
|
|
response = test_client.get("/readyz")
|
|
|
|
assert response.status_code == 503
|
|
data = response.json()
|
|
assert data["ready"] is False
|
|
assert data["checks"]["upstream"]["ready"] is False
|
|
assert "connection refused" in data["checks"]["upstream"]["error"]
|
|
|
|
|
|
def test_health_includes_upstream_check_result(monkeypatch):
|
|
"""/health always returns 200 but exposes the upstream check result."""
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
)
|
|
app = create_app(config)
|
|
|
|
with TestClient(app) as test_client:
|
|
response = test_client.get("/health")
|
|
|
|
assert response.status_code == 200
|
|
data = response.json()
|
|
assert "upstream" in data["checks"]
|
|
upstream = data["checks"]["upstream"]
|
|
assert "enabled" in upstream
|
|
assert "ready" in upstream
|
|
assert "status" in upstream
|
|
|
|
|
|
def test_health_reports_enabled_proxy_extensions():
|
|
"""`headroom wrap` reads this to carry the shared proxy's extensions over to a
|
|
dedicated proxy it has to start beside it."""
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
proxy_extensions=["routemegood", "observability"],
|
|
)
|
|
app = create_app(config)
|
|
|
|
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345)) as client:
|
|
reported = client.get("/health").json()["config"]
|
|
|
|
assert reported["proxy_extensions"] == ["observability", "routemegood"]
|