mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 11:31:17 +08:00
## Description Three LiteLLM lookups swallow every exception without leaving a trace: - `OpenAIProvider.get_context_limit` used `except Exception: pass`. - `CohereProvider.get_context_limit` used `except Exception: pass`. - `counterfactual.resolve_rates` used `except Exception: return None`. When a context limit comes out wrong, or a price falls back to list, there was no log line explaining why. Each site now logs one DEBUG line with the model and a payload-safe description of the failure: the exception types and code locations from `headroom.log_safety.describe_exception`, never the exception message or a traceback. LiteLLM's error text can carry backend configuration or credentials, so it is kept out of the log at every level. Return values and control flow are unchanged. 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/providers/openai.py`: `logger.debug(f"LiteLLM get_model_info failed for {safe_id(model)}: {describe_exception(e)}")`, then the existing built-in limit fallback. - `headroom/providers/cohere.py`: the same line for each `model_variant` tried (`cohere/<model>`, then `<model>`), then the existing built-in limit fallback. - `headroom/pricing/counterfactual.py`: `logger.debug("counterfactual: LiteLLM catalog lookup failed for %s: %s", safe_id(model), describe_exception(exc))`, with no `exc_info`. `resolve_rates` is memoized, so this logs at most once per model. - Only the model id (through `safe_id`: repr, capped at 80 characters) and exception types and locations are logged. There are no headers, keys, URLs or exception messages. Exception text appears only with the operator's explicit content opt-in, `HEADROOM_DEBUG_DUMP=full`. - `tests/test_litellm_probe_fallback_logs.py` (new): - Each probe raises an exception chain carrying a credential canary and a content canary. - Every captured record, at all levels, is rendered with `logging.Formatter`, which includes `exc_info`. - The tests assert that neither canary and no traceback appears, that a DEBUG record names the model and the exception type, and that the fallback value is unchanged. - A successful probe logs nothing. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text $ pytest -q tests/test_litellm_probe_fallback_logs.py tests/test_log_safety.py tests/test_providers/test_openai.py tests/test_providers/test_cohere.py tests/test_counterfactual_pricing.py tests/test_startup_log_noise.py tests/test_xai_cache_economics.py tests/test_provider_model_fallback.py tests/test_openai_model_table_resolution.py tests/test_openai_pricing_resolution.py 198 passed, 3 warnings in 10.73s $ pytest -q tests/test_litellm_probe_fallback_logs.py # same tests against the previous commit's product code (scratch worktree) 3 failed (the formatted records contain the credential canary: OpenAI/Cohere in the message, counterfactual in the traceback) $ ruff check / ruff format --check (touched files) All checks passed! 4 files already formatted $ mypy headroom/providers/openai.py headroom/providers/cohere.py headroom/pricing/counterfactual.py --ignore-missing-imports Success: no issues found in 3 source files ``` ## Real Behavior Proof - Environment: macOS, repo venv, branch checkout at7a7f54cf, 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) force the OpenAI, Cohere and counterfactual LiteLLM lookups to raise an error whose text holds a credential, and print the DEBUG records (command below). - Observed result: smoke requests return HTTP 200 with savings and no new warnings; each forced failure logs the model and `RuntimeError at <location>` only, the credential never appears, and the fallbacks are unchanged (128000, 128000, `None`). - Not tested: a real LiteLLM catalog error from the live library; the failure is injected. ```text $ bash smoke.sh <worktree> branch: cleanup/providers-evals-litellm-probe-logs @7a7f54cfhealth: 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. 2 headroom.transforms.kompress_compressor - WARNING - Kompress: 'onnx/kompress-int8-wo.onnx' for chopratejas/kompress-v2-base is not cached and HEADROOM_OFFLINE forbids fetching it (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.). Compression falls back to the non-ML path. 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 "<DEBUG on the three loggers; make get_model_info and model_cost.get raise RuntimeError('catalog error at https://u:sk-canary-123@x.test'); call each lookup>" headroom.providers.openai DEBUG LiteLLM get_model_info failed for 'gpt-4o-2099-01-01': RuntimeError at <string>:7 in boom <- headroom/providers/openai.py:602 in get_context_limit headroom.providers.cohere DEBUG LiteLLM get_model_info failed for 'cohere/command-r': RuntimeError at <string>:7 in boom <- headroom/providers/cohere.py:279 in get_context_limit headroom.providers.cohere DEBUG LiteLLM get_model_info failed for 'command-r': RuntimeError at <string>:7 in boom <- headroom/providers/cohere.py:279 in get_context_limit headroom.pricing.counterfactual DEBUG counterfactual: LiteLLM catalog lookup failed for 'probe-fail-model': RuntimeError at <string>:7 in boom <- headroom/pricing/counterfactual.py:424 in resolve_rates openai context limit: 128000 cohere context limit: 128000 rates: None ``` ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A, debug logging only. - Stable/default behavior changed: No. Only new DEBUG-level lines, hidden at the default log level, and they carry no exception text. - Kill switch / disable path: Log level. These lines are DEBUG only. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert this PR's commits. ## 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 - [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 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. Depends on #4138; its two files show in this diff until it merges. This is a debuggability change, not a bug fix. The earlier version of this PR put LiteLLM's exception text (OpenAI, Cohere) and a traceback (counterfactual) into the DEBUG lines. Review showed a credential in that text reaches the formatted record, so all three sites now use `describe_exception`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
121 lines
4.4 KiB
Python
121 lines
4.4 KiB
Python
"""A failed LiteLLM probe falls back as before and logs the model and failure type only.
|
|
|
|
The probe's exception text comes from LiteLLM and can carry backend configuration or
|
|
credentials, so no log record may contain it, at any level, with or without a traceback.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from collections.abc import Iterator
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
import headroom.pricing.counterfactual as counterfactual
|
|
import headroom.providers.cohere as cohere
|
|
import headroom.providers.openai as openai_provider
|
|
|
|
CREDENTIAL_CANARY = "sk-canary-0123456789abcdef"
|
|
CONTENT_CANARY = "user-prompt-canary-text"
|
|
|
|
# A dated variant is not in the built-in table, so get_context_limit reaches the LiteLLM probe.
|
|
_DATED_GPT4O = "gpt-4o-2099-01-01"
|
|
|
|
|
|
class _Records(logging.Handler):
|
|
def __init__(self) -> None:
|
|
super().__init__(logging.DEBUG)
|
|
self.records: list[logging.LogRecord] = []
|
|
|
|
def emit(self, record: logging.LogRecord) -> None:
|
|
self.records.append(record)
|
|
|
|
def formatted(self) -> list[str]:
|
|
# A real Formatter renders exc_info and stack_info, which getMessage() leaves out.
|
|
formatter = logging.Formatter("%(levelname)s %(name)s %(message)s")
|
|
return [formatter.format(record) for record in self.records]
|
|
|
|
|
|
@pytest.fixture
|
|
def records(monkeypatch: pytest.MonkeyPatch) -> Iterator[_Records]:
|
|
# The content opt-in would put exception text back on purpose; test the default.
|
|
monkeypatch.delenv("HEADROOM_DEBUG_DUMP", raising=False)
|
|
# Attach directly: headroom.* loggers may not propagate to caplog's root handler.
|
|
handler = _Records()
|
|
loggers = [logging.getLogger(m.__name__) for m in (openai_provider, cohere, counterfactual)]
|
|
saved = [lg.level for lg in loggers]
|
|
for lg in loggers:
|
|
lg.addHandler(handler)
|
|
lg.setLevel(logging.DEBUG)
|
|
yield handler
|
|
for lg, level in zip(loggers, saved):
|
|
lg.removeHandler(handler)
|
|
lg.setLevel(level)
|
|
|
|
|
|
def _failing(*_args: object, **_kwargs: object) -> dict[str, object]:
|
|
try:
|
|
raise KeyError(f"api_key={CREDENTIAL_CANARY}")
|
|
except KeyError as cause:
|
|
raise RuntimeError(
|
|
f"catalog error for {CONTENT_CANARY} at https://u:{CREDENTIAL_CANARY}@x.test"
|
|
) from cause
|
|
|
|
|
|
def _assert_safe(records: _Records, model: str) -> None:
|
|
lines = records.formatted()
|
|
for line in lines:
|
|
assert CREDENTIAL_CANARY not in line
|
|
assert CONTENT_CANARY not in line
|
|
assert "Traceback" not in line
|
|
failure_lines = [line for line in lines if "failed for" in line and repr(model) in line]
|
|
assert failure_lines, lines
|
|
assert all("RuntimeError" in line for line in failure_lines)
|
|
|
|
|
|
def test_openai_context_limit_probe_failure_is_logged_safely(
|
|
monkeypatch: pytest.MonkeyPatch, records: _Records
|
|
) -> None:
|
|
provider = openai_provider.OpenAIProvider()
|
|
expected = provider._get_context_limit_manual(_DATED_GPT4O)
|
|
|
|
monkeypatch.setattr(
|
|
openai_provider, "_get_litellm_module", lambda: SimpleNamespace(get_model_info=_failing)
|
|
)
|
|
assert provider.get_context_limit(_DATED_GPT4O) == expected
|
|
_assert_safe(records, _DATED_GPT4O)
|
|
|
|
records.records.clear()
|
|
monkeypatch.setattr(
|
|
openai_provider,
|
|
"_get_litellm_module",
|
|
lambda: SimpleNamespace(get_model_info=lambda m: {"max_input_tokens": 1234}),
|
|
)
|
|
assert provider.get_context_limit(_DATED_GPT4O) == 1234
|
|
assert not [line for line in records.formatted() if "get_model_info failed" in line]
|
|
|
|
|
|
def test_cohere_context_limit_probe_failure_is_logged_safely(
|
|
monkeypatch: pytest.MonkeyPatch, records: _Records
|
|
) -> None:
|
|
monkeypatch.setattr(cohere, "LITELLM_AVAILABLE", True)
|
|
monkeypatch.setattr(cohere, "litellm", SimpleNamespace(get_model_info=_failing), raising=False)
|
|
|
|
assert cohere.CohereProvider().get_context_limit("command-r") == 128000
|
|
_assert_safe(records, "cohere/command-r")
|
|
_assert_safe(records, "command-r")
|
|
|
|
|
|
def test_counterfactual_catalog_failure_is_logged_safely(
|
|
monkeypatch: pytest.MonkeyPatch, records: _Records
|
|
) -> None:
|
|
broken_catalog = SimpleNamespace(model_cost=SimpleNamespace(get=_failing))
|
|
monkeypatch.setattr(counterfactual, "_litellm", lambda: broken_catalog)
|
|
counterfactual.resolve_rates.cache_clear()
|
|
try:
|
|
assert counterfactual.resolve_rates("probe-fail-model") is None
|
|
finally:
|
|
counterfactual.resolve_rates.cache_clear()
|
|
_assert_safe(records, "probe-fail-model")
|