Files
headroom/tests/test_provider_codex_model_metadata.py
Tejas ChopraandClaude Opus 5.5 688b327039 chore(providers): remove dead provider and model helpers (#4078)
## Description

This PR removes provider and model helpers that nothing calls. Two of
them were reached only by tests. For one of those, the test is pointed
at the function production actually uses, so the code path keeps its
coverage.

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/models/config.py`: remove `get_default_embedding_model`,
`get_default_embedding_dim`, `get_default_spacy_model`,
`get_default_siglip_model` and `MLModelConfig.total_memory_estimate`.
Callers read `ML_MODEL_DEFAULTS.<field>` directly, and none of these is
in the `headroom.models` lazy export map.
- `headroom/providers/opencode/config.py`:
  - Remove `_render_provider_block`.
- Remove `_opencode_home_dir`. `OPENCODE_HOME` is resolved by
`headroom.install.paths.opencode_config_path` and by
`context_tool_cleanup._opencode_home`.
- Remove `append_headroom_plugin` and its two tests. The live plugin
wiring is in `opencode/runtime.py`.
- `headroom/providers/litellm.py`: drop the unused `from litellm import
model_cost as litellm_model_cost` and its `None` fallback.
- `headroom/providers/codex/model_metadata.py`: remove the test-only
`fetch_chatgpt_codex_model_ids` wrapper. Its test now calls
`fetch_chatgpt_codex_model_entries`, which is what production uses, and
checks the same slugs and the same request.
- Evidence: a word search (`rg -c -w <name>`) across the repo (code,
tests, docs, wiki, CI, pyproject) and the private consumer repos finds
only each definition, plus tests for the two test-only helpers.

## 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 tests/test_providers_opencode_config.py tests/test_cli/test_wrap_opencode.py tests/test_providers_opencode_install.py tests/test_provider_codex_model_metadata.py tests/test_providers/test_universal.py tests/test_ml_model_registry_lifecycle.py tests/test_startup_log_noise.py tests/test_install/test_paths.py
239 passed, 1 warning in 14.22s
$ pytest -q tests/test_paths_backward_compat.py tests/test_paths.py tests/test_provider_codex_runtime.py tests/test_models.py
120 passed in 5.38s
$ ruff check (touched files)
All checks passed!
$ mypy headroom/models/config.py headroom/providers/opencode/config.py headroom/providers/codex/model_metadata.py headroom/providers/litellm.py --ignore-missing-imports
Success: no issues found in 4 source files
```

## Real Behavior Proof

- Environment: macOS, repo venv, branch checkout at 91e11e40, temp HOME
/ HEADROOM_WORKSPACE_DIR / CODEX_HOME, offline.
- Exact command / steps: (1) shared smoke harness: start a real proxy
from this checkout against a local fake upstream and send one Anthropic
and one OpenAI request with a compressible tool result; (2) under a temp
HOME, run the OpenCode config injection that `headroom wrap opencode`
uses (the live code left in `opencode/config.py`) and print the written
config, plus the `ML_MODEL_DEFAULTS` fields that replace the removed
`get_default_*` accessors.
- Observed result: smoke requests return HTTP 200 with savings; the
injection writes `~/.config/opencode/opencode.json` (the
`OPENCODE_HOME`/default path resolved by `install.paths`) with the
Headroom provider at `http://127.0.0.1:8787/v1`; `ML_MODEL_DEFAULTS`
reports the default embedding model and dimension.
- Not tested: launching the real OpenCode binary (not installed here)
and a live ChatGPT Codex model-registry fetch.

```text
$ bash smoke.sh <worktree>
branch: cleanup/providers-evals-dead-provider-helpers @ 91e11e40
health: 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:
   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.

$ HOME=$(mktemp -d) python -c "inject_opencode_provider_config(8787); print(opencode_config_path().read_text()); print(ML_MODEL_DEFAULTS...)"
.config/opencode/opencode.json
{
  "provider": {
    "headroom": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Headroom Proxy",
      "options": {
        "baseURL": "http://127.0.0.1:8787/v1"
      },
      "models": { "gpt-4o": {...}, "gpt-4.1": {...} }
    }
  }
}
embedding model: all-MiniLM-L6-v2 384
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A, dead code only.
- 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.

A second, equally unused `_opencode_home_dir` in `headroom/cli/wrap.py`
is being removed in a separate CLI cleanup branch. Neither copy had a
caller. No documentation referenced any removed name.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 08:57:09 -07:00

164 lines
5.1 KiB
Python

import base64
import json
import httpx
import pytest
from headroom.providers.codex import (
CodexRoutingDecision as ExportedCodexRoutingDecision,
)
from headroom.providers.codex import (
resolve_codex_routing as exported_resolve_codex_routing,
)
from headroom.providers.codex.model_metadata import (
codex_model_registry_entry,
fetch_chatgpt_codex_model_entries,
normalize_codex_registry_headers,
synthetic_model_get_response,
synthetic_models_list_response,
)
from headroom.providers.codex.runtime import (
decode_openai_bearer_payload,
resolve_codex_routing,
resolve_codex_routing_headers,
)
def _jwt(payload: dict) -> str:
header = {"alg": "none", "typ": "JWT"}
def encode(part: dict) -> str:
raw = json.dumps(part, separators=(",", ":")).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
return f"{encode(header)}.{encode(payload)}."
def test_codex_runtime_resolves_chatgpt_account_from_openai_oauth_jwt() -> None:
token = _jwt(
{
"https://api.openai.com/auth": {
"chatgpt_account_id": "acct-from-jwt",
}
}
)
payload = decode_openai_bearer_payload({"authorization": f"Bearer {token}"})
headers, is_chatgpt_auth = resolve_codex_routing_headers({"authorization": f"Bearer {token}"})
assert payload == {
"https://api.openai.com/auth": {
"chatgpt_account_id": "acct-from-jwt",
}
}
assert is_chatgpt_auth is True
assert headers["ChatGPT-Account-ID"] == "acct-from-jwt"
def test_codex_runtime_exposes_named_routing_decision() -> None:
decision = resolve_codex_routing({"ChatGPT-Account-ID": "acct-explicit"})
assert decision.is_chatgpt_auth is True
assert decision.headers == {"ChatGPT-Account-ID": "acct-explicit"}
def test_codex_package_exports_routing_decision() -> None:
decision = exported_resolve_codex_routing({"ChatGPT-Account-ID": "acct-root"})
assert isinstance(decision, ExportedCodexRoutingDecision)
assert decision.is_chatgpt_auth is True
assert decision.headers == {"ChatGPT-Account-ID": "acct-root"}
def test_codex_runtime_ignores_malformed_oauth_jwt() -> None:
assert decode_openai_bearer_payload({"authorization": "Bearer header.***.sig"}) is None
headers, is_chatgpt_auth = resolve_codex_routing_headers(
{"authorization": "Bearer header.***.sig"}
)
assert is_chatgpt_auth is False
assert headers == {"authorization": "Bearer header.***.sig"}
def test_codex_registry_headers_normalize_account_and_accept_headers() -> None:
headers = normalize_codex_registry_headers(
{
"Host": "localhost:8787",
"authorization": "Bearer token",
"ChatGPT-Account-ID": "acct",
"Accept": "text/event-stream",
}
)
assert headers == {
"authorization": "Bearer token",
"chatgpt-account-id": "acct",
"accept": "application/json",
}
@pytest.mark.asyncio
async def test_codex_model_registry_fetch_returns_slugs() -> None:
class FakeClient:
def __init__(self) -> None:
self.calls: list[tuple[str, dict[str, str]]] = []
async def get(self, url, **kwargs): # type: ignore[no-untyped-def]
self.calls.append((url, dict(kwargs.get("headers", {}))))
return httpx.Response(
200,
json={"models": [{"slug": "gpt-5.5"}, {"slug": ""}, {"slug": "gpt-5.4"}]},
)
client = FakeClient()
entries = await fetch_chatgpt_codex_model_entries(
client,
{"authorization": "Bearer token", "chatgpt-account-id": "acct"},
"0.135.0",
)
assert entries is not None
assert [entry["slug"] for entry in entries] == ["gpt-5.5", "gpt-5.4"]
assert client.calls == [
(
"https://chatgpt.com/backend-api/codex/models?client_version=0.135.0",
{
"authorization": "Bearer token",
"chatgpt-account-id": "acct",
"accept": "application/json",
},
)
]
def test_codex_synthetic_model_metadata_responses() -> None:
list_payload = json.loads(synthetic_models_list_response().body)
known_payload = json.loads(synthetic_model_get_response("gpt-5.5").body)
unknown = synthetic_model_get_response("gpt-99-future")
assert list_payload["object"] == "list"
assert "gpt-5.5" in {entry["id"] for entry in list_payload["data"]}
assert known_payload == {
"id": "gpt-5.5",
"object": "model",
"created": 0,
"owned_by": "openai",
}
assert unknown.status_code == 404
def test_codex_model_registry_entry_preserves_upstream_fields_and_defaults() -> None:
entry = codex_model_registry_entry(
"gpt-5.3-codex-spark",
{"display_name": "Spark", "context_window": 12345},
)
assert entry["slug"] == "gpt-5.3-codex-spark"
assert entry["display_name"] == "Spark"
assert entry["context_window"] == 12345
assert entry["default_reasoning_level"] == "medium"
assert entry["supports_parallel_tool_calls"] is True
assert entry["supported_in_api"] is True