Files
headroom/tests/test_session_affinity.py
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

73 lines
2.4 KiB
Python

"""Session-affinity header: sent to providers that route on it, and nowhere else."""
from __future__ import annotations
import httpx
import pytest
pytest.importorskip("fastapi")
from fastapi.testclient import TestClient
from headroom.proxy.server import ProxyConfig, create_app
REPLY = {
"id": "m1",
"type": "message",
"role": "assistant",
"content": [{"type": "text", "text": "ok"}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 3, "output_tokens": 1},
}
def forwarded_headers(upstream: str, extra: dict[str, str] | None = None) -> list[dict]:
config = ProxyConfig(
optimize=False,
cache_enabled=False,
rate_limit_enabled=False,
cost_tracking_enabled=False,
log_requests=False,
ccr_inject_tool=False,
ccr_handle_responses=False,
ccr_context_tracking=False,
anthropic_api_url=upstream,
)
sent: list[dict] = []
async def fake_upstream(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001, ANN003
sent.append({k.lower(): v for k, v in headers.items()})
return httpx.Response(200, json=REPLY)
with TestClient(create_app(config)) as client:
client.app.state.proxy._retry_request = fake_upstream
for _ in range(2):
response = client.post(
"/v1/messages",
headers={"x-api-key": "k", "anthropic-version": "2023-06-01", **(extra or {})},
json={
"model": "kimi",
"max_tokens": 5,
"system": "You are a coding agent.",
"messages": [{"role": "user", "content": "hi"}],
},
)
assert response.status_code == 200
return sent
def test_fireworks_gets_one_stable_affinity_per_conversation() -> None:
first, second = forwarded_headers("https://api.fireworks.ai/inference")
assert first["x-session-affinity"]
assert first["x-session-affinity"] == second["x-session-affinity"]
@pytest.mark.parametrize("upstream", ["https://api.anthropic.com", "http://vllm.internal:8000"])
def test_other_upstreams_get_no_affinity_header(upstream: str) -> None:
assert all("x-session-affinity" not in h for h in forwarded_headers(upstream))
def test_client_affinity_header_is_kept() -> None:
sent = forwarded_headers("https://api.fireworks.ai/inference", {"X-Session-Affinity": "mine"})
assert all(h["x-session-affinity"] == "mine" for h in sent)