mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
refactor: remove write-only and test-only code in subscription and install (#4123)
## Description This PR removes private code in `subscription/` and `install/` that nothing reads. - `subscription/tracker.py`: `_PERSIST_FILE_ENV`, `_DEFAULT_PERSIST_DIR` and `_DEFAULT_PERSIST_FILE` are left over from before the path moved to `paths.subscription_state_path()`. `_full_tokens` was a counter that was written on every request and never read. It also kept an 8-character OAuth token prefix in memory. - `install/runtime.py`: `_process_matches_runtime` was a test-only wrapper for `_process_identity(...) is True`. Product code calls `_process_identity` directly. Evidence: `rg -n '<name>' headroom tests crates plugins sdk examples benchmarks scripts e2e docs wiki .github pyproject.toml` and the same search over the consumer repos find only the definitions, plus the tests changed here. No `getattr` string spelling exists for any of them. Refs #4136 ## Type of Change - [ ] 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) - [ ] Documentation update - [ ] Performance improvement - [x] Code refactoring (no functional changes) ## Changes Made - `headroom/subscription/tracker.py`: remove the three persist constants and `_full_tokens`. - `headroom/install/runtime.py`: remove `_process_matches_runtime`. - `tests/test_install/test_runtime.py`: the six asserts now check `_process_identity(...) is True` or `is False` directly. - `tests/test_subscription_tracker.py`: drop the one assert on `_full_tokens`. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text $ pytest -q -p no:cacheprovider tests/test_subscription_tracker.py tests/test_install/test_runtime.py tests/test_network_diff_capture.py tests/test_subscription_window_render.py tests/test_subscription_poll_credential_policy.py tests/test_stateless_no_disk.py tests/test_cli_learn.py # on origin/main (a9815bbb): 176 passed, 1 warning in 9.92s # on this branch: 176 passed, 1 warning in 9.52s $ uvx ruff@0.16.8 check <4 touched files> All checks passed! $ mypy headroom/subscription/tracker.py headroom/install/runtime.py --ignore-missing-imports Success: no issues found in 2 source files ``` ## Real Behavior Proof - Environment: macOS, Python 3.12, repo `.venv`, this branch's worktree. Temp `HOME`, `HEADROOM_WORKSPACE_DIR` and `CODEX_HOME`; nothing touched the real home. - Exact command / steps: 1. Shared smoke harness: a real proxy from this checkout against a local fake upstream, with one Anthropic and one OpenAI request carrying a compressible tool result (`smoke.sh <worktree>`). 2. Lifecycle path that the removed wrapper used to front: saved a `persistent-task` manifest whose `runner.pid` holds the PID of an unrelated live process (`sleep 300`), then ran the real CLI `headroom install status --profile rt`. `runtime_status` goes through `_process_identity`, which rejects the PID. 3. Tracker path: `SubscriptionTracker().notify_active("Bearer oauth-token-123", from_local_operator=True)`. - Observed result: ```text branch: cleanup/cli-integrations-dead-subscription-install-capture @06377018health: 200 POST /v1/messages -> HTTP200 smoke-ok POST /v1/chat/completions -> HTTP200 smoke-ok stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82 proxy.log WARNING/ERROR lines ($SMOKE/ws/logs/proxy-50694.log): 2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes. 4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base 4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection. (smoke dir: $SMOKE) ``` ```text # runner.pid holds the PID of an unrelated live process (sleep 300) $ headroom install status --profile rt Profile: rt Preset: persistent-task Runtime: python Supervisor: none Scope: user Port: 18999 Status: stopped Healthy: no exit=0 sleep still alive (status never signalled it) $ python -c "...notify_active('Bearer oauth-token-123', from_local_operator=True)..." active: True | token prefix counter present: False ``` - Not tested: a live persistent install under launchd/systemd; this PR deletes only private names, and `_process_identity` itself is unchanged. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A; dead-code removal. - Stable/default behavior changed: No. - Kill switch / disable path: N/A. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert this commit. ## 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 - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [ ] 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 (a CI guard enforces this) ## Screenshots (if applicable) N/A ## Additional Notes Part of maintainer-requested cleanup #4136 (dead code, duplication, debuggability), split into small PRs for review. Left for the maintainer: public dataclass field. `CapturedExchange.request_body_preview` in `headroom/capture/network_diff.py` is filled for every captured exchange (by `_preview_body`, capped at `MAX_BODY_PREVIEW_CHARS`) and never read; `CaptureDiff.to_dict` does not serialize exchanges. `CapturedExchange` is in `headroom.capture.__all__`, so the field and the code that fills it stay unchanged here. `SubscriptionTracker.latest_snapshot` is used only by tests, but it stays: it is a public property, and removing it was optional. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
9266b0300d
commit
c191beef59
@@ -369,11 +369,6 @@ def _proxy_deployment_markers_match(cmdline: list[str], manifest: DeploymentMani
|
||||
return True
|
||||
|
||||
|
||||
def _process_matches_runtime(pid: int, manifest: DeploymentManifest) -> bool:
|
||||
"""Verify the PID's deployment identity before lifecycle operations."""
|
||||
return _process_identity(pid, manifest) is True
|
||||
|
||||
|
||||
def _process_identity(pid: int, manifest: DeploymentManifest) -> bool | None:
|
||||
"""Return whether a PID matches, or ``None`` when identity is unavailable."""
|
||||
if pid == os.getpid():
|
||||
|
||||
@@ -49,9 +49,6 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULT_POLL_INTERVAL_S = 300
|
||||
_DEFAULT_ACTIVE_WINDOW_S = 60
|
||||
_PERSIST_FILE_ENV = _paths.HEADROOM_SUBSCRIPTION_STATE_PATH_ENV
|
||||
_DEFAULT_PERSIST_DIR = ".headroom"
|
||||
_DEFAULT_PERSIST_FILE = "subscription_state.json"
|
||||
|
||||
# Singleton on-demand poll floor (seconds): the dashboard may request a fresh
|
||||
# poll if the cached snapshot is stale, but we cap how often we will actually
|
||||
@@ -127,7 +124,6 @@ class SubscriptionTracker(QuotaTracker):
|
||||
self._lock = threading.Lock()
|
||||
self._state = SubscriptionState()
|
||||
self._current_token: str | None = None
|
||||
self._full_tokens: dict[str, int] = {} # token_prefix -> count of requests
|
||||
|
||||
self._stop_event: asyncio.Event | None = None
|
||||
self._poll_task: asyncio.Task[None] | None = None
|
||||
@@ -200,8 +196,6 @@ class SubscriptionTracker(QuotaTracker):
|
||||
if not from_local_operator:
|
||||
return
|
||||
self._current_token = raw
|
||||
prefix = raw[:8]
|
||||
self._full_tokens[prefix] = self._full_tokens.get(prefix, 0) + 1
|
||||
|
||||
def update_contribution(
|
||||
self,
|
||||
|
||||
@@ -15,7 +15,6 @@ from headroom.install.runtime import (
|
||||
_deployment_env,
|
||||
_mount_source,
|
||||
_process_identity,
|
||||
_process_matches_runtime,
|
||||
_read_pid,
|
||||
_runtime_env,
|
||||
_write_pid,
|
||||
@@ -847,7 +846,7 @@ def test_process_identity_must_match_headroom_command(monkeypatch) -> None:
|
||||
}
|
||||
|
||||
monkeypatch.setitem(sys.modules, "psutil", types.SimpleNamespace(Process=FakeProcess))
|
||||
assert not _process_matches_runtime(4321, _python_service_manifest())
|
||||
assert _process_identity(4321, _python_service_manifest()) is False
|
||||
|
||||
class MatchingProcess(FakeProcess):
|
||||
def cmdline(self) -> list[str]:
|
||||
@@ -860,7 +859,7 @@ def test_process_identity_must_match_headroom_command(monkeypatch) -> None:
|
||||
}
|
||||
|
||||
monkeypatch.setitem(sys.modules, "psutil", types.SimpleNamespace(Process=MatchingProcess))
|
||||
assert _process_matches_runtime(4321, _python_service_manifest())
|
||||
assert _process_identity(4321, _python_service_manifest()) is True
|
||||
|
||||
|
||||
def test_process_identity_falls_back_without_psutil(monkeypatch) -> None:
|
||||
@@ -876,7 +875,7 @@ def test_process_identity_falls_back_without_psutil(monkeypatch) -> None:
|
||||
),
|
||||
)
|
||||
monkeypatch.setitem(sys.modules, "psutil", None)
|
||||
assert _process_matches_runtime(4321, manifest)
|
||||
assert _process_identity(4321, manifest) is True
|
||||
|
||||
|
||||
def test_process_identity_uses_macos_ps_fallback_without_psutil(monkeypatch) -> None:
|
||||
@@ -893,7 +892,7 @@ def test_process_identity_uses_macos_ps_fallback_without_psutil(monkeypatch) ->
|
||||
)
|
||||
|
||||
monkeypatch.setattr("headroom.install.runtime.run", lambda *a, **k: Result())
|
||||
assert _process_matches_runtime(4321, manifest)
|
||||
assert _process_identity(4321, manifest) is True
|
||||
|
||||
|
||||
def test_process_identity_uses_windows_wmi_command_line_without_psutil(monkeypatch) -> None:
|
||||
@@ -914,7 +913,7 @@ def test_process_identity_uses_windows_wmi_command_line_without_psutil(monkeypat
|
||||
lambda command, **kwargs: calls.append(command) or Result(),
|
||||
)
|
||||
|
||||
assert _process_matches_runtime(4321, manifest)
|
||||
assert _process_identity(4321, manifest) is True
|
||||
assert calls[0][:3] == ["powershell.exe", "-NoProfile", "-NonInteractive"]
|
||||
|
||||
|
||||
@@ -1010,7 +1009,7 @@ def test_runtime_status_does_not_use_ready_probe_for_failed_identity(
|
||||
|
||||
def test_process_identity_rejects_current_pid(monkeypatch) -> None:
|
||||
monkeypatch.setattr("headroom.install.runtime.os.getpid", lambda: 4321)
|
||||
assert not _process_matches_runtime(4321, _python_service_manifest())
|
||||
assert _process_identity(4321, _python_service_manifest()) is False
|
||||
|
||||
|
||||
def test_darwin_task_preserves_popen_path(monkeypatch, tmp_path: Path) -> None:
|
||||
|
||||
@@ -59,7 +59,6 @@ def test_tracker_notify_active_update_and_basic_state(monkeypatch: pytest.Monkey
|
||||
|
||||
tracker.notify_active("Bearer oauth-token-123", from_local_operator=True)
|
||||
assert tracker._current_token == "oauth-token-123"
|
||||
assert tracker._full_tokens["oauth-to"] == 1
|
||||
assert tracker.is_active() is True
|
||||
|
||||
tracker.update_contribution(
|
||||
|
||||
Reference in New Issue
Block a user