mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-25 12:11:49 +08:00
## Description Several savings and metrics paths swallow exceptions and log nothing, so when one fails, a customer-facing number can come out wrong with no record of why. This PR adds a log line on each of those paths. The numbers and the control flow are unchanged. Refs #4136 | Where | Before | Now | |---|---|---| | `tool_schema_savings_policy.reconcile_deferred_tokens` | A failure left the tool-search deferral credit as booked, so `/stats` over-reported. Nothing was logged. | Warns once per exception type, giving the booked token count and the fact that `/stats` is over-reported. Every occurrence is also logged at debug. | | `outcome.py` output-savings record/estimate | Booked 0 silently. | Debug, with the request id. | | `server.py` `/stats` `output_reduction` | The section went missing silently. | Debug. | | `server.py` `create_app` saved-settings apply | `settings_store.load()` already warns about an unreadable or corrupt file. Any other error while applying it was swallowed. | Warns with the settings file path and says to fix or remove that file and restart. Startup continues. | | `server.py` security gate, audit record | Debug only. | Warns with the method and path, and says the request is missing from the `headroom.audit` trail. | | `savings_tracker` pricing for an unpriced model | Raised `RuntimeError` only to reach the fallback, and logged nothing. | Returns the fallback directly and logs once per model at debug. The `except` blocks now see only unexpected errors, and log them at debug. | | `savings_tracker._resolve_litellm_model` probes | Two `except Exception: pass` blocks. | Debug. litellm raises a bare `Exception` for a model it does not know, so the catch cannot be narrower. | **No content at any level.** A tokenizer error can quote the client's tool schema, and a settings or pricing error can quote a credential. So every line this PR adds describes a failure with `describe_exception(exc)` from `headroom/log_safety.py`: the exception types and code locations of the cause chain, never the message and never a traceback. Model ids go through `safe_id`, and audit paths are capped the same way. The full text appears only when the operator sets `HEADROOM_DEBUG_DUMP=full`. **Bounded dedupe.** The reconcile guard (keyed by exception type) and the unpriced-model guard (keyed by model) use the shared `WarnOnce`. Each key is logged once, at most a fixed number of keys per hour, followed by one overflow notice. The unpriced-model guard is consulted only when DEBUG is enabled, so a model is not used up while its line is suppressed. ## 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 - `headroom/proxy/tool_schema_savings_policy.py`: `_log_reconcile_failure` uses `WarnOnce(32, ...)` and `describe_exception`. - `headroom/proxy/outcome.py`, `headroom/proxy/server.py`, `headroom/proxy/savings_tracker.py`: add the lines in the table above, all through `describe_exception` and `safe_id`. `_log_unpriced_model_once` uses `WarnOnce`. - Tests: - `tests/test_tool_schema_savings_policy.py`: - a tokenizer error quoting a private-schema canary; - every captured DEBUG and WARNING record is rendered with `logging.Formatter()`, which includes `exc_info`, and none contains the canary; - the booked credit stays unchanged; - one warning per exception type, a debug line per failure. - `tests/test_savings_pricing_fallback_logging.py`: - a pricing error and a litellm probe error that quote an API-key canary, with the canary absent from every formatted record; - an unpriced model logs once; - nothing is used up while DEBUG is off. - `tests/test_saved_settings_apply_logging.py`: a settings-apply error that quotes an API-key canary through a real `create_app`. One warning names the file and the exception type, and no formatted record contains the canary. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text # New regressions against the previous commit's product files (c5850f02), in a scratch worktree: FAILED tests/test_tool_schema_savings_policy.py::test_reconcile_failure_keeps_private_schema_out_of_every_log_record E assert 'PRIVATE-SCHEMA-CANARY-7f3a' not in "tool-schema...NARY-7f3a'}]" FAILED tests/test_tool_schema_savings_policy.py::test_reconcile_warns_again_for_a_new_exception_type FAILED tests/test_savings_pricing_fallback_logging.py::test_unpriced_model_logs_once FAILED tests/test_savings_pricing_fallback_logging.py::test_credential_bearing_pricing_error_is_described_not_quoted FAILED tests/test_savings_pricing_fallback_logging.py::test_unpriced_model_not_marked_when_debug_disabled FAILED tests/test_saved_settings_apply_logging.py::test_settings_apply_failure_warns_without_credential =================== 6 failed, 10 passed, 1 warning in 3.54s ==================== # This branch: $ pytest -q -p no:cacheprovider tests/test_tool_schema_savings_policy.py tests/test_savings_pricing_fallback_logging.py tests/test_saved_settings_apply_logging.py ======================== 16 passed, 1 warning in 2.77s ========================= $ pytest -q -p no:cacheprovider <every test file referencing the touched estimators, reconcile_deferred_tokens, settings_store, record_admin_action or log_safety> + the savings/stats/output-shaper files ======================= 401 passed, 1 warning in 44.33s ======================== $ uvx ruff@0.16.8 check <touched files> && uvx ruff@0.16.8 format --check headroom/proxy All checks passed! $ mypy headroom/proxy/tool_schema_savings_policy.py headroom/proxy/savings_tracker.py headroom/proxy/server.py headroom/proxy/outcome.py --ignore-missing-imports Success: no issues found in 4 source files ``` `tests/test_cost_card_attribution.py` and `tests/test_savings_provider_matrix.py` also fail at collection on a clean `origin/main`, because the local litellm build prices none of their candidate models. I left them out of the runs above. ## Real Behavior Proof - Environment: macOS, Python 3.12.13, this branch atd3834fea, the repo .venv, a temp `HOME`, `HEADROOM_WORKSPACE_DIR` and `CODEX_HOME`, and `HEADROOM_OFFLINE=1`. - Exact command / steps: - (1) The shared smoke harness, `smoke.sh <worktree>`. It runs a real `headroom proxy` from this checkout against a local fake upstream, sends one Anthropic and one OpenAI request that each carry a compressible tool result, reads `/stats`, and greps `proxy.log`. - (2) A script that forces each new path: - `settings_store.apply_to_environ` raises `RuntimeError("value sk-secret-should-not-appear")` under `create_app()`; - `reconcile_deferred_tokens` is called twice with a counter that raises `RuntimeError("... secret-schema-text")`; - the unknown model `local-llama-7b` is priced three times with the savings-tracker logger at DEBUG. - Observed result: ```text (1) branch: cleanup/proxy-core-b-savings-logging @d3834feahealth: 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 (2) WARNING headroom.proxy: Could not apply saved settings from <tmp>/ws/settings.json (RuntimeError at pcb_4084_proof.py:16 in _boom <- headroom/proxy/server.py:3141 in create_app); continuing with env and defaults. Fix or remove that file and restart the proxy. WARNING headroom.proxy.tool_schema_savings_policy: tool-schema deferral reconcile failed (RuntimeError at pcb_4084_proof.py:31 in _broken <- headroom/proxy/tool_schema_savings_policy.py:146 in reconcile_deferred_tokens); credit left at 100 booked tokens, so /stats over-reports tool-search savings for this request. Please report this as a bug. DEBUG headroom.proxy.savings_tracker: litellm cannot price model='local-llama-7b' as given: BadRequestError at get_llm_provider_logic.py:515 in get_llm_provider <- get_llm_provider_logic.py:528 in get_llm_provider <- cost_calculator.py:472 in cost_per_token DEBUG headroom.proxy.savings_tracker: No litellm input_cost_per_token for model='local-llama-7b'; savings and cost use the fallback rate ``` - Neither secret string appears in any line. - The second reconcile failure does not warn again. - The unpriced model is logged once across three calls. - Not tested: - Forcing the audit-record failure inside a running proxy. It uses the same `describe_exception` pattern. - Seeing the debug lines in a running proxy's `proxy.log`. That depends on #4137, which makes `HEADROOM_LOG_LEVEL=debug` reach `headroom.*`. Until it lands, these debug lines show only when the `headroom` logger is set to DEBUG programmatically, as in the script. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A; logging only. - Stable/default behavior changed: No. Every dollar value is the same as before, and an unpriced model now gets its fallback returned directly instead of through a raise and catch, with an identical result. Only the log output changes. - Kill switch / disable path: None needed. Warnings fire only on a real failure, and they are deduplicated with a bound. - Unsafe override required: No. `HEADROOM_DEBUG_DUMP=full` is the existing explicit opt-in for full exception text. - Qualification impact: None. - Rollback path: Revert this PR. ## 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 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. Docs for the new warnings are collected for the single follow-up docs PR. Depends on #4138; its files (`headroom/log_safety.py`, `handlers/_debug_dump.py` and their tests) show in this diff until it merges. This PR's own diff, excluding #4138's files, is +377/−20, and 256 of those added lines are tests. `cost._warn_pricing_once` is not reused for unpriced models because it logs at WARNING, and it shares its set with the live cost path, which already warns once per unpriceable model. For an unknown model, cache savings book 0 while compression savings use the $3/M fallback. This PR leaves that unchanged for a maintainer decision. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
235 lines
8.8 KiB
Python
235 lines
8.8 KiB
Python
from __future__ import annotations
|
|
|
|
from headroom.proxy.tool_schema_savings_policy import (
|
|
TOOL_SCHEMA_SAVINGS_TAGS,
|
|
headline_tokens_saved,
|
|
tool_schema_saved_from_tags,
|
|
)
|
|
|
|
|
|
def test_tool_schema_saved_from_tags_sums_headroom_deferral_tags() -> None:
|
|
assert (
|
|
tool_schema_saved_from_tags(
|
|
{
|
|
"tool_search_deferred_tokens": "120",
|
|
"turn_hook_tools_saved_tokens": 30,
|
|
"unrelated": 999,
|
|
}
|
|
)
|
|
== 150
|
|
)
|
|
|
|
|
|
def test_tool_schema_saved_from_tags_ignores_invalid_values() -> None:
|
|
assert (
|
|
tool_schema_saved_from_tags(
|
|
{
|
|
"tool_search_deferred_tokens": "not-an-int",
|
|
"turn_hook_tools_saved_tokens": None,
|
|
}
|
|
)
|
|
== 0
|
|
)
|
|
|
|
|
|
def test_tool_schema_saved_from_tags_rejects_non_mapping_tags() -> None:
|
|
assert tool_schema_saved_from_tags(None) == 0
|
|
assert tool_schema_saved_from_tags([("tool_search_deferred_tokens", 10)]) == 0
|
|
|
|
|
|
def test_tool_schema_savings_tags_are_stable() -> None:
|
|
assert TOOL_SCHEMA_SAVINGS_TAGS == (
|
|
"tool_search_deferred_tokens",
|
|
"turn_hook_tools_saved_tokens",
|
|
)
|
|
|
|
|
|
# ── headline_tokens_saved: the one figure every surface reports ────────────────
|
|
# Headroom saves tool-definition tokens in two accounting shapes — compaction
|
|
# folds into tokens_saved, deferral is tagged and additive. Both existed before
|
|
# but the rule was never written down, so two harnesses dropped their compaction
|
|
# savings and three surfaces open-coded the sum. These cases pin the contract.
|
|
|
|
|
|
def test_folded_compaction_is_not_counted_twice() -> None:
|
|
"""Compaction is ALREADY inside tokens_saved (handlers fold both endpoints).
|
|
|
|
Adding an attribution amount back on top would inflate every tool-heavy turn.
|
|
"""
|
|
assert headline_tokens_saved(420, {}) == 420
|
|
|
|
|
|
def test_deferral_tags_are_additive_to_tokens_saved() -> None:
|
|
"""Deferral removes schemas count_messages never saw, so it can't be folded."""
|
|
tags = {"tool_search_deferred_tokens": 9639}
|
|
assert headline_tokens_saved(0, tags) == 9639
|
|
assert headline_tokens_saved(1_000, tags) == 10_639
|
|
|
|
|
|
def test_headline_identical_across_harnesses_for_equivalent_work() -> None:
|
|
"""A 500-token saving reports as 500 whichever accounting shape produced it.
|
|
|
|
Anthropic/Claude Code folds its compaction; a Codex deferral is tagged. Same
|
|
real saving, same headline — that equivalence is the point of the helper.
|
|
"""
|
|
anthropic_folded = headline_tokens_saved(500, {})
|
|
codex_tagged = headline_tokens_saved(0, {"tool_search_deferred_tokens": 500})
|
|
assert anthropic_folded == codex_tagged == 500
|
|
|
|
|
|
def test_headline_survives_malformed_tags() -> None:
|
|
for tags in (None, {}, "not-a-dict", {"tool_search_deferred_tokens": None}):
|
|
assert headline_tokens_saved(10, tags) == 10
|
|
assert headline_tokens_saved(10, {"tool_search_deferred_tokens": "abc"}) == 10
|
|
assert headline_tokens_saved(None, None) == 0
|
|
|
|
|
|
def test_headline_clamps_negative_message_savings() -> None:
|
|
"""Handlers revert inflation before forwarding, so a negative is a count artifact."""
|
|
assert headline_tokens_saved(-5, {}) == 0
|
|
assert headline_tokens_saved(-5, {"tool_search_deferred_tokens": 100}) == 95
|
|
|
|
|
|
def test_tool_schema_compaction_saves_real_tokens_not_just_bytes() -> None:
|
|
"""The premise of folding compaction into tokens_saved on every handler.
|
|
|
|
Compaction strips annotation keys ($schema/title/examples). If that only moved
|
|
bytes that tokenize to nothing, the fold would be worthless — so pin a positive
|
|
TOKEN delta on a realistically-shaped tool array, and pin that folding it into
|
|
both endpoints keeps ``tok_before - tok_after == tok_saved`` coherent.
|
|
"""
|
|
import json
|
|
|
|
from headroom.providers.anthropic import AnthropicProvider
|
|
from headroom.proxy.tool_schema_compaction import compact_tools
|
|
|
|
tok = AnthropicProvider().get_token_counter("claude-sonnet-4-6")
|
|
payload = {
|
|
"tools": [
|
|
{
|
|
"name": f"tool_{i}",
|
|
"description": "Does a thing.\n\n Returns text.",
|
|
"input_schema": {
|
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
"title": f"tool_{i}_schema",
|
|
"examples": [{"path": "/tmp/x"}, {"path": "/tmp/y"}],
|
|
"type": "object",
|
|
"properties": {"path": {"type": "string", "description": "File path"}},
|
|
"required": ["path"],
|
|
},
|
|
}
|
|
for i in range(14)
|
|
]
|
|
}
|
|
before_tools = payload["tools"]
|
|
body, modified, _bytes_before, _bytes_after = compact_tools(payload)
|
|
assert modified is True
|
|
|
|
tool_before = tok.count_text(json.dumps(before_tools, default=str))
|
|
tool_after = tok.count_text(json.dumps(body["tools"], default=str))
|
|
assert tool_after < tool_before, "compaction must shrink tool TOKENS, not only bytes"
|
|
|
|
# Mirrors the fold each handler applies at its final recount, with zero message
|
|
# compression — the shape that used to report tok_saved=0 on Claude Code.
|
|
original_tokens = optimized_tokens = 5_000
|
|
if 0 < tool_after < tool_before:
|
|
original_tokens += tool_before
|
|
optimized_tokens += tool_after
|
|
tokens_saved = max(0, original_tokens - optimized_tokens)
|
|
|
|
assert tokens_saved == tool_before - tool_after
|
|
assert original_tokens - optimized_tokens == tokens_saved
|
|
assert headline_tokens_saved(tokens_saved, {}) == tokens_saved
|
|
|
|
|
|
SCHEMA_CANARY = "PRIVATE-SCHEMA-CANARY-7f3a"
|
|
|
|
|
|
def _capture_policy_logs(monkeypatch):
|
|
import logging
|
|
|
|
from headroom.log_safety import WarnOnce
|
|
from headroom.proxy import tool_schema_savings_policy as policy
|
|
|
|
records: list[logging.LogRecord] = []
|
|
|
|
class _Capture(logging.Handler):
|
|
def emit(self, record: logging.LogRecord) -> None:
|
|
records.append(record)
|
|
|
|
handler = _Capture(level=logging.DEBUG)
|
|
policy.logger.addHandler(handler)
|
|
old_level = policy.logger.level
|
|
policy.logger.setLevel(logging.DEBUG)
|
|
monkeypatch.setattr(
|
|
policy, "_reconcile_warned", WarnOnce(32, "test reconcile types"), raising=False
|
|
)
|
|
monkeypatch.delenv("HEADROOM_DEBUG_DUMP", raising=False)
|
|
return policy, records, handler, old_level
|
|
|
|
|
|
def test_reconcile_failure_keeps_private_schema_out_of_every_log_record(monkeypatch) -> None:
|
|
import logging
|
|
|
|
policy, records, handler, old_level = _capture_policy_logs(monkeypatch)
|
|
|
|
tool = {"name": "Read", "defer_loading": True, "description": SCHEMA_CANARY}
|
|
|
|
def _tokenizer_echoes_schema(tools: object) -> int:
|
|
# A tokenizer error that quotes the schema it choked on.
|
|
raise ValueError(f"cannot tokenize {tools!r}")
|
|
|
|
tags = {"tool_search_deferred_tokens": 100}
|
|
booking = (100, {"Read": dict(tool)}, None)
|
|
try:
|
|
policy.reconcile_deferred_tokens(tags, booking, [dict(tool)], _tokenizer_echoes_schema)
|
|
policy.reconcile_deferred_tokens(tags, booking, [dict(tool)], _tokenizer_echoes_schema)
|
|
finally:
|
|
policy.logger.removeHandler(handler)
|
|
policy.logger.setLevel(old_level)
|
|
|
|
# The booked credit is left as it was.
|
|
assert tags["tool_search_deferred_tokens"] == 100
|
|
|
|
levels = [r.levelno for r in records]
|
|
assert levels.count(logging.WARNING) == 1, "warns once per exception type"
|
|
assert levels.count(logging.DEBUG) == 2, "every failure is recorded at debug"
|
|
formatter = logging.Formatter()
|
|
for record in records:
|
|
rendered = formatter.format(record)
|
|
assert SCHEMA_CANARY not in rendered
|
|
assert "ValueError" in rendered
|
|
assert "100 booked tokens" in records[0].getMessage()
|
|
|
|
|
|
def test_reconcile_warns_again_for_a_new_exception_type(monkeypatch) -> None:
|
|
import logging
|
|
|
|
policy, records, handler, old_level = _capture_policy_logs(monkeypatch)
|
|
tool = {"name": "Read", "defer_loading": True, "description": "x"}
|
|
booking = (100, {"Read": dict(tool)}, None)
|
|
|
|
def _runtime(tools: object) -> int:
|
|
raise RuntimeError("boom")
|
|
|
|
def _value(tools: object) -> int:
|
|
raise ValueError("boom")
|
|
|
|
try:
|
|
# A healthy reconcile logs nothing.
|
|
policy.reconcile_deferred_tokens(
|
|
{"tool_search_deferred_tokens": 100}, booking, [dict(tool)], lambda t: 10
|
|
)
|
|
assert records == []
|
|
for counter in (_runtime, _runtime, _value):
|
|
policy.reconcile_deferred_tokens(
|
|
{"tool_search_deferred_tokens": 100}, booking, [dict(tool)], counter
|
|
)
|
|
finally:
|
|
policy.logger.removeHandler(handler)
|
|
policy.logger.setLevel(old_level)
|
|
|
|
warnings = [r.getMessage() for r in records if r.levelno == logging.WARNING]
|
|
assert len(warnings) == 2
|
|
assert "RuntimeError" in warnings[0] and "ValueError" in warnings[1]
|