mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-08-27 14:17:10 -04:00
## Description Hardens persistent install startup and proxy compression behavior for issue #1843. Repeated `headroom install start` / scheduled ensure calls no longer spawn duplicate runtimes by default, and `/v1/compress` now fails open on compression timeout instead of returning a 503. The PR also adds a machine-readable platform feature matrix and app-level stabilization tests for health, compression functionality, timeout behavior, and matrix evidence. Refs #1843 ## 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 - [x] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - Wrapped direct persistent deployment starts with the existing profile-local runtime start lock. - Made `headroom install start` idempotent when the deployment is already healthy. - Added wedged-runtime handling: if a PID is running but `/readyz` does not recover inside the grace window, stop it before starting again. - Kept `install agent ensure` inside the already-held lock while delegating to the shared start helper. - Changed `/v1/compress` timeout behavior from `503 compression_timeout` to fail-open `200` with original messages, `compression_skipped: true`, and `skip_reason: compression_timeout`. - Added `tests/test_platform_stabilization_functional.py` covering real FastAPI health/compression routes, successful compression metrics, timeout fail-open speed, and a real JSON tool payload that reduces tokens. - Added `docs/platform-feature-matrix.json` and `docs/platform-stabilization.md` for Linux/macOS/Windows hardening coverage and known gaps. - Strengthened matrix tests so cited local test/workflow paths must exist. ## 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 # Clean source tree without copied Rust extension: functional module is skipped locally, as CI copies _core from the built wheel. > python -m pytest tests/test_install tests/test_cli/test_install_cli.py tests/test_platform_feature_matrix.py tests/test_platform_stabilization_functional.py -q collected 120 items / 1 skipped 119 passed, 2 skipped in 17.08s > python -m ruff check headroom/proxy/handlers/openai.py tests/test_platform_stabilization_functional.py tests/test_platform_feature_matrix.py All checks passed! # Local Windows compiled-core proof: > python -m maturin build --profile ci --out dist-local Built wheel for abi3 Python >= 3.10 to dist-local\headroom_ai-0.29.0-cp310-abi3-win_amd64.whl # Copied _core.pyd from the wheel into headroom/ for local route execution, then: > python -m pytest tests/test_platform_stabilization_functional.py -q collected 4 items 4 passed in 6.71s > python -m pytest tests/test_install tests/test_cli/test_install_cli.py tests/test_platform_feature_matrix.py -q collected 120 items 119 passed, 1 skipped in 17.16s Commit hooks: Sync plugin versions.....................................................Passed check for merge conflicts................................................Passed ruff.....................................................................Passed ruff-format..............................................................Passed mypy.....................................................................Passed ``` ## Real Behavior Proof - Environment: Windows 11, PowerShell, Python 3.13.13, worktree `C:\git\headroom-stabilization` on branch `jd/cross-platform-stabilization`. - Exact command / steps: built the Windows wheel with `maturin`, extracted `_core.pyd`, ran the new FastAPI route tests and install/matrix tests listed above, then removed generated artifacts before committing. - Observed result: direct start paths now no-op when healthy, skip spawning when the start lock is contended, and stop a wedged runtime before restart. `/v1/compress` now returns original messages quickly on timeout instead of a 503. The real JSON tool-payload smoke test returns `tokens_before > tokens_after`, `tokens_saved > 0`, `compression_ratio < 1.0`, and non-empty transforms through the public route. - Not tested: full native Windows persistent process e2e remains blocked by the upstream CRT/wheel issue already documented in workflows and in the matrix. No real OS service was installed locally; service manager behavior is covered by argument-level unit tests. ## 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 - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) N/A ## Additional Notes CHANGELOG is not updated because this is an unreleased hardening/test/documentation pass. The platform matrix intentionally records partial/blocked Windows/macOS e2e gaps instead of claiming full coverage where the repo cannot currently run it.
166 lines
5.6 KiB
Python
166 lines
5.6 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import time
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
pytest.importorskip("fastapi")
|
|
pytest.importorskip("headroom._core")
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
from headroom.config import TransformResult
|
|
from headroom.proxy.server import ProxyConfig, create_app
|
|
|
|
|
|
def _proxy_config(**overrides: Any) -> ProxyConfig:
|
|
defaults: dict[str, Any] = {
|
|
"optimize": True,
|
|
"cache_enabled": False,
|
|
"rate_limit_enabled": False,
|
|
"cost_tracking_enabled": False,
|
|
"log_requests": False,
|
|
"ccr_inject_tool": False,
|
|
"ccr_handle_responses": False,
|
|
"ccr_context_tracking": False,
|
|
"image_optimize": False,
|
|
"disable_kompress": True,
|
|
"compression_max_workers": 1,
|
|
}
|
|
defaults.update(overrides)
|
|
return ProxyConfig(**defaults)
|
|
|
|
|
|
def test_proxy_health_surfaces_compression_runtime_metrics(monkeypatch) -> None:
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
app = create_app(_proxy_config(optimize=False))
|
|
|
|
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345)) as client:
|
|
live = client.get("/livez")
|
|
health = client.get("/health")
|
|
|
|
assert live.status_code == 200
|
|
assert live.json()["alive"] is True
|
|
assert health.status_code == 200
|
|
runtime = health.json()["runtime"]
|
|
assert runtime["compression_executor"]["max_workers"] == 1
|
|
assert runtime["compression_executor"]["queued"] == 0
|
|
assert runtime["compression_executor"]["queue_timeouts_total"] == 0
|
|
|
|
|
|
def test_v1_compress_success_reports_actual_metrics(monkeypatch) -> None:
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
app = create_app(_proxy_config())
|
|
proxy = app.state.proxy
|
|
request_messages = [{"role": "user", "content": "summarize this repeated payload"}]
|
|
compressed_messages = [{"role": "user", "content": "summary payload"}]
|
|
|
|
def fake_apply(**kwargs):
|
|
assert kwargs["messages"] == request_messages
|
|
assert kwargs["model"] == "gpt-4o"
|
|
return TransformResult(
|
|
messages=compressed_messages,
|
|
tokens_before=100,
|
|
tokens_after=40,
|
|
transforms_applied=["test:compress"],
|
|
markers_inserted=["marker-1"],
|
|
)
|
|
|
|
monkeypatch.setattr(proxy.openai_pipeline, "apply", fake_apply)
|
|
|
|
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345)) as client:
|
|
response = client.post(
|
|
"/v1/compress",
|
|
json={"model": "gpt-4o", "messages": request_messages},
|
|
)
|
|
|
|
body = response.json()
|
|
assert response.status_code == 200
|
|
assert body["messages"] == compressed_messages
|
|
assert body["tokens_before"] == 100
|
|
assert body["tokens_after"] == 40
|
|
assert body["tokens_saved"] == 60
|
|
assert body["compression_ratio"] == 0.4
|
|
assert body["transforms_applied"] == ["test:compress"]
|
|
assert body["transforms_summary"] == {"test:compress": 1}
|
|
assert body["ccr_hashes"] == ["marker-1"]
|
|
|
|
|
|
def test_v1_compress_timeout_fails_open_quickly(monkeypatch) -> None:
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
app = create_app(_proxy_config())
|
|
proxy = app.state.proxy
|
|
request_messages = [{"role": "user", "content": "do not mutate me"}]
|
|
|
|
async def timeout_executor(fn, *, timeout): # noqa: ANN001
|
|
raise TimeoutError("compression deadline exceeded")
|
|
|
|
monkeypatch.setattr(proxy, "_run_compression_in_executor", timeout_executor)
|
|
|
|
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345)) as client:
|
|
started = time.perf_counter()
|
|
response = client.post(
|
|
"/v1/compress",
|
|
json={"model": "gpt-4o", "messages": request_messages},
|
|
)
|
|
elapsed = time.perf_counter() - started
|
|
|
|
body = response.json()
|
|
assert response.status_code == 200
|
|
assert elapsed < 0.5
|
|
assert body["messages"] == request_messages
|
|
assert body["tokens_saved"] == 0
|
|
assert body["compression_ratio"] == 1.0
|
|
assert body["transforms_applied"] == []
|
|
assert body["compression_skipped"] is True
|
|
assert body["skip_reason"] == "compression_timeout"
|
|
|
|
|
|
def test_v1_compress_real_json_tool_payload_reduces_tokens(monkeypatch) -> None:
|
|
monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
|
|
app = create_app(
|
|
_proxy_config(
|
|
ccr_inject_marker=False,
|
|
min_tokens_to_crush=20,
|
|
max_items_after_crush=10,
|
|
)
|
|
)
|
|
items = [
|
|
{
|
|
"id": i,
|
|
"status": "ok",
|
|
"score": i % 5,
|
|
"message": "same repeated value " * 20,
|
|
}
|
|
for i in range(80)
|
|
]
|
|
request = {
|
|
"model": "gpt-4o",
|
|
"messages": [
|
|
{"role": "user", "content": "summarize rows"},
|
|
{
|
|
"role": "assistant",
|
|
"content": None,
|
|
"tool_calls": [
|
|
{
|
|
"id": "call-1",
|
|
"type": "function",
|
|
"function": {"name": "list_rows", "arguments": "{}"},
|
|
}
|
|
],
|
|
},
|
|
{"role": "tool", "tool_call_id": "call-1", "content": json.dumps(items)},
|
|
],
|
|
}
|
|
|
|
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345)) as client:
|
|
response = client.post("/v1/compress", json=request)
|
|
|
|
body = response.json()
|
|
assert response.status_code == 200, response.text
|
|
assert body["tokens_before"] > body["tokens_after"], body
|
|
assert body["tokens_saved"] > 0
|
|
assert body["compression_ratio"] < 1.0
|
|
assert body["transforms_applied"], body
|