Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(ccr): preserve thinking blocks in buffered stream re-synthesis (#1897)
Rod Boevede085cc11d7
diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.pyindex f77aa41c6..27b51fa0f 100644--- a/headroom/proxy/handlers/streaming.py+++ b/headroom/proxy/handlers/streaming.py@@ -350,6 +350,19 @@ class StreamingMixin:# sequentially, but the index map is the source of truth.blocks_by_index: dict[int, dict[str, Any]] = {}current_block: dict[str, Any] | None = None+ # Track which block indices have already been appended to+ # `response["content"]`. Dedup used to be `target not in+ # response["content"]` — plain dict-equality. Two distinct blocks+ # that happen to accumulate identical values (most commonly two+ # separate empty `thinking` blocks, e.g. from a retried HTTP/2+ # stream reset redelivering a truncated segment) either got+ # wrongly collapsed into one, or — when their partial content+ # happened to differ (same index, unequal dict) — both slipped+ # through as duplicates. Indexing by `index` (falling back to+ # object identity for the legacy no-index path) makes dedup exact+ # regardless of what the accumulated content looks like: one+ # entry per block index, first `content_block_stop` wins.+ appended_block_keys: set[int] = set()for line in sse_data.split("\n"):if not line.startswith("data: "):@@ -456,12 +469,15 @@ class StreamingMixin:# Anthropic API.if target.get("type") == "thinking" and "thinking_buffer" in target:target["thinking"] = target.pop("thinking_buffer")- # Append the block exactly once. `current_block`- # may not match the indexed target if the stream- # interleaved multiple blocks; index-keyed map is- # authoritative.- if target not in response["content"]:+ # Append the block exactly once, keyed by its block+ # index (or object identity when no index was ever+ # assigned). `current_block` may not match the+ # indexed target if the stream interleaved multiple+ # blocks; index-keyed map is authoritative.+ block_key = idx if idx is not None else id(target)+ if block_key not in appended_block_keys:response["content"].append(target)+ appended_block_keys.add(block_key)current_block = Noneelif event_type == "message_delta":diff --git a/tests/test_sse_thinking_blocks.py b/tests/test_sse_thinking_blocks.pyindex 5ed2abd38..faee266c3 100644--- a/tests/test_sse_thinking_blocks.py+++ b/tests/test_sse_thinking_blocks.py@@ -265,3 +265,145 @@ def test_response_to_sse_rejects_unknown_content_block() -> None:{"content": [{"type": "future_block", "payload": "preserve me"}]},"anthropic",)+++# Issue #1876: CCR buffered-stream re-synthesis corrupted extended-thinking+# responses — `content_block_stop` deduped appended blocks by whole-dict+# equality (`target not in response["content"]`), so two distinct blocks+# that happened to be value-identical could collapse into one, or two+# stops for the *same* index with different accumulated content (a+# retried HTTP/2 stream reset redelivering a truncated segment) could+# both slip through as duplicates. Dedup is now keyed by block index.+++def test_distinct_empty_thinking_blocks_at_different_indices_both_survive() -> None:+ """Two separate empty `thinking` blocks are two blocks, not one.++ Regression guard: if dedup ever regresses to dict-equality, this+ collapses to a single entry since both blocks are value-identical.+ """+ parser = _Parser()+ events = [+ {"type": "message_start", "message": {"id": "msg_1", "model": "claude-opus-4"}},+ {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "thinking", "thinking": ""},+ },+ {"type": "content_block_stop", "index": 0},+ {+ "type": "content_block_start",+ "index": 1,+ "content_block": {"type": "thinking", "thinking": ""},+ },+ {"type": "content_block_stop", "index": 1},+ {+ "type": "content_block_start",+ "index": 2,+ "content_block": {"type": "text", "text": ""},+ },+ {+ "type": "content_block_delta",+ "index": 2,+ "delta": {"type": "text_delta", "text": "Here is my answer."},+ },+ {"type": "content_block_stop", "index": 2},+ ]+ response = parser._parse_sse_to_response(_build_sse(events), "anthropic")+ assert response is not None+ assert len(response["content"]) == 3+ assert response["content"][0]["type"] == "thinking"+ assert response["content"][0]["thinking"] == ""+ assert response["content"][1]["type"] == "thinking"+ assert response["content"][1]["thinking"] == ""+ # The text block that followed the two empty thinking blocks must not+ # be dropped — this is the "text blocks are missing entirely" half of+ # the reported corruption.+ assert response["content"][2]["type"] == "text"+ assert response["content"][2]["text"] == "Here is my answer."+++def test_redelivered_block_same_index_different_content_collapses_to_one_entry() -> None:+ """A fully redelivered content_block lifecycle (start/delta/stop) for+ an index that was already appended must not produce a second entry —+ even though the redelivered content differs from the first, which is+ exactly the case the old whole-dict-equality dedup missed. Reproduces+ an HTTP/2 stream-reset retry (`_stream_response`'s retry path)+ redelivering a fresh accumulation for the same block index: with the+ old `target not in response["content"]` check, the two dicts have+ unequal `thinking` text, so *both* slipped through as duplicate+ entries for one logical block.+ """+ parser = _Parser()+ events = [+ {"type": "message_start", "message": {"id": "msg_1", "model": "claude-opus-4"}},+ {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "thinking", "thinking": ""},+ },+ {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "thinking_delta", "thinking": "partial"},+ },+ {"type": "content_block_stop", "index": 0},+ # Full redelivery of the same index with different accumulated+ # content — must be ignored, not appended as a second block.+ {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "thinking", "thinking": ""},+ },+ {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "thinking_delta", "thinking": "full retried text"},+ },+ {"type": "content_block_stop", "index": 0},+ ]+ response = parser._parse_sse_to_response(_build_sse(events), "anthropic")+ assert response is not None+ assert len(response["content"]) == 1+ assert response["content"][0]["thinking"] == "partial"+++def test_buffered_ccr_extended_thinking_round_trip_preserves_all_blocks() -> None:+ """End-to-end shape for issue #1876: a buffered CCR continuation+ response with thinking -> text -> tool_use must reconstruct to SSE+ (the re-synthesis path `anthropic.py` uses for the client-facing+ stream) with the text preserved and the thinking block emitted+ exactly once, unduplicated."""+ parser = _Parser()+ response = {+ "id": "msg_final",+ "model": "claude-opus-4",+ "role": "assistant",+ "content": [+ {+ "type": "thinking",+ "thinking": "Now I have the context, let me answer.",+ "signature": "sig_final",+ },+ {"type": "text", "text": "Based on the retrieved context, here is the answer."},+ {"type": "tool_use", "id": "toolu_real_1", "name": "real_tool", "input": {"y": 2}},+ ],+ "stop_reason": "tool_use",+ "usage": {"input_tokens": 8, "output_tokens": 12},+ }++ sse_text = b"".join(parser._response_to_sse(response, "anthropic")).decode("utf-8")+ assert sse_text.count('"type": "thinking"') == 1+ assert "Based on the retrieved context, here is the answer." in sse_text++ round_tripped = parser._parse_sse_to_response(sse_text, "anthropic")+ assert round_tripped is not None+ assert len(round_tripped["content"]) == 3+ assert round_tripped["content"][0]["type"] == "thinking"+ assert round_tripped["content"][0]["thinking"] == "Now I have the context, let me answer."+ assert round_tripped["content"][1]["type"] == "text"+ assert (+ round_tripped["content"][1]["text"] == "Based on the retrieved context, here is the answer."+ )+ assert round_tripped["content"][2]["type"] == "tool_use"+ assert round_tripped["content"][2]["input"] == {"y": 2}