headroom/tests/test_huggingface_tokenizer_timeout.py
Rod Boev 551f473e04
fix(proxy): accept Codex websocket before upstream retries (#2203)
## Description

Codex Desktop could abandon Headroom's local `/v1/responses` WebSocket
handshake before Headroom's upstream retry strategy had a chance to
recover. The ChatGPT-auth path waited for an upstream opening handshake
with a minimum 30-second timeout before sending the local 101, while the
reported Codex Desktop handshake expired after about 34 seconds.

This change accepts validated ChatGPT-auth Codex WebSockets before
opening the upstream connection, then keeps the existing upstream
retries and HTTP fallback behind the established local session. API-key
sessions retain connect-before-accept behavior so upstream `x-codex-*`
headers can still be attached to their client-facing 101. The change is
scoped to the pre-101 timing failure and does not address the separate
large-context streaming investigation in #1944.

Closes #2184

## 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)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Accept ChatGPT-auth Codex WebSocket clients before the upstream
connect and retry loop.
- Preserve API-key connect-before-accept ordering and upstream
`x-codex-*` handshake-header forwarding.
- Keep upstream retry, relay, usage-state refresh, and WebSocket-to-HTTP
fallback behavior after the local 101.
- Add a deterministic regression that blocks the first upstream opening
handshake and proves the local acceptance deadline is independent of it.

## Testing

- [x] Unit tests pass (`uv run pytest
tests/test_openai_codex_ws_lifecycle.py -q`)
- [x] Linting passes (`uv run ruff check
headroom/proxy/handlers/openai.py
tests/test_openai_codex_ws_lifecycle.py`)
- [ ] Type checking passes (`uv run mypy headroom`)
- [x] New tests added for new functionality when applicable
- [ ] Manual testing performed

### Test Output

```text
uv run pytest tests/test_openai_codex_ws_lifecycle.py -q
28 passed in 2.02s
uv run ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py
All checks passed!
uv run ruff format headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py --check
2 files already formatted
```

## Real Behavior Proof

- Environment: Python 3.12, synced development worktree, local fake
Codex client and upstream WebSocket, no live provider
- Exact command / steps: Run `uv run pytest
tests/test_openai_codex_ws_lifecycle.py::test_chatgpt_ws_accepts_before_stalled_upstream_connect
-q`; the fake upstream blocks its first opening handshake while the
client enforces a bounded local-accept deadline.
- Observed result: `1 passed in 0.46s`; the ChatGPT-auth client receives
its local 101 before the blocked upstream connect is released, and the
handler continues into its existing upstream recovery path.
- Not tested: live Codex Desktop pre-turn compaction against ChatGPT
subscription infrastructure

## 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
- [ ] 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
- [x] I have updated the CHANGELOG.md if applicable

## Additional Notes

`CHANGELOG.md` is unchanged because the release pipeline generates it
from conventional commits. No user documentation changes are required;
the handler comments and ordered-flow docstring are updated with the
auth-mode-specific behavior. The broader #1944 large-context disconnect
surface remains out of scope.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-15 18:18:06 +00:00

144 lines
5.8 KiB
Python

"""HF tokenizer loading must be bounded (GH #1701): AutoTokenizer.from_pretrained
performs unbounded network downloads/retries; called lazily from the proxy's request
path it blocked the event loop for ~10 minutes and zombified the server. The fix
tries the local HF cache first (local_files_only=True), bounds the network attempt
with HEADROOM_HF_TOKENIZER_LOAD_TIMEOUT_SECS on a daemon thread, and fails open to
estimation — caching the failure so the hub is probed at most once per process.
"""
from __future__ import annotations
import sys
import time
import types
from typing import Any
import pytest
from headroom.tokenizers import huggingface as hf_mod
from headroom.tokenizers.huggingface import (
HuggingFaceTokenizer,
_load_tokenizer,
get_tokenizer_name,
)
@pytest.fixture(autouse=True)
def _fresh_cache():
_load_tokenizer.cache_clear()
yield
_load_tokenizer.cache_clear()
def _install_fake_transformers(monkeypatch: pytest.MonkeyPatch, from_pretrained) -> None:
fake = types.ModuleType("transformers")
fake.AutoTokenizer = type(
"AutoTokenizer", (), {"from_pretrained": staticmethod(from_pretrained)}
)
monkeypatch.setitem(sys.modules, "transformers", fake)
def test_local_cache_tried_before_network(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[dict[str, Any]] = []
def fake_from_pretrained(name: str, **kwargs: Any):
calls.append(kwargs)
if kwargs.get("local_files_only"):
raise OSError("not in cache")
return "network-tokenizer"
_install_fake_transformers(monkeypatch, fake_from_pretrained)
monkeypatch.setenv("HEADROOM_HF_TOKENIZER_LOAD_TIMEOUT_SECS", "5")
assert _load_tokenizer("some/model") == "network-tokenizer"
assert calls[0].get("local_files_only") is True, "first attempt must be cache-only"
assert not calls[1].get("local_files_only")
def test_cache_hit_never_touches_network(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[dict[str, Any]] = []
def fake_from_pretrained(name: str, **kwargs: Any):
calls.append(kwargs)
return "cached-tokenizer"
_install_fake_transformers(monkeypatch, fake_from_pretrained)
assert _load_tokenizer("some/model") == "cached-tokenizer"
assert len(calls) == 1
assert calls[0].get("local_files_only") is True
def test_slow_network_load_times_out_and_fails_open(monkeypatch: pytest.MonkeyPatch) -> None:
def fake_from_pretrained(name: str, **kwargs: Any):
if kwargs.get("local_files_only"):
raise OSError("not in cache")
time.sleep(60) # simulates hung huggingface_hub download
return "never"
_install_fake_transformers(monkeypatch, fake_from_pretrained)
monkeypatch.setenv("HEADROOM_HF_TOKENIZER_LOAD_TIMEOUT_SECS", "0.2")
start = time.monotonic()
assert _load_tokenizer("slow/model") is None
assert time.monotonic() - start < 5, "load must unblock at the timeout, not the download"
# Failure is cached (lru_cache) — the second call must not re-probe the hub.
start = time.monotonic()
assert _load_tokenizer("slow/model") is None
assert time.monotonic() - start < 0.05
def test_timeout_zero_disables_network_loading(monkeypatch: pytest.MonkeyPatch) -> None:
def fake_from_pretrained(name: str, **kwargs: Any):
if kwargs.get("local_files_only"):
raise OSError("not in cache")
raise AssertionError("network load attempted despite timeout=0")
_install_fake_transformers(monkeypatch, fake_from_pretrained)
monkeypatch.setenv("HEADROOM_HF_TOKENIZER_LOAD_TIMEOUT_SECS", "0")
assert _load_tokenizer("offline/model") is None
def test_count_messages_fails_open_to_estimation(monkeypatch: pytest.MonkeyPatch) -> None:
def fake_from_pretrained(name: str, **kwargs: Any):
raise OSError("unavailable")
_install_fake_transformers(monkeypatch, fake_from_pretrained)
monkeypatch.setenv("HEADROOM_HF_TOKENIZER_LOAD_TIMEOUT_SECS", "0.2")
counter = HuggingFaceTokenizer("deepseek-chat")
tokens = counter.count_messages([{"role": "user", "content": "hello world" * 50}])
assert tokens > 0 # estimation fallback, no exception, no hang
def test_deepseek_model_aliases_resolve_to_expected_tokenizers() -> None:
assert get_tokenizer_name("deepseek-v3.2") == "deepseek-ai/DeepSeek-V3.2"
assert get_tokenizer_name("deepseek-v4-pro") == "deepseek-ai/DeepSeek-V4-Pro"
assert get_tokenizer_name("deepseek-v4-flash") == "deepseek-ai/DeepSeek-V4-Flash"
assert get_tokenizer_name("deepseek-r1") == "deepseek-ai/DeepSeek-R1"
assert get_tokenizer_name("deepseek-r1-0528") == "deepseek-ai/DeepSeek-R1-0528"
def test_invalid_timeout_env_falls_back_to_default(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("HEADROOM_HF_TOKENIZER_LOAD_TIMEOUT_SECS", "not-a-number")
assert hf_mod._load_timeout_secs() == hf_mod._LOAD_TIMEOUT_DEFAULT
def test_get_tokenizer_name_prefers_most_specific_prefix() -> None:
"""A more-specific family key must win over a shorter one.
Prefix matching used to scan MODEL_TO_TOKENIZER in dict-insertion order, so
the short "qwen" key preceded "qwen2"/"qwen2.5" and shadowed them —
"qwen2-7b-instruct" resolved to the Qwen1 tokenizer (a different vocabulary,
hence wrong counts). The resolver now picks the longest matching prefix.
"""
# Versioned models not present as literal keys must hit the right family.
assert get_tokenizer_name("qwen2-7b-instruct") == "Qwen/Qwen2-7B"
assert get_tokenizer_name("qwen2.5-turbo") == "Qwen/Qwen2.5-7B"
assert get_tokenizer_name("deepseek-v2.5") == "deepseek-ai/DeepSeek-V2"
# Direct hits and shorter family fallbacks still resolve through their
# longest matching tokenizer aliases.
assert get_tokenizer_name("qwen-14b") == "Qwen/Qwen-14B"
assert get_tokenizer_name("deepseek-chat") == "deepseek-ai/DeepSeek-V3"