Commit Graph
9 Commits
Author SHA1 Message Date
Tejas ChopraandClaude Opus 5.5 30b22df7fd fix(proxy): read stream cache usage from message_delta; keep Fireworks sessions on one replica (#4174)
## Description

Two fixes for Claude Code (or any Anthropic-format client) running
through Headroom to Anthropic-compatible hosts such as Fireworks.

1. **Stream cache usage was read from the wrong event.** Fireworks'
`/v1/messages` stream sends zeros in `message_start` and the real
`input_tokens` / `cache_read_input_tokens` only in `message_delta`. The
SSE parser only read them from `message_start`, so every streamed turn
was logged as `cache_read=0`. The prefix tracker uses that number to
decide how much history to freeze, so it froze nothing and could rewrite
history Fireworks had already cached. `message_delta` usage is
cumulative, so the parser now takes its counts when they are larger.
2. **Session affinity for Fireworks.** Fireworks documents
`x-session-affinity` as the routing hint for keeping prompt-cache hits
on one replica. Requests to `api.fireworks.ai` now carry Headroom's
session id in that header. No other host gets it, and a value the client
set wins.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)

## Changes Made

- `headroom/proxy/handlers/streaming.py`: also read `input_tokens`,
`cache_read_input_tokens`, `cache_creation_input_tokens` from
`message_delta` usage, keeping the larger value.
- `headroom/proxy/session_affinity.py` (new): host → affinity-header
map, currently only `api.fireworks.ai` → `x-session-affinity`.
- `headroom/proxy/handlers/anthropic.py`: add the affinity header on the
direct path, right after the upstream URL is built. The Bedrock, Vertex
and translated backends are not affected.
- Tests:
`test_streaming_parser_reads_cache_usage_sent_only_in_message_delta`
fails without the fix and passes with it.
`tests/test_session_affinity.py` covers four things through the real
proxy: Fireworks gets one stable affinity value per conversation,
Anthropic and other upstreams get no header, and a client-set header is
kept.

## Testing

- [x] Unit tests pass (`pytest`): the tests above plus the neighbouring
proxy, streaming, cache and backend suites
- [x] Linting passes (`ruff check .`, `ruff format --check .`, ruff
0.16.8)
- [ ] Type checking passes (`mypy headroom`): one error, in a file this
PR does not touch (see notes)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ ruff check . && ruff format --check .
All checks passed!
1779 files already formatted
$ pytest tests/test_session_affinity.py tests/test_proxy_cache_ttl_metrics.py tests/test_proxy_anthropic_*.py \
    tests/*stream* tests/*prefix_tracker* tests/*cache_stab* tests/*copilot* tests/*bedrock* tests/*vertex* ...
1326 passed, 3 skipped
$ mypy headroom --ignore-missing-imports
headroom/integrations/langchain/chat_model.py:380: error: Function "RunnableBinding" could always be true in boolean context  [truthy-function]
```

## Real Behavior Proof

- Environment: macOS, real Claude Code (`claude -p`) → Headroom proxy →
`https://api.fireworks.ai/inference`
(`accounts/fireworks/models/kimi-k3`). A local relay in front of
Headroom swaps Claude Code's model name for the Fireworks one and
records the provider usage.
- Exact steps: run a small coding task on `pallets/itsdangerous@2.2.0`
(add a method, write tests, run pytest) with
`ANTHROPIC_TARGET_API_URL=https://api.fireworks.ai/inference`.
- Observed result:
- **Before:** on the same requests where Fireworks reported
`cache_read_input_tokens` of 25461 and 29213, Headroom's `PERF` lines
logged `cache_read=0` every time.
- **After:** Headroom logs the provider's real counts, e.g.
`cache_read=8192`. The task completed with all tests passing. With
compression on, every turn that hit the cache reused the full previous
prompt minus one token, so Headroom caused no prefix breaks.
- **Affinity:** the header is harmless to Anthropic: `api.anthropic.com`
returned 200 with and without it, and Headroom never sends it there
anyway. On Fireworks' `/v1/messages` with Kimi K3, 8-turn probes with
and without the header gave the same cache-hit pattern, and a live
Claude Code run measured 77.7% with it vs 78–79% without. **No hit-rate
improvement was measured on this endpoint and model.** It follows
Fireworks' documented guidance and may matter more on dedicated
multi-replica deployments.
- Not tested: dedicated Fireworks deployments; Fireworks'
OpenAI-compatible endpoint (the header is only added on the Anthropic
path).

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed:
- Streamed Anthropic-format responses whose real counts arrive in
`message_delta` now report them. Anthropic's own stream puts them in
`message_start`, so it is unaffected; the larger-value rule never lowers
a count.
  - Requests to `api.fireworks.ai` gain one header.
- Kill switch / disable path: a client-set `x-session-affinity`
overrides Headroom's value. There is no env toggle.
- Unsafe override required: no
- Qualification impact: none expected
- 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
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation (n/a)
- [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`

## Additional Notes

- The mypy error in `headroom/integrations/langchain/chat_model.py:380`
exists on `main` without this change; this PR does not touch that file.
- Two related concerns are in one PR by request. They touch separate
code and can be reverted independently.
- Related: vLLM's Anthropic endpoint only reports cached tokens when
started with `--enable-prompt-tokens-details`. Worth a docs note for
self-hosted users in a follow-up.

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

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4174"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 11:17:50 -07:00
Tejas Chopra 31d378b0e5 refactor(proxy): remove test-only and dead helpers from the handlers (#4117)
## Description

This removes proxy handler helpers that production code never calls, and
one test that always skipped. Behaviour does not change.

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/proxy/handlers/openai.py`: removed
`_compact_openai_tool_schema_value`. It had no callers anywhere.
- `headroom/proxy/handlers/streaming.py`:
- Removed `StreamingMixin._parse_sse_usage`, the 92-line single-chunk
SSE usage parser. Production only calls `_parse_sse_usage_from_buffer`.
- Removed `_sse_contains_error_event`, a 5-line wrapper over
`_sse_event_outcome` that only `tests/test_route_advice.py` called.
- `headroom/proxy/handlers/gemini.py`: removed
`GeminiHandlerMixin._count_texts_offloaded`, which only tests called.
`tests/test_tokenizer_count_offload.py:77` already asserts that no
handler uses it.
- Test changes:
- `tests/test_proxy_cache_ttl_metrics.py`: the TTL-bucket test now
drives `_parse_sse_usage_from_buffer`.
- `tests/test_streaming_sse_malformed_events.py`: dropped the
chunk-parser variants. The buffered-parser variants of the same cases
stay.
- `tests/test_route_advice.py`: carries the error-event helper locally,
so its `_sse_event_outcome` coverage is unchanged.
- `tests/test_tokenizer_count_offload.py`: calls
`token_counting.count_texts_offloaded(proxy, ...)` directly, still on a
real proxy and its worker thread.
- `tests/test_codex_ws_compression_scheduler.py`: removed
`test_codex_ws_emits_perf_log_with_cache_keys`, which called
`pytest.skip` unconditionally ("Pending: full WS lifecycle harness"),
along with the fixtures only it used.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [ ] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
$ uvx ruff@0.16.8 check headroom/proxy/handlers tests/test_codex_ws_compression_scheduler.py tests/test_tokenizer_count_offload.py tests/test_route_advice.py tests/test_streaming_sse_malformed_events.py tests/test_proxy_cache_ttl_metrics.py
All checks passed!
$ pytest -q tests/test_streaming_sse_malformed_events.py tests/test_proxy_cache_ttl_metrics.py tests/test_route_advice.py tests/test_tokenizer_count_offload.py tests/test_codex_ws_compression_scheduler.py tests/test_openai_responses_context_compaction.py tests/test_openai_responses_additional_tools.py tests/test_gemini_compression_offload.py tests/test_proxy_gemini_integration.py tests/test_proxy_gemini_native_integration.py
470 passed, 27 skipped in 24.13s
```

## Real Behavior Proof

- Environment: macOS, Python 3.12, repo venv, branch
`cleanup/proxy-handlers-dead-helpers` @ c15e679e, temp
`HOME`/`HEADROOM_WORKSPACE_DIR`/`CODEX_HOME`, `HEADROOM_OFFLINE=1`
- Exact command / steps: (1) a `grep -rnE
'_compact_openai_tool_schema_value|_parse_sse_usage\b|_sse_contains_error_event|_count_texts_offloaded'`
over headroom, tests, crates, plugins, sdk, examples, benchmarks,
scripts, e2e, docs, wiki, .github, pyproject.toml and every consumer
repo clone; (2) the shared smoke harness: a real `headroom proxy` from
this checkout against a local fake upstream, with one Anthropic and one
OpenAI turn; (3) a direct check that the removed names are gone from the
assembled `HeadroomProxy` and that the live SSE usage parser still works
- Observed result: (1) before the change, only the definitions and tests
matched; after it, nothing in `headroom/` references the removed names.
(2) and (3) are shown below: both turns return 200 with savings, the
names are absent, and the live parser returns the usage.
- Not tested: a real hosted upstream

```text
$ bash smoke.sh <worktree>
branch: cleanup/proxy-handlers-dead-helpers @ c15e679e
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:
   (only the pre-existing offline-mode notice and Kompress offline-prefetch warnings)

$ HOME=$T/h HEADROOM_WORKSPACE_DIR=$T/ws CODEX_HOME=$T/c python -c "<check HeadroomProxy attrs; run _parse_sse_usage_from_buffer>"
_parse_sse_usage on HeadroomProxy: False
_sse_contains_error_event on HeadroomProxy: False
_count_texts_offloaded on HeadroomProxy: False
_compact_openai_tool_schema_value in openai: False
live SSE usage parser: {'input_tokens': 9, 'output_tokens': 2, 'cache_read_input_tokens': 0}
```

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: stable
- Stable/default behavior changed: no
- Kill switch / disable path: not applicable (dead code removal)
- 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.

- `headroom.proxy.token_counting.count_texts_offloaded` is now called
only by tests. It is outside this cleanup slice, so it is left in place
and flagged for the token-counting owner.
- No `headroom.proxy.handlers` symbol appears in the consumer import
index.
- mypy and comments: N/A, since this PR only deletes code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-10-10 09:00:49 -07:00
b1fb162b62 fix(grok): attribute api.x.ai chat outcomes as provider xai, recognize grok-shell UA (#2626)
## Description

Grok Build chat requests were recorded as `custom` or `openai`,
preventing xAI provider rollups. This change records custom-base and
directly routed Grok chat traffic as `xai`, recognizes both `grok/` and
`grok-shell/` clients, and keeps API-key requests on credential-driven
PAYG policy.

Closes #3996

## Type of Change

- [x] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring

## Changes Made

- Attribute supported xAI chat routes, including trailing-dot hosts, to
`xai`.
- Preserve per-model catalog cache prices and share the xAI cache
fallback between dashboard costs and persisted savings.
- Exclude inferred cache writes from billed aggregate totals; those
tokens already belong to uncached input. Explicit provider-reported
writes remain billable.
- Cover custom-base outcome integration, catalog pricing precedence,
legacy and current client credentials, and inferred writes with and
without TTL splits.

## Testing

At `29fd4f9d7a24a76f3a3f53edacc5832e357cae58`: 130 focused pricing,
accounting, auth, cache, and routing tests pass (one existing Starlette
warning). Ruff lint and format, whitespace checks, and Linux-target mypy
over 567 source files pass. Main refresh retains `3c418f6f` ancestry.
Latest documentation dependency audit found zero vulnerabilities.

## Real Behavior Proof

- Environment: Windows, Python 3.12, a real uvicorn proxy and a separate
loopback HTTP upstream. Subscription polling disabled. Only upstream
network delivery is redirected; this is not live xAI billing traffic.
- Steps: send four real TCP chat POSTs with custom-base, direct, legacy
Grok, and trailing-dot routing; query the running proxy's `/stats`
endpoint. The upstream returns 10,000 input tokens, 5,000 cached input
tokens, and 1,000 output tokens per request. A priced xAI catalog
fixture has $1/M input and $2/M output, with no explicit cache-read
rate.
- Observed: all four requests return HTTP 200, outcomes record
`provider=xai` and `client=grok_build`, and `/stats` records
`{"xai":4}`. Input spend is $0.0232 using the xAI 0.16 cache fallback.
Before the aggregate-accounting correction this same replay reported
$0.0432.
- Evidence: `pr2626-resume15-pricing-runtime.log` and
`pr2626-resume15-final-tests.log`; regressions reproduce the
pricing/auth defects before correction.

## Runtime Rollout Safety

- Rollout-managed features: none; attribution, credential
classification, and accounting use the existing request paths.
- Default behavior: supported xAI routes receive the xAI label; API keys
use PAYG policy, JWT credentials retain OAuth policy. Unknown gateways
retain the bounded custom provider bucket.
- Pricing behavior: when a priced catalog row has no cache rates and the
caller omits `provider`, `resolve_rates` now identifies the provider
from `litellm_provider` and uses the shared fallback. For xAI this means
cached input costs 0.16 times list input; explicit model cache rates
still win. Dashboard aggregates also exclude inferred writes already
counted as uncached input. These corrections change reported input costs
and persisted savings, not upstream requests or billing.
- Rollback: revert the pricing/auth/attribution commits; no new rollout
switch or unsafe override is introduced.
- Coverage: real HTTP routing and `/stats` replay plus focused
default-policy and accounting tests.

## Checklist

- [x] Self-review completed
- [x] Added regression coverage
- [x] Relevant local tests and static checks pass
- [x] Did not edit CHANGELOG.md

## Additional Notes

Hosted checks and automated review must qualify this newly published
head before approval. No PR merge performed.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-10-08 10:56:22 -05:00
b4f807f21a fix(proxy/cost): price cache savings by most-used model, not first-seen (#2023)
## Description

`build_prefix_cache_stats` (`headroom/proxy/cost.py`) values each
provider's cache-read savings
using a single "base input price per token". It derives that price by
scanning
`cost_tracker._tokens_sent_by_model` and **breaking on the first**
provider-matching model that
has a price — even though the comment says "most-used model":

```python
# Get the base input price per token for the most-used model on this provider
input_price_per_token = None
if cost_tracker:
    for model_name in cost_tracker._tokens_sent_by_model:   # insertion order, NOT usage order
        ...
        if is_match:
            price_per_1m = cost_tracker._get_list_price(model_name)
            if price_per_1m:
                input_price_per_token = price_per_1m / 1_000_000
                break                                        # first match wins
```

`_tokens_sent_by_model` is insertion-ordered, so the price used depends
on which model was
*recorded first*, not on usage volume. A Claude Code session sends both
Sonnet (main loop) and
Haiku (titles/subagents). If Haiku ($0.80/M) was seen before Sonnet
($3/M), **all** of the
provider's cache-read savings are priced at Haiku's rate — understating
the dashboard's cache
savings by ~3.75×. Reverse the order and it overstates.

Closes: no issue filed — found while auditing the cache-savings pricing.

## Fix

Pick the provider-matching, priced model with the **highest token
volume** instead of breaking
on the first match:

```python
best_tokens = -1
for model_name, tokens_sent in cost_tracker._tokens_sent_by_model.items():
    if is_match and tokens_sent > best_tokens:
        price_per_1m = cost_tracker._get_list_price(model_name)
        if price_per_1m:
            input_price_per_token = price_per_1m / 1_000_000
            best_tokens = tokens_sent
```

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `headroom/proxy/cost.py`: select the highest-volume provider-matching
model (with a known price) rather than the first-recorded one.
- `tests/test_proxy_cache_ttl_metrics.py`: add
`test_prefix_cache_stats_prices_by_most_used_model` using real distinct
per-model prices. (The existing cache-stats tests monkeypatch
`_get_list_price` to a constant `100.0`, which masked the
model-selection logic — hence the bug slipped through.)

## Testing

- [x] New regression test added
(`tests/test_proxy_cache_ttl_metrics.py`)
- [x] Linting/formatting clean — run with the CI-pinned `ruff==0.15.17`
- [ ] Full `pytest` deferred to CI (local-OOM reason below).

```text
$ uvx ruff@0.15.17 check headroom/proxy/cost.py tests/test_proxy_cache_ttl_metrics.py
All checks passed!
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.10, headroom from this branch.
Importing `headroom` pulls in the torch/transformers stack and a full
`pytest` gets OOM-killed on this box, so I verified the selection logic
with a dependency-free script and left the full pytest to CI.
- Exact command / steps: ran a `{haiku: 500, sonnet: 50000}` token map
(Haiku recorded first, Sonnet the higher volume) through both the old
first-match and new highest-volume selection with real prices.
- Observed result: the old logic picks Haiku's $0.80/M (first-inserted);
the new logic picks Sonnet's $3/M (highest volume) and is
insertion-order independent:

```text
OLD picks Haiku price: 0.80/M  (first-inserted)
NEW picks Sonnet price: 3.00/M  (highest volume)
  -> old understates the input price by 3.75x (3.75x)
NEW is insertion-order independent
COST MOST-USED-MODEL FIX VERIFIED
```

- Not tested: rendering the live dashboard (needs the running app). The
fix is confined to the price-selection loop and the new test drives
`build_prefix_cache_stats` directly. Full local `pytest` deferred to CI
(OOM, per above).

## 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
- [ ] New and existing unit tests pass locally with my changes — ran
lint + a standalone logic check; full pytest deferred to CI (local OOM,
disclosed above)
- [x] I have updated the CHANGELOG.md if applicable

## Additional Notes

- No new dependencies; a single-loop change plus a test with realistic
prices.
- @JerrettDavis tagging you — this skews the dashboard's per-provider
cache-savings dollar figure by the ratio between a provider's models
(≈3.75× for Sonnet/Haiku), so it seemed worth surfacing. Thanks!

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
Co-authored-by: Tejas Chopra <chopratejas@gmail.com>
2026-07-13 09:37:58 -04:00
Rod Boev 53a465b121 fix(proxy): subtract cache write premiums from net savings (#1800)
## Description

Cache stats already calculate both prompt-cache read savings and
cache-write premium cost, but the exported `net_savings_usd` field used
gross read savings alone. That made cache-heavy token-mode workloads
look profitable even when extra cache writes offset or exceeded the read
discount. This updates existing cache cost accounting so provider and
total `net_savings_usd` subtract write premiums while keeping gross
savings and write premium fields visible. Refs #327.

The scope follows doublefx's controlled measurement in
https://github.com/headroomlabs-ai/headroom/issues/327#issuecomment-4683604089,
which showed token-mode compression increasing cache write volume and
billed cost while dashboard token savings looked positive.

## 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

- Subtract cache write premiums from provider-level cache
`net_savings_usd`.
- Subtract aggregate cache write premiums from total cache
`net_savings_usd`.
- Keep gross `savings_usd` and `write_premium_usd` visible for dashboard
and telemetry consumers.
- Add focused regressions for provider net, total net, and
zero-write-premium preservation.
- Update the dashboard cache TTL fixture to match the corrected net
value.

## Testing

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

### Test Output

```text
uv run pytest tests/test_proxy_cache_ttl_metrics.py tests/test_dashboard_cache_ttl_playwright.py tests/test_proxy_dashboard_stats_cache.py -q
28 passed, 2 skipped, 1 warning in 32.75s

uv run pytest tests/test_proxy_cache_ttl_metrics.py -q -k keeps_net_equal_without_write_premium
1 passed, 16 deselected in 0.15s

uv run ruff check headroom/proxy/cost.py tests/test_proxy_cache_ttl_metrics.py tests/test_dashboard_cache_ttl_playwright.py tests/test_proxy_dashboard_stats_cache.py
All checks passed!
```

## Real Behavior Proof

- Environment: Windows, Python through the project `uv` environment.
- Exact command / steps: run the cache net-savings regressions against
base and head.
- Observed result: base reports provider net as `0.0036` instead of
`0.0021` and total net as `0.0046` instead of `0.0031`; head passes the
focused cache metrics suite and preserves `net_savings_usd ==
savings_usd` when there is no write premium.
- Not tested: broader cache-hit-rate tuning, prompt-cache policy
changes, and live provider billing.

## 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
- [x] 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

No changelog entry is needed because this corrects existing stats fields
rather than adding a new command or control. Type checking was not part
of the focused local validation for this Python-only fix. Dashboard
Playwright coverage is CI-owned locally; the import-gated file was
included in the focused pytest command and skipped because Playwright is
not installed in this environment.
2026-07-07 23:24:41 -05:00
Vinay Gupta 5fe4e7b195 fix(proxy): expose persistent savings metrics (#1647)
## Description

Closes #1616

Expose the proxy's durable `persistent_savings.lifetime` totals through
`/metrics` so Prometheus/Grafana scrapes can read the same lifetime
savings counters already visible in `/stats` and `/stats-history`.

The existing runtime counters remain process-local:
`headroom_tokens_saved_total` still resets with the proxy process. New
`headroom_persistent_savings_*` counters are sourced from the
`SavingsTracker` lifetime block.

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

## Changes Made

- Export durable lifetime savings counters from
`PrometheusMetrics.export()`:
  - `headroom_persistent_savings_requests_total`
  - `headroom_persistent_savings_tokens_saved_total`
  - `headroom_persistent_savings_input_tokens_total`
  - `headroom_persistent_savings_input_cost_usd_total`
  - `headroom_persistent_savings_compression_savings_usd_total`
- Add a restart regression proving runtime counters reset while
persistent savings counters remain available from the same savings file.
- Extend the existing `/stats-history` restart test with `/metrics`
endpoint assertions.
- Update metrics docs to distinguish runtime
`headroom_tokens_saved_total` from lifetime
`headroom_persistent_savings_tokens_saved_total`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
Local focused checks:
$ rtk /usr/bin/env HEADROOM_REQUIRE_RUST_CORE=false PYTHONPATH=. /tmp/headroom-1616-testenv/bin/python -m pytest tests/test_proxy_cache_ttl_metrics.py::test_prometheus_metrics_export_includes_extended_fields tests/test_proxy_cache_ttl_metrics.py::test_prometheus_export_includes_persistent_savings_after_restart
2 passed, 1 warning in 0.19s

$ rtk /tmp/headroom-1616-testenv/bin/python -m ruff check headroom/proxy/prometheus_metrics.py tests/test_proxy_cache_ttl_metrics.py tests/test_proxy_savings_history.py
All checks passed!

$ rtk /tmp/headroom-1616-testenv/bin/python -m ruff format --check headroom/proxy/prometheus_metrics.py tests/test_proxy_cache_ttl_metrics.py tests/test_proxy_savings_history.py
3 files already formatted

$ rtk git diff --check
# no output

GitHub Actions:
All non-skipped checks passed on PR #1647, including lint, build, build-wheel, test (1-4), test-agno, test-extras, test-dashboard-ui, docker-native-e2e, docker-init-e2e, docker-wrap-e2e, security checks, merge-conflicts, and PR governance.
```

## Real Behavior Proof

- Environment: local macOS worktree, throwaway Python env at
`/tmp/headroom-1616-testenv`, `PYTHONPATH=.`.
- Exact command / steps: recorded a compressed request through
`PrometheusMetrics.record_request()`, re-created `PrometheusMetrics`
with the same `SavingsTracker` path, then exported `/metrics` text.
- Observed result: runtime counters are zero after re-creating the
metrics object, while `headroom_persistent_savings_tokens_saved_total`
and related persistent counters still expose the durable lifetime
values.
- Not tested: full server-level pytest locally, because the local build
is blocked by the known native `headroom._core`/`esaxx-rs` build issue
(`fatal error: 'cstdint' file not found`). The app-level `/metrics`
assertions passed in GitHub Actions.

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

## Screenshots (if applicable)

N/A

## Additional Notes

This intentionally does not rename or hydrate the existing runtime
`headroom_tokens_saved_total` counter. That preserves the current
process-local semantics and gives external dashboards a dedicated
lifetime series that maps directly to `/stats.persistent_savings`.

`mypy headroom` was not run as a standalone local command. CHANGELOG is
N/A for this narrow proxy metrics fix unless maintainers prefer an
entry.
2026-07-01 23:28:12 -05:00
Lakshya Sharma 4658721ea0 feat(cache): attribute prompt-cache misses to TTL lapse vs prefix change (#1313) (#1343)
## Description

A low prompt-cache hit rate is hard to act on without knowing *why*
turns miss. Two very different causes need very different responses:

- **TTL lapse** — the session went idle longer than the provider's cache
lifetime, so the entry expired. The fix is a longer TTL (e.g.
Anthropic's 1h breakpoint instead of the 5m default).
- **Prefix change** — the cacheable message prefix shifted, so the new
request couldn't match the cached key. A longer TTL won't help here at
all.

Right now those look identical from the dashboard (just "cache_read was
0"). This adds the attribution so a user can actually decide 5m vs 1h.

Closes #1313

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] 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

`PrefixCacheTracker` already kept the previous turn's forwarded messages
and a per-turn activity timestamp, so the signal was already there — it
just wasn't being read.

- **`prefix_tracker.py`** — `classify_cache_miss()`: when a turn
expected a cached prefix (non-zero cached tokens last turn) but read 0
this turn, returns `ttl_expiry` if the idle gap exceeded the provider
cache TTL, else `prefix_change` if the forwarded prefix differs from
last turn's, else `unknown`. **TTL wins ties** — once the entry lapsed,
a coincident content change is moot, and the 5m-vs-1h decision is
exactly what the TTL signal answers. A 1h-breakpoint session can widen
the window via `PrefixFreezeConfig.cache_ttl_seconds`. Cold starts and
hits return `is_miss=False`.
- **Anthropic handlers (streaming + non-streaming)** — classify BEFORE
`update_from_response` overwrites the last-turn state the classifier
reads, then record the reason.
- **`prometheus_metrics.py`** — a per-provider/per-reason counter,
`record_cache_miss_attribution()`, reset handling, and a
`headroom_cache_miss_attribution_total{provider,reason}` export series.
- **`cost.py`** — `build_prefix_cache_stats()` aggregates a
`miss_attribution` block (per-provider + totals, with the ttl/prefix
split as a % of *attributed* misses, so `unknown` doesn't dilute the
headline).
- **dashboard** — a "Cache Miss Attribution" panel (TTL expiry / prefix
change / unknown / total) with a "mostly TTL lapse" vs "mostly prefix
change" headline.

Scoped to Anthropic for this first cut (where the tracker is fully
wired); OpenAI/Gemini can follow once the shape is proven.

## Testing

- [x] Unit tests pass (`pytest`)
- [ ] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
$ python -m pytest tests/test_cache/test_prefix_tracker.py -q
38 passed
# 29 existing + 9 new classifier tests (TestClassifyCacheMiss).

$ python -m pytest tests/test_proxy_cache_ttl_metrics.py -k "miss_attribution or reset_runtime_clears" -q
5 passed, 8 deselected
# new: counter bucketing, stats aggregation, empty case, /metrics export, reset.
```

The full `test_proxy_cache_ttl_metrics.py` /
`test_proxy_dashboard_stats_cache.py` files have some failures in this
sandbox (`test_stats_endpoint_*`, streaming-parser, reset-counters) —
those spin up the proxy server / Rust `_core` extension, which isn't
built here. I confirmed via `git stash` that they fail identically on
`main` without my changes, so they're pre-existing and unrelated. My
additions to the stats dict are purely additive and don't break any
passing assertion.

## Real Behavior Proof

- Environment: Windows 11, Python 3.10. The Rust `_core` extension and a
live proxy aren't available in this checkout.
- Exact command / steps: drove `classify_cache_miss()` through every
branch with a faithful warm-then-miss sequence; drove
`record_cache_miss_attribution()` → `build_prefix_cache_stats()` →
`export()` end to end.
- Observed result: classifier returns
`cold_start`/`hit`/`ttl_expiry`/`prefix_change`/`unknown` correctly, TTL
wins the tie when both signals fire, a growing (append-only) prefix is
treated as stable, and the 1h override widens the window. The stats
builder produces `miss_attribution.totals`
(`ttl_expiry`/`prefix_change`/`unknown`/`total` +
`ttl_expiry_pct`/`prefix_change_pct` over attributed misses) and
`by_provider`; `/metrics` emits
`headroom_cache_miss_attribution_total{provider="anthropic",reason="ttl_expiry"}`.
- Not tested: a live Anthropic session through the running proxy with a
real idle-then-resume to confirm the handler wiring fires end-to-end. I
verified the handler integration by reading scope/order (classify before
`update_from_response`, `provider_name`/`self.metrics` in scope) and
unit-tested every layer it calls, but didn't exercise the actual server
loop.

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

## Additional Notes

- The classifier is intentionally pure (takes the cache-read result +
current forwarded messages + an optional idle override) so it's
order-independent and unit-testable without a live tracker clock.
- No README/docs change yet — this surfaces in the dashboard and
`/metrics`, which are self-describing; happy to add a docs page if you'd
like one.
- CHANGELOG.md isn't touched — release-please generates it from the
`feat(cache):` commit subject.
- Follow-ups if useful: extend to OpenAI/Gemini handlers, and add a
per-provider breakdown row in the dashboard panel (the stats already
carry `by_provider`).
2026-06-24 09:50:34 -05:00
JerrettDavisandCopilot be6aa14110 feat: expose proxy OTEL metrics and Langfuse status
Wire the proxy's operational metrics facade into the new observability
layer, expand built-in Prometheus export, surface OTEL and Langfuse status
in /stats, and document the split between anonymous telemetry, OTEL metrics,
and Langfuse traces.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-09 21:20:46 -05:00
JerrettDavis a6787556be Add observed cache TTL metrics and dashboard coverage 2026-04-06 21:13:30 -05:00