Files
headroom/tests/test_stream_output_tokens.py
755293dd68 fix(proxy): count output tokens from CRLF-framed SSE streams too (#4298)
## Description

When an upstream streams a response with no usage chunk,
`estimate_output_tokens()` (`headroom/proxy/stream_output_tokens.py`)
recovers the output-token count from the stream itself. It uses the
request's output ceiling when the turn stopped on it, otherwise the
generated text, and only as a last resort `total_bytes // 40`. All of
that goes through `_iter_sse_payloads()`, which splits events on
`"\n\n"` and lines on `"\n"` only.

SSE allows CRLF and bare-CR line endings, and the rest of the proxy
handles them (#649). A CRLF-framed stream has no `"\n\n"` in it, though:
it becomes one block, every `data:` line keeps a trailing `\r`, the
concatenated payloads aren't valid JSON, and nothing is recovered. The
stop reason isn't found either, so even the exact-ceiling rung is
skipped and the estimate falls through to the raw-bytes heuristic. For
the stream in the proof below that's 281 instead of 130 tokens, a 2.2×
over-count on the number that feeds the cost model and the
output-savings estimate.

Closes: N/A (no matching issue found)

## 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/stream_output_tokens.py`: `_iter_sse_payloads()`
normalises `\r\n` and bare `\r` to `\n` before splitting. JSON payloads
escape their own carriage returns (`\r` inside a string is the two
characters `\` `r`), so this can't alter the data. LF streams are
processed exactly as before. The function is shared by
`extract_stream_text()` and the ceiling detector, so both rungs are
fixed.
- `tests/test_stream_output_tokens.py`:
`test_crlf_and_cr_framed_streams_are_parsed[crlf, cr]` takes an LF
stream that ends on `finish_reason: "length"`, re-frames it with CRLF
and with bare CR, and checks that the extracted text matches the LF
stream's, that the ceiling rung returns `(64, "exact_ceiling")`, and
that the text rung returns `estimated_text`.

## Testing

- [x] Unit tests pass (`pytest`): `tests/test_stream_output_tokens.py`,
`tests/test_streaming_usage_parser.py`,
`tests/test_streaming_sse_malformed_events.py`,
`tests/test_sse_byte_buffer_policy.py`,
`tests/test_proxy_streaming_resilience.py`,
`tests/test_openai_streaming_backend.py`,
`tests/test_sse_utf8_split.py`, not the full suite
- [x] Linting passes (`ruff check .`): on the changed files
- [ ] Type checking passes (`mypy headroom`): not run
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

New test on `main` (fix reverted, test kept):

```text
$ python -m pytest tests/test_stream_output_tokens.py -q
E   AssertionError: assert '' == 'Hello world,...Hello world, '
E   AssertionError: assert '' == 'Hello world,...Hello world, '
FAILED tests/test_stream_output_tokens.py::test_crlf_and_cr_framed_streams_are_parsed[crlf]
FAILED tests/test_stream_output_tokens.py::test_crlf_and_cr_framed_streams_are_parsed[cr]
========================= 2 failed, 27 passed in 1.31s =========================
```

With the fix:

```text
$ python -m pytest tests/test_stream_output_tokens.py tests/test_streaming_usage_parser.py tests/test_streaming_sse_malformed_events.py \
    tests/test_sse_byte_buffer_policy.py tests/test_proxy_streaming_resilience.py tests/test_openai_streaming_backend.py tests/test_sse_utf8_split.py -q
======================== 425 passed, 3 skipped in 8.34s ========================

$ ruff check headroom/proxy/stream_output_tokens.py tests/test_stream_output_tokens.py
All checks passed!
$ ruff format --check headroom/proxy/stream_output_tokens.py tests/test_stream_output_tokens.py
2 files already formatted
```

## Real Behavior Proof

- Environment: macOS 27.0.1 (arm64), Python 3.12.11, source tree on this
branch (native `headroom._core` from the 0.41.0 wheel), real `headroom
proxy` in front of a local stub Anthropic upstream that streams
`/v1/messages` with CRLF framing (`event:`/`data:` lines ending `\r\n`)
and no `usage` fields, `HEADROOM_OFFLINE=1`
- Exact command / steps: started the stub on :18951 and
`HEADROOM_OFFLINE=1 python -m headroom.cli proxy --port 18952 --mode
token --anthropic-api-url http://127.0.0.1:18951 --no-rate-limit`, then
sent a streaming `POST /v1/messages` (`max_tokens: 1024`). The stub
streams 81 `text_delta` events (521 chars of text, 11,275 bytes on the
wire) and ends with `stop_reason: end_turn`. I read the proxy's `No
usage chunk in SSE` log line, on `main` and on this branch.
- Observed result: the client gets the same 11,275 bytes in both runs.
On `main` the proxy can't parse the stream and records 281 output tokens
from raw bytes. On this branch it records 130, counted from the stream
text.

  ```text
  == main
  proxy status: 200 | streamed bytes to client: 11275
No usage chunk in SSE; output_tokens=281 (estimated from 11275 raw SSE
bytes)
  == this branch
  proxy status: 200 | streamed bytes to client: 11275
  No usage chunk in SSE; output_tokens=130 (counted from stream text)
  ```
- Not tested: a real upstream that frames with CRLF (stub only); the
OpenAI chat path. There, without memory mode, the proxy doesn't buffer
the stream text at all, so the estimate is bytes-based on both branches.
That's a separate gap; I checked it with a CRLF OpenAI stub and got the
same number on `main` and on this branch.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: N/A
- Stable/default behavior changed: only for CRLF- or CR-framed streams
without a usage chunk: their output tokens are now counted from the text
or the ceiling instead of the raw-bytes fallback. LF streams are
unchanged.
- Kill switch / disable path: N/A
- 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
- [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)

## Additional Notes

Related but separate: #4252 covers CR-only frames in the streaming
byte-buffer parser (`sse_byte_buffer_policy`), a different code path.
This PR touches only the post-stream estimate.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-24 08:43:49 -07:00

304 lines
12 KiB
Python

"""Output tokens must be counted from the stream's text, not its wire size.
When an upstream sends no usage chunk, the proxy estimated output tokens as
``total_bytes // 40`` over the RAW SSE WIRE — ``data:`` prefixes, JSON
envelopes, ``role``/``finish_reason``/``id``/``model`` fields and blank-line
framing all included. From a field log (Copilot Chat, 0.36.x):
Could not parse output_tokens from SSE, estimating 8 from 334 bytes
The divisor is a fudge for "bytes per token including framing", so the error
tracked how chattily the answer was chunked rather than how long it was: the
same answer split into more deltas scores higher purely for being split.
GitHub's Copilot CAPI is one of the upstreams that omits the usage chunk, so
this was every Copilot turn's output number — and output tokens feed the
output-shaping savings estimate and the cost model.
"""
from __future__ import annotations
import json
import pytest
from headroom.proxy.stream_output_tokens import (
TEXT_CHARS_PER_TOKEN,
WIRE_BYTES_PER_TOKEN,
estimate_output_tokens,
extract_stream_text,
)
def _sse(*objs: dict, done: bool = True) -> str:
out = "".join(f"data: {json.dumps(o)}\n\n" for o in objs)
return out + ("data: [DONE]\n\n" if done else "")
def _chat_delta(text: str) -> dict:
return {"choices": [{"index": 0, "delta": {"content": text}}]}
# --------------------------------------------------------------------------- #
# Extraction, per surface
# --------------------------------------------------------------------------- #
def test_openai_chat_deltas() -> None:
sse = _sse(
{"choices": [{"delta": {"role": "assistant"}}]},
_chat_delta("Hello "),
_chat_delta("world"),
{"choices": [{"delta": {}, "finish_reason": "stop"}]},
)
assert extract_stream_text(sse) == "Hello world"
def test_anthropic_content_block_deltas() -> None:
sse = _sse(
{"type": "message_start", "message": {"id": "msg_1"}},
{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "abc"}},
{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "def"}},
{"type": "message_stop"},
done=False,
)
assert extract_stream_text(sse) == "abcdef"
def test_openai_responses_deltas() -> None:
sse = _sse(
{"type": "response.output_text.delta", "delta": "part one "},
{"type": "response.output_text.delta", "delta": "part two"},
)
assert extract_stream_text(sse) == "part one part two"
def test_reasoning_and_tool_arguments_are_billed_output_too() -> None:
"""Omitting these under-counts exactly the most expensive turns."""
sse = _sse(
{"choices": [{"delta": {"reasoning_content": "thinking hard"}}]},
{"choices": [{"delta": {"tool_calls": [{"function": {"arguments": '{"path":"a.py"}'}}]}}]},
)
text = extract_stream_text(sse)
assert "thinking hard" in text
assert '{"path":"a.py"}' in text
def test_anthropic_thinking_and_partial_json() -> None:
sse = _sse(
{"type": "content_block_delta", "delta": {"thinking": "plan"}},
{"type": "content_block_delta", "delta": {"partial_json": '{"a":1}'}},
done=False,
)
assert extract_stream_text(sse) == 'plan{"a":1}'
# --------------------------------------------------------------------------- #
# Malformed input must never raise — this runs on the response path
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize(
"sse",
[
"",
"data: not-json\n\n",
"data: [DONE]\n\n",
"garbage without data prefix\n\n",
'data: {"choices": "not-a-list"}\n\n',
'data: {"choices": [null]}\n\n',
'data: {"choices": [{"delta": null}]}\n\n',
'data: {"choices": [{"delta": {"content": 42}}]}\n\n',
'data: {"type": "content_block_delta", "delta": "not-a-dict"}\n\n',
"data:\n\n",
],
)
def test_malformed_streams_yield_empty_not_an_exception(sse: str) -> None:
assert extract_stream_text(sse) == ""
def test_multi_line_data_fields_concatenate() -> None:
"""Per the SSE spec, and real streams do it."""
payload = json.dumps(_chat_delta("joined"))
half = len(payload) // 2
sse = f"data: {payload[:half]}\ndata: {payload[half:]}\n\n"
assert extract_stream_text(sse) == "joined"
@pytest.mark.parametrize("newline", ["\r\n", "\r"], ids=["crlf", "cr"])
def test_crlf_and_cr_framed_streams_are_parsed(newline: str) -> None:
"""SSE allows CRLF and bare CR line endings; the proxy forwards both (#649)."""
lf = _sse(
_chat_delta("Hello world, " * 20),
{"choices": [{"index": 0, "delta": {}, "finish_reason": "length"}]},
)
sse = lf.replace("\n", newline)
assert extract_stream_text(sse) == extract_stream_text(lf) == "Hello world, " * 20
assert estimate_output_tokens(
sse_text=sse, total_bytes=len(sse.encode()), body={"max_tokens": 64}
) == (64, "exact_ceiling")
assert estimate_output_tokens(sse_text=sse, total_bytes=len(sse.encode())) == (
len("Hello world, " * 20) // TEXT_CHARS_PER_TOKEN,
"estimated_text",
)
# --------------------------------------------------------------------------- #
# The estimate itself
# --------------------------------------------------------------------------- #
def test_text_beats_the_wire_heuristic_on_the_reported_shape() -> None:
"""A chunky stream: framing dominates the wire, so bytes//40 misreads it."""
sse = _sse(*[_chat_delta(w) for w in ("The ", "quick ", "brown ", "fox ", "jumps")])
total_bytes = len(sse.encode())
tokens, source = estimate_output_tokens(sse_text=sse, total_bytes=total_bytes)
assert source == "estimated_text"
# "The quick brown fox jumps" is 25 chars -> 6 tokens.
assert tokens == len("The quick brown fox jumps") // TEXT_CHARS_PER_TOKEN
# The old estimator scored this stream far higher purely for its framing.
assert total_bytes // WIRE_BYTES_PER_TOKEN > tokens
def test_chunking_no_longer_changes_the_answer() -> None:
"""Same text, different delta split — the count must not move."""
text = "identical content across both streams"
one = _sse(_chat_delta(text))
many = _sse(*[_chat_delta(c) for c in text])
a, _ = estimate_output_tokens(sse_text=one, total_bytes=len(one.encode()))
b, _ = estimate_output_tokens(sse_text=many, total_bytes=len(many.encode()))
assert a == b
# And the wire-based estimator would have disagreed wildly.
assert len(one.encode()) // WIRE_BYTES_PER_TOKEN != len(many.encode()) // WIRE_BYTES_PER_TOKEN
def test_a_short_answer_is_never_recorded_as_zero() -> None:
sse = _sse(_chat_delta("OK"))
tokens, source = estimate_output_tokens(sse_text=sse, total_bytes=len(sse.encode()))
assert source == "estimated_text"
assert tokens == 1
def test_falls_back_to_bytes_when_no_text_is_recoverable() -> None:
"""The upstream-error path reaches here with no stream text at all."""
tokens, source = estimate_output_tokens(sse_text="", total_bytes=800)
assert source == "estimated_bytes"
assert tokens == 800 // WIRE_BYTES_PER_TOKEN
def test_negative_or_zero_bytes_are_safe() -> None:
assert estimate_output_tokens(sse_text="", total_bytes=0) == (0, "estimated_bytes")
assert estimate_output_tokens(sse_text="", total_bytes=-5) == (0, "estimated_bytes")
# --------------------------------------------------------------------------- #
# A turn stopped by its output ceiling is counted exactly, never estimated.
#
# Measured against Anthropic while probing echo ratios: a Write tool call cut
# off by ``max_tokens`` billed 1500 output tokens and left ~45 characters of
# recoverable stream text. Tool arguments stream as ``input_json_delta``
# fragments, and an upstream that stops mid-object drops the incomplete
# remainder rather than emit unparseable JSON. The text rung reads that as ~11
# tokens: a 100x under-count, on the most expensive turns there are. Repeated
# at two ceilings, both exact:
#
# max_tokens=1500 -> usage.output_tokens=1500
# max_tokens=4096 -> usage.output_tokens=4096
#
# Which is the fix: the ceiling is denominated in output tokens, so a turn that
# stopped because it hit the ceiling produced exactly that many.
# --------------------------------------------------------------------------- #
def _truncated_anthropic_tool_call() -> str:
"""An Anthropic tool call whose arguments were cut off mid-JSON."""
return _sse(
{
"type": "content_block_start",
"index": 0,
"content_block": {"type": "tool_use", "id": "toolu_1", "name": "Write", "input": {}},
},
{
"type": "content_block_delta",
"index": 0,
"delta": {"type": "input_json_delta", "partial_json": '{"path"'},
},
{
"type": "content_block_delta",
"index": 0,
"delta": {"type": "input_json_delta", "partial_json": ': "a/b.py"'},
},
{"type": "message_delta", "delta": {"stop_reason": "max_tokens"}},
{"type": "message_stop"},
done=False,
)
def test_truncated_tool_call_is_counted_from_the_ceiling_not_the_text() -> None:
sse = _truncated_anthropic_tool_call()
tokens, source = estimate_output_tokens(
sse_text=sse, total_bytes=len(sse.encode()), body={"max_tokens": 1500}
)
assert source == "exact_ceiling"
assert tokens == 1500
# What the text rung would have said, and why it cannot be trusted here.
text_tokens, text_source = estimate_output_tokens(sse_text=sse, total_bytes=len(sse.encode()))
assert text_source == "estimated_text"
assert text_tokens < 50
def test_openai_chat_length_finish_reason_uses_max_completion_tokens() -> None:
sse = _sse(
_chat_delta("partial answer that ran out of room"),
{"choices": [{"index": 0, "delta": {}, "finish_reason": "length"}]},
)
tokens, source = estimate_output_tokens(
sse_text=sse, total_bytes=len(sse.encode()), body={"max_completion_tokens": 900}
)
assert (tokens, source) == (900, "exact_ceiling")
def test_openai_responses_incomplete_uses_max_output_tokens() -> None:
sse = _sse(
{"type": "response.output_text.delta", "delta": "cut off"},
{
"type": "response.incomplete",
"response": {"incomplete_details": {"reason": "max_output_tokens"}},
},
)
tokens, source = estimate_output_tokens(
sse_text=sse, total_bytes=len(sse.encode()), body={"max_output_tokens": 256}
)
assert (tokens, source) == (256, "exact_ceiling")
def test_a_turn_that_finished_normally_still_counts_its_text() -> None:
"""The new rung must not swallow the common case."""
sse = _sse(
_chat_delta("a complete answer "),
_chat_delta("that stopped on its own"),
{"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
)
tokens, source = estimate_output_tokens(
sse_text=sse, total_bytes=len(sse.encode()), body={"max_tokens": 4096}
)
assert source == "estimated_text"
assert tokens == len(extract_stream_text(sse)) // TEXT_CHARS_PER_TOKEN
def test_ceiling_rung_falls_through_when_the_body_does_not_carry_one() -> None:
"""A truncated turn with no usable ceiling must degrade, not guess."""
sse = _truncated_anthropic_tool_call()
for body in (None, {}, {"max_tokens": 0}, {"max_tokens": "1500"}):
_, source = estimate_output_tokens(sse_text=sse, total_bytes=len(sse.encode()), body=body)
assert source == "estimated_text", body
def test_boolean_ceiling_is_not_mistaken_for_a_token_count() -> None:
"""``bool`` is an ``int`` subclass; ``max_tokens: True`` is not 1 token."""
sse = _truncated_anthropic_tool_call()
_, source = estimate_output_tokens(
sse_text=sse, total_bytes=len(sse.encode()), body={"max_tokens": True}
)
assert source == "estimated_text"