mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(proxy): retain final backend streaming usage (#4814)
## Description
Translated OpenAI streams (`/v1/chat/completions` through a backend such
as `anyllm` or LiteLLM) recorded the **first nonzero** usage snapshot
instead of the last one.
`_absorb` in `_stream_openai_via_backend` wrote a counter only when the
accumulator was still falsy:
```python
if key in usage and not stream_state.get(key):
stream_state[key] = usage[key]
```
A provider that reports climbing cumulative snapshots on successive
content chunks therefore had every later frame thrown away. Replaying
the two frames from the issue through the real proxy path, `/stats`
recorded 10 input / 1 output tokens and `/metrics` recorded 2 cache
reads — while the client received both frames intact. The bug is in
accounting after delivery, not a dropped upstream event.
Closes #4263
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- `_parse_sse_usage_from_buffer` (openai branch): absent counters no
longer default to `0`. A frame that omits a field was previously
indistinguishable from one reporting an explicit zero, which is a
prerequisite for "absent keeps the last value".
- `_absorb`: assigns unconditionally, so the latest cumulative snapshot
wins. An absent field keeps its earlier value; an explicit zero still
replaces it.
- Removed `_parse_completion_tokens_from_sse_chunk`. It existed to catch
completion-only frames, but the buffered SSE parser already handles
those, and its `not stream_state["output_tokens"]` guard latched the
output count a second time.
- Replaced that helper's unit tests with eight regressions driving the
real `_stream_openai_via_backend` path through stream finalization, in
Chat and Responses shapes.
- `docs/content/docs/proxy.mdx`: one paragraph on the `POST
/v1/chat/completions` page documenting the accounting rule, in the
published docs site.
Net: -100/+113 lines, of which most deletions are the removed helper and
its implementation-only tests.
## 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
$ python -m pytest tests/test_streaming_usage_parser.py -q
........ [100%]
8 passed in 1.01s
$ ruff check headroom/proxy/handlers/streaming.py tests/test_streaming_usage_parser.py
All checks passed!
$ ruff format --check headroom/proxy/handlers/streaming.py tests/test_streaming_usage_parser.py
2 files already formatted
$ mypy headroom/proxy/handlers/streaming.py
Success: no issues found in 1 source file
```
Regression set — the new tests against the unfixed handler (`git stash`
of `streaming.py` only):
```text
$ python -m pytest tests/test_streaming_usage_parser.py -q
FAILED ...[latest-snapshot-chat] assert (10, 1, 2, 3) == (13, 5, 9, 1)
FAILED ...[latest-snapshot-responses]
FAILED ...[partial-chat] assert (10, 1, 2, 3) == (10, 5, 2, 3)
FAILED ...[partial-responses]
FAILED ...[explicit-zero-chat] assert (10, 1, 2, 3) == (0, 0, 0, 0)
FAILED ...[explicit-zero-responses]
6 failed, 2 passed in 1.07s
```
Six fail before the fix, all eight pass after — matching the issue
exactly.
Wider streaming and parser suites:
```text
$ python -m pytest tests/test_streaming_usage_parser.py tests/test_streaming_sse_malformed_events.py \
tests/test_provider_billed_input.py tests/test_proxy_cache_ttl_metrics.py tests/test_proxy_handler_helpers.py \
tests/test_proxy_streaming_request_logger.py tests/test_route_advice.py tests/test_h2_stream_reset_retry.py \
tests/test_proxy_streaming_resilience.py tests/test_proxy_streaming_ratelimit_headers.py -q
3 failed, 607 passed in 10.21s
```
The three failures are
`tests/test_proxy_cache_ttl_metrics.py::test_stats_endpoint_reports_*`,
which raise `SystemExit: 78` from `_check_rust_core()` in `server.py`.
They are environmental (unbuilt Rust core in this checkout) and fail
identically on unmodified `upstream/main` with this branch stashed —
unrelated to this change.
## Real Behavior Proof
- Environment: Windows, Python 3.13.11, this branch, `PYTHONPATH` set to
the checkout.
- Exact command / steps: replayed the issue's two usage snapshots as a
Chat stream through `_stream_openai_via_backend` with a stub backend,
then read the resulting `RequestOutcome`.
- Observed result: the corrected counts from the issue; previously 10 /
1 / 2.
```text
provider_input_tokens=13 (expect 13)
output_tokens =5 (expect 5)
cache_read_tokens =9 (expect 9)
```
- Not tested: a live `anyllm`/LiteLLM upstream over real HTTP (no
credentials in this environment). The replay drives the identical
handler and parser path the proxy uses; the frames are byte-for-byte the
issue's.
## Runtime Rollout Safety
- Rollout-managed feature(s): none.
- Minimum rollout channel: n/a.
- Stable/default behavior changed: token accounting for translated
OpenAI streams now records the final snapshot. This is the fix; counts
move up from truncated to complete.
- Kill switch / disable path: none beyond reverting this commit.
- Unsafe override required: none.
- Qualification impact: none.
- Rollback path: `git revert`.
## 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 did **not** edit `CHANGELOG.md`
## Additional Notes
Authorship is credited to @oxura, who diagnosed this in #4263 and wrote
the original patch on their fork; they were holding it back on the
ten-open-PR limit. This PR carries their change rebased onto current
`upstream/main` (their branch was cut from `fbf7bc32`, and
`streaming.py` has since drifted ~200 lines), with the commit message
and tests adapted to the current tree. Their `Authored-by` trailer is on
the commit.
One hunk from their patch was redirected: they documented the rule in
`wiki/proxy.md`, which `AGENTS.md:38` says is unpublished and must not
receive new content, so the paragraph now lives on the `POST
/v1/chat/completions` page in `docs/content/docs/proxy.mdx`. Thanks to
Devin Review for flagging it.
Co-authored-by: oxura <grozafroza44@gmail.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
oxura
JerrettDavis
parent
199912e020
commit
93331f2874
@@ -532,6 +532,8 @@ Anthropic API format. The proxy compresses messages, forwards to Anthropic, and
|
||||
|
||||
OpenAI API format. The proxy compresses messages, forwards to OpenAI, and returns the response.
|
||||
|
||||
On translated backends (`anyllm`, `litellm-<provider>`), streaming token accounting uses the latest provider usage snapshot. Providers may repeat a cumulative `usage` block on several content chunks before the terminal frame; the final counts win. A frame that omits a field leaves the earlier value alone, while an explicitly reported zero replaces it — so `/stats` and the cache-hit-rate metrics report what the provider last said, not the first nonzero count it sent.
|
||||
|
||||
### `POST /v1/responses`
|
||||
|
||||
OpenAI Responses API format. The proxy compresses `input` payloads where applicable, forwards the request, and returns the response.
|
||||
|
||||
@@ -184,36 +184,6 @@ def _sse_dict(value: Any) -> dict[str, Any]:
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _parse_completion_tokens_from_sse_chunk(chunk_bytes: bytes) -> int | None:
|
||||
"""Extract `usage.completion_tokens` from a single SSE chunk if present.
|
||||
|
||||
Returns the integer count when the chunk carries a usage frame (LiteLLM
|
||||
emits this only when the request included
|
||||
``stream_options.include_usage=true``), or None when no usage data is
|
||||
present (the typical content-only chunk path) or when the chunk fails
|
||||
to parse. Used by the OpenAI-via-backend stream path to track
|
||||
completion tokens online instead of buffering the entire response.
|
||||
"""
|
||||
try:
|
||||
decoded = chunk_bytes.decode("utf-8", errors="replace")
|
||||
except (UnicodeDecodeError, AttributeError):
|
||||
return None
|
||||
for line in decoded.split("\n"):
|
||||
line = line.strip()
|
||||
if not line.startswith("data: ") or line == "data: [DONE]":
|
||||
continue
|
||||
try:
|
||||
data = json.loads(line[6:])
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
continue
|
||||
if not isinstance(data, dict):
|
||||
continue
|
||||
chunk_usage = data.get("usage")
|
||||
if isinstance(chunk_usage, dict):
|
||||
return int(chunk_usage.get("completion_tokens", 0) or 0)
|
||||
return None
|
||||
|
||||
|
||||
class StreamingMixin:
|
||||
"""Mixin providing streaming response methods for HeadroomProxy."""
|
||||
|
||||
@@ -422,21 +392,27 @@ class StreamingMixin:
|
||||
# response.usage on response.completed.
|
||||
input_tokens = chunk_usage.get("prompt_tokens")
|
||||
if input_tokens is None:
|
||||
input_tokens = chunk_usage.get("input_tokens", 0)
|
||||
input_tokens = chunk_usage.get("input_tokens")
|
||||
output_tokens = chunk_usage.get("completion_tokens")
|
||||
if output_tokens is None:
|
||||
output_tokens = chunk_usage.get("output_tokens", 0)
|
||||
usage_found["input_tokens"] = usage_int(input_tokens)
|
||||
usage_found["output_tokens"] = usage_int(output_tokens)
|
||||
output_tokens = chunk_usage.get("output_tokens")
|
||||
# Only report fields this frame actually carries: an
|
||||
# absent counter must leave the caller's last known
|
||||
# value alone, while an explicit zero replaces it.
|
||||
if input_tokens is not None:
|
||||
usage_found["input_tokens"] = usage_int(input_tokens)
|
||||
if output_tokens is not None:
|
||||
usage_found["output_tokens"] = usage_int(output_tokens)
|
||||
details = (
|
||||
chunk_usage.get("prompt_tokens_details")
|
||||
or chunk_usage.get("input_tokens_details")
|
||||
or {}
|
||||
)
|
||||
if isinstance(details, dict):
|
||||
usage_found["cache_read_input_tokens"] = usage_int(
|
||||
details.get("cached_tokens")
|
||||
)
|
||||
if details.get("cached_tokens") is not None:
|
||||
usage_found["cache_read_input_tokens"] = usage_int(
|
||||
details["cached_tokens"]
|
||||
)
|
||||
# Responses reports billed cache writes itself; the
|
||||
# Anthropic-shape key routes them down the real-write
|
||||
# branch instead of inferring them from uncached.
|
||||
@@ -2542,6 +2518,9 @@ class StreamingMixin:
|
||||
completed_normally = False
|
||||
stream_failed = False
|
||||
|
||||
# Usage frames are cumulative snapshots of the same turn: each one
|
||||
# supersedes the last, so an absent field keeps its earlier value
|
||||
# and an explicit zero replaces it.
|
||||
def _absorb(usage: dict[str, int] | None) -> None:
|
||||
if not usage:
|
||||
return
|
||||
@@ -2551,7 +2530,7 @@ class StreamingMixin:
|
||||
"cache_read_input_tokens",
|
||||
"cache_creation_input_tokens",
|
||||
):
|
||||
if key in usage and not stream_state.get(key):
|
||||
if key in usage:
|
||||
stream_state[key] = usage[key]
|
||||
|
||||
try:
|
||||
@@ -2560,11 +2539,6 @@ class StreamingMixin:
|
||||
stream_state["sse_buffer"].extend(chunk_bytes)
|
||||
full_sse_bytes.extend(chunk_bytes)
|
||||
_absorb(self._parse_sse_usage_from_buffer(stream_state, "openai"))
|
||||
# Per-chunk fallback for upstreams that emit only
|
||||
# ``completion_tokens`` and not a full usage frame.
|
||||
parsed = _parse_completion_tokens_from_sse_chunk(chunk_bytes)
|
||||
if parsed is not None and not stream_state["output_tokens"]:
|
||||
stream_state["output_tokens"] = parsed
|
||||
yield chunk_bytes
|
||||
stream_failed = stream_state.get("stream_failed", False)
|
||||
completed_normally = (
|
||||
|
||||
@@ -1,60 +1,97 @@
|
||||
"""Unit tests for the online SSE usage parser used by the
|
||||
OpenAI-via-backend streaming path.
|
||||
"""Final provider usage must survive progressive and partial backend frames.
|
||||
|
||||
These tests pin the per-chunk parsing contract so streaming memory
|
||||
stays O(1) regardless of stream length — the prior implementation
|
||||
buffered the entire response just to scan the trailing usage frame.
|
||||
The OpenAI-via-backend stream path is fed cumulative usage snapshots: a
|
||||
provider may repeat `usage` on several content chunks with climbing counts
|
||||
before its terminal frame. Accounting must record the LAST snapshot, not
|
||||
the first nonzero one, and a frame that omits a counter must leave that
|
||||
counter alone rather than resetting it to zero.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
from headroom.proxy.handlers.streaming import _parse_completion_tokens_from_sse_chunk
|
||||
import pytest
|
||||
|
||||
from headroom.proxy.handlers.streaming import StreamingMixin
|
||||
|
||||
|
||||
def test_returns_completion_tokens_from_usage_frame() -> None:
|
||||
chunk = b'data: {"id":"x","usage":{"prompt_tokens":10,"completion_tokens":42}}\n\n'
|
||||
assert _parse_completion_tokens_from_sse_chunk(chunk) == 42
|
||||
@pytest.mark.parametrize("responses", [False, True], ids=["chat", "responses"])
|
||||
@pytest.mark.parametrize(
|
||||
("last", "expected"),
|
||||
[
|
||||
(
|
||||
{
|
||||
"input_tokens": 13,
|
||||
"output_tokens": 5,
|
||||
"input_tokens_details": {"cached_tokens": 9, "cache_write_tokens": 1},
|
||||
},
|
||||
(13, 5, 9, 1),
|
||||
),
|
||||
({"output_tokens": 5}, (10, 5, 2, 3)),
|
||||
(
|
||||
{
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
"input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0},
|
||||
},
|
||||
(0, 0, 0, 0),
|
||||
),
|
||||
({}, (10, 1, 2, 3)),
|
||||
],
|
||||
ids=["latest-snapshot", "partial", "explicit-zero", "absent"],
|
||||
)
|
||||
def test_backend_stream_records_latest_present_usage(responses, last, expected):
|
||||
initial = {
|
||||
"input_tokens": 10,
|
||||
"output_tokens": 1,
|
||||
"input_tokens_details": {"cached_tokens": 2, "cache_write_tokens": 3},
|
||||
}
|
||||
|
||||
def frame(usage):
|
||||
if responses:
|
||||
data = {"response": {"usage": usage}}
|
||||
else:
|
||||
names = {
|
||||
"input_tokens": "prompt_tokens",
|
||||
"output_tokens": "completion_tokens",
|
||||
"input_tokens_details": "prompt_tokens_details",
|
||||
}
|
||||
data = {"usage": {names[key]: value for key, value in usage.items()}}
|
||||
return f"data: {json.dumps(data)}\n\n"
|
||||
|
||||
def test_returns_none_for_content_only_chunk() -> None:
|
||||
chunk = b'data: {"choices":[{"delta":{"content":"hi"}}]}\n\n'
|
||||
assert _parse_completion_tokens_from_sse_chunk(chunk) is None
|
||||
class Backend:
|
||||
name = "openai"
|
||||
|
||||
async def stream_openai_message(self, body, headers):
|
||||
yield frame(initial)
|
||||
yield 'data: {"choices":[{"delta":{"content":"answer"}}]}\n\n'
|
||||
yield frame(last)
|
||||
yield "data: [DONE]\n\n"
|
||||
|
||||
def test_returns_none_for_done_marker() -> None:
|
||||
assert _parse_completion_tokens_from_sse_chunk(b"data: [DONE]\n\n") is None
|
||||
class Handler(StreamingMixin):
|
||||
config = SimpleNamespace(ccr_inject_tool=False)
|
||||
anthropic_backend = Backend()
|
||||
|
||||
async def _record_request_outcome(self, outcome):
|
||||
self.outcome = outcome
|
||||
|
||||
def test_returns_none_for_invalid_json() -> None:
|
||||
assert _parse_completion_tokens_from_sse_chunk(b"data: not-json\n\n") is None
|
||||
handler = Handler()
|
||||
|
||||
async def consume():
|
||||
response = await handler._stream_openai_via_backend(
|
||||
{"messages": []}, {}, "model", "request", 0.0, 10, 10, 0, [], {}, 0.0
|
||||
)
|
||||
async for _ in response.body_iterator:
|
||||
pass
|
||||
|
||||
def test_returns_none_for_empty_chunk() -> None:
|
||||
assert _parse_completion_tokens_from_sse_chunk(b"") is None
|
||||
|
||||
|
||||
def test_handles_chunk_with_multiple_frames() -> None:
|
||||
# SSE frames can batch across a single chunk write.
|
||||
chunk = (
|
||||
b'data: {"choices":[{"delta":{"content":"a"}}]}\n\n'
|
||||
b'data: {"choices":[{"delta":{"content":"b"}}],"usage":{"completion_tokens":7}}\n\n'
|
||||
)
|
||||
assert _parse_completion_tokens_from_sse_chunk(chunk) == 7
|
||||
|
||||
|
||||
def test_treats_zero_completion_tokens_as_zero_not_none() -> None:
|
||||
chunk = b'data: {"usage":{"completion_tokens":0}}\n\n'
|
||||
assert _parse_completion_tokens_from_sse_chunk(chunk) == 0
|
||||
|
||||
|
||||
def test_handles_non_dict_data_payload() -> None:
|
||||
# Edge case: a JSON array or scalar where a dict was expected.
|
||||
chunk = b"data: [1,2,3]\n\n"
|
||||
assert _parse_completion_tokens_from_sse_chunk(chunk) is None
|
||||
|
||||
|
||||
def test_handles_invalid_utf8_bytes_without_crashing() -> None:
|
||||
# Leading invalid UTF-8 bytes corrupt the "data: " prefix; parser
|
||||
# should skip the malformed line and return None rather than raise.
|
||||
chunk = b'\xff\xfedata: {"usage":{"completion_tokens":3}}\n\n'
|
||||
assert _parse_completion_tokens_from_sse_chunk(chunk) is None
|
||||
asyncio.run(consume())
|
||||
outcome = handler.outcome
|
||||
assert outcome.status_code == 200
|
||||
assert (
|
||||
outcome.provider_input_tokens,
|
||||
outcome.output_tokens,
|
||||
outcome.cache_read_tokens,
|
||||
outcome.cache_write_tokens,
|
||||
) == expected
|
||||
assert outcome.cache_inferred is False
|
||||
|
||||
Reference in New Issue
Block a user