Files
headroom/tests/test_streaming_usage_parser.py
93331f2874 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>
2026-11-16 19:51:50 -06:00

98 lines
3.0 KiB
Python

"""Final provider usage must survive progressive and partial backend frames.
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.
"""
import asyncio
import json
from types import SimpleNamespace
import pytest
from headroom.proxy.handlers.streaming import StreamingMixin
@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"
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"
class Handler(StreamingMixin):
config = SimpleNamespace(ccr_inject_tool=False)
anthropic_backend = Backend()
async def _record_request_outcome(self, outcome):
self.outcome = outcome
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
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