headroom/tests/test_tokenizers/test_tiktoken_load_timeout.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

82 lines
2.7 KiB
Python
Raw Permalink Normal View History

fix(tokenizers): bound tiktoken vocab load so a stalled download cannot hang requests (#956) (#994) ## Description The #956 symptom — `compression_first_stage` always timing out at ~30s with 0 tokens removed — is not a PyO3/event-loop issue (compression itself runs ~120ms on Python 3.14). Root cause: `tiktoken` downloads its BPE vocab via `requests.get(...)` with no timeout, loaded lazily inside the compression worker (`TiktokenCounter.encoding`, `AnthropicProvider.__init__`). On a firewalled network that blocks indefinitely, so the worker hangs and `asyncio.wait_for` trips at 30s on every request (the hung download never caches, so it repeats). Refs #956 (runtime half). ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - Load the encoding on a worker thread bounded by `HEADROOM_TIKTOKEN_LOAD_TIMEOUT_SECONDS` (default 10s); on timeout raise `TiktokenLoadError` and fall back to estimation (registry -> EstimatingTokenCounter; Anthropic provider -> character estimate). - Remember the first timed-out encoding so later requests fail fast instead of re-blocking. ## Testing - [x] Unit tests pass (`pytest`) - [x] New tests added for new functionality ### Test Output ```text $ pytest tests/test_tokenizers/test_tiktoken_load_timeout.py -q 4 passed in 0.69s ``` ## Real Behavior Proof - Environment: Linux, Python 3.14 and 3.13 - Exact command / steps: timed the Rust compression call sync / via run_in_executor / 2x concurrent on both interpreters; ran the bounded-loader tests against a simulated stalled get_encoding - Observed result: compression ~118-120ms on both 3.14 and 3.13 (no event-loop block); the bounded loader raises/falls back within the timeout instead of hanging - Not tested: the real firewalled-network stall (could not reproduce on an unfirewalled host); the no-timeout requests.get is confirmed in tiktoken's source ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 12:27:09 -04:00
"""tiktoken vocab loading must be bounded (GH #956).
tiktoken downloads its BPE vocab via ``requests.get`` with no timeout, so a
stalled/firewalled connection blocks indefinitely. The proxy calls this lazily
inside a request worker, so the only bound was the 30s compression timeout
yielding "every request times out, 0 compression". The bounded loader caps the
wait and falls back to estimation instead.
"""
from __future__ import annotations
import time
import pytest
from headroom.tokenizers import tiktoken_counter as tc
from headroom.tokenizers.estimator import EstimatingTokenCounter
from headroom.tokenizers.registry import TokenizerRegistry
@pytest.fixture(autouse=True)
def _reset_encoding_state():
tc._get_encoding.cache_clear()
tc._load_failed.clear()
yield
tc._get_encoding.cache_clear()
tc._load_failed.clear()
def _stalled_get_encoding(_name: str):
# Simulates tiktoken's unbounded network download stalling.
time.sleep(2.0)
return object()
def test_load_encoding_is_bounded_on_stall(monkeypatch: pytest.MonkeyPatch) -> None:
import tiktoken
monkeypatch.setattr(tiktoken, "get_encoding", _stalled_get_encoding)
monkeypatch.setenv("HEADROOM_TIKTOKEN_LOAD_TIMEOUT_SECONDS", "0.2")
start = time.perf_counter()
with pytest.raises(tc.TiktokenLoadError):
tc.load_encoding("stall-enc")
elapsed = time.perf_counter() - start
assert elapsed < 1.5, f"load was not bounded (took {elapsed:.2f}s vs the 2s stall)"
def test_failed_encoding_short_circuits(monkeypatch: pytest.MonkeyPatch) -> None:
import tiktoken
monkeypatch.setattr(tiktoken, "get_encoding", _stalled_get_encoding)
monkeypatch.setenv("HEADROOM_TIKTOKEN_LOAD_TIMEOUT_SECONDS", "0.2")
with pytest.raises(tc.TiktokenLoadError):
tc.load_encoding("stall-enc-2")
# A second request must fail instantly via the _load_failed short-circuit,
# not wait out the timeout again (this is what makes it not "every request").
start = time.perf_counter()
with pytest.raises(tc.TiktokenLoadError):
tc.load_encoding("stall-enc-2")
assert time.perf_counter() - start < 0.1
def test_fast_load_returns_encoding(monkeypatch: pytest.MonkeyPatch) -> None:
import tiktoken
sentinel = object()
monkeypatch.setattr(tiktoken, "get_encoding", lambda _name: sentinel)
assert tc.load_encoding("fast-enc") is sentinel
def test_registry_falls_back_to_estimator_on_stall(monkeypatch: pytest.MonkeyPatch) -> None:
import tiktoken
monkeypatch.setattr(tiktoken, "get_encoding", _stalled_get_encoding)
monkeypatch.setenv("HEADROOM_TIKTOKEN_LOAD_TIMEOUT_SECONDS", "0.2")
counter = TokenizerRegistry()._create_tiktoken("gpt-4")
assert isinstance(counter, EstimatingTokenCounter)