headroom/tests/test_platform_feature_matrix.py
JD Davis 1d2b76e72e
fix: harden persistent install startup (#1851)
## 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.
2026-07-10 00:40:34 -04:00

70 lines
2.7 KiB
Python

from __future__ import annotations
import json
from pathlib import Path
MATRIX_PATH = Path("docs/platform-feature-matrix.json")
VALID_STATUSES = {"covered", "partial", "gap", "blocked"}
PLATFORMS = {"linux", "macos", "windows"}
def test_platform_feature_matrix_is_complete() -> None:
matrix = json.loads(MATRIX_PATH.read_text(encoding="utf-8"))
assert matrix["schema_version"] == 1
assert set(matrix["platforms"]) == PLATFORMS
assert set(matrix["status_values"]) == VALID_STATUSES
assert matrix["features"], "matrix must list hardening features"
feature_ids: set[str] = set()
for feature in matrix["features"]:
feature_id = feature["id"]
assert feature_id not in feature_ids, f"duplicate feature id: {feature_id}"
feature_ids.add(feature_id)
assert feature["name"]
assert feature["risk"] in {"install", "runtime", "performance", "cache", "proxy"}
assert set(feature["platforms"]) == PLATFORMS
for platform, coverage in feature["platforms"].items():
status = coverage["status"]
assert status in VALID_STATUSES, f"{feature_id}/{platform} has invalid status"
assert coverage["tests"], f"{feature_id}/{platform} must cite tests or workflows"
for test_ref in coverage["tests"]:
path = Path(test_ref.split("#", 1)[0])
assert path.exists(), f"{feature_id}/{platform} cites missing path {test_ref}"
if status in {"partial", "gap", "blocked"}:
assert coverage.get("gap"), f"{feature_id}/{platform} must explain {status}"
def test_platform_feature_matrix_covers_issue_1843_regression_areas() -> None:
matrix = json.loads(MATRIX_PATH.read_text(encoding="utf-8"))
feature_ids = {feature["id"] for feature in matrix["features"]}
assert {
"install_windows_service",
"single_instance_start",
"compression_fail_open",
"proxy_functional_smoke",
"ccr_persistence",
"toin_skip_recommendations",
} <= feature_ids
def test_platform_feature_matrix_sanity_tests_are_enumerated() -> None:
matrix = json.loads(MATRIX_PATH.read_text(encoding="utf-8"))
sanity_ids = {item["id"] for item in matrix["sanity_tests"]}
assert {
"cli_help",
"install_paths",
"runtime_selection",
"health_startup",
"compression_backpressure",
"proxy_route_smoke",
} <= sanity_ids
for item in matrix["sanity_tests"]:
assert item["description"]
assert item["tests"]
for test_ref in item["tests"]:
path = Path(test_ref.split("#", 1)[0])
assert path.exists(), f"{item['id']} cites missing path {test_ref}"