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(savings): count compression savings once per conversation, not once per turn (#3480)
gglucass427fa76f6080
diff --git a/headroom/proxy/conversation_savings.py b/headroom/proxy/conversation_savings.pynew file mode 100644index 000000000..df2de82fa--- /dev/null+++ b/headroom/proxy/conversation_savings.py@@ -0,0 +1,187 @@+"""Novel-vs-repeat attribution for per-request compression savings.++Providers disagree about what a request's ``tokens_saved`` means, and the+disagreement only shows up once something sums it.++Anthropic's cached prefix is frozen -- the router leaves it alone so the+provider's prefix cache keeps hitting -- so a turn's ``tokens_saved`` covers+only content that newly entered the conversation. Summing across turns counts+each removed token once.++OpenAI's ``/v1/responses`` carries the whole transcript in every request and+the router recompresses all of it, so a turn's ``tokens_saved`` is the running+total of everything removed from that conversation so far. Summing across+turns counts the same removed token once per remaining turn: roughly twenty+times on a twenty-turn conversation.++Measured 2026-09-08 across one machine's retained proxy logs: gpt/codex models+reported 8.10M tokens saved against 3.90M tokens of new input (2.1x, which no+share of new content can be), where Claude reported 4.18M against 43.3M. Two+requests from the same machine and the same minute::++ gpt-6-astra tok_before=156260 tok_after=80240 tok_saved=76020 cache_read=66304+ claude-opus-5 tok_before=114024 tok_after=113566 tok_saved=458 cache_read=98503++Every cumulative consumer inherits the inflation: lifetime savings totals, the+per-model savings percent, the dollar figure (repeat removals priced at the+full uncached input rate when the alternative was a cache read at ~0.1x), and+any rate dividing savings by new input, which then has no 100% ceiling.++This module converts the cumulative series into the incremental one. Per+request descriptions keep the wire truth -- ``tok_before``/``tok_after``, the+request log and the transformations feed all still say what left this process+-- because those tokens really were removed from this request's payload. Only+the running totals switch to the novel figure, so a removed token is counted+once per conversation instead of once per turn.+"""++from __future__ import annotations++import hashlib+import threading+from collections import OrderedDict+from typing import Any++from headroom.proxy.output_savings_policy import _unwrap_response_create_body++__all__ = [+ "ConversationSavings",+ "get_conversation_savings",+ "reset_conversation_savings",+ "savings_conversation_key",+]++_ID_KEYS = ("id", "conversation_id", "session_id", "thread_id")+++def _explicit_id(value: Any) -> str:+ if isinstance(value, str):+ return value if value and value.lower() != "auto" else ""+ if isinstance(value, dict):+ for key in _ID_KEYS:+ nested = value.get(key)+ if isinstance(nested, str) and nested:+ return nested+ return ""+++def savings_conversation_key(body: Any, *, session_id: str | None = None) -> str | None:+ """Identity under which a Responses request's ``tokens_saved`` is a running total.++ Returns ``None`` unless BOTH premises of the cumulative accounting hold, in+ which case the funnel keeps ordinary per-request accounting:++ 1. The request names one conversation. Only an explicit id counts: a+ top-level ``conversation_id``/``session_id``/``thread_id``, one of+ those inside ``metadata``/``client_metadata``, or a transport-scoped+ ``session_id`` the caller vouches for (a WebSocket, a session header).+ Two things are deliberately NOT accepted. The holdout key's fallbacks+ (the instructions prefix, the literal ``responses``): two independent+ conversations with the same instructions would share a running total+ and suppress each other's savings. And ``prompt_cache_key``: it groups+ prompt-cache routing, and OpenAI documents one key shared across a+ user's sessions and forks, or across independent single-turn judging+ requests, so it aliases conversations the same way. An adapter that+ establishes a client sets it uniquely per conversation may pass it as+ ``session_id``; nothing here does.+ 2. The request carries the whole transcript. With ``previous_response_id``+ or a server-side ``conversation`` the provider holds prior context and+ the payload is this turn's increment, so ``tokens_saved`` is already+ per-request and must not be differenced.++ Chat-completions bodies (no ``input``) return ``None``: their handlers+ freeze the cached prefix, so their ``tokens_saved`` is novel-only already.+ """+ if not isinstance(body, dict):+ return None+ body = _unwrap_response_create_body(body)+ if "input" not in body:+ return None+ if body.get("previous_response_id") or body.get("conversation"):+ return None++ identity = ""+ for key in ("conversation_id", "session_id", "thread_id"):+ value = _explicit_id(body.get(key))+ if value:+ identity = f"{key}:{value}"+ break+ if not identity:+ for container_key in ("client_metadata", "metadata"):+ container = body.get(container_key)+ if not isinstance(container, dict):+ continue+ for key in (+ "conversation_id",+ "conversation_key",+ "session_id",+ "thread_id",+ "codex_session_id",+ ):+ value = _explicit_id(container.get(key))+ if value:+ identity = f"{container_key}.{key}:{value}"+ break+ if identity:+ break+ if not identity and session_id:+ identity = f"session:{session_id}"+ if not identity:+ return None+ return hashlib.sha256(("savings\x00" + identity).encode("utf-8", "ignore")).hexdigest()+++# Conversations tracked before the oldest is forgotten. A forgotten+# conversation that is still live restarts from zero and re-counts its+# transcript once, so the cap trades a bounded, one-off overcount for bounded+# memory. 512 is far above the number of conversations one client keeps warm.+DEFAULT_MAX_CONVERSATIONS = 512+++class ConversationSavings:+ """Cumulative-per-turn savings to novel-this-turn savings, bounded."""++ def __init__(self, max_conversations: int = DEFAULT_MAX_CONVERSATIONS) -> None:+ self._max = max(1, int(max_conversations))+ self._seen: OrderedDict[str, int] = OrderedDict()+ self._lock = threading.Lock()++ def novel(self, conversation_key: str | None, cumulative: int | None) -> int | None:+ """Tokens this request removed for the first time in its conversation.++ ``cumulative`` is the conversation's running removed-token total as of+ this request. Returns ``None`` when the caller cannot supply both a+ conversation key and a total, which means "this path does not+ distinguish" -- the funnel then falls back to ``tokens_saved``, which+ is already novel-only on providers that freeze their cached prefix.+ """+ if not conversation_key or cumulative is None:+ return None++ total = max(0, int(cumulative))+ with self._lock:+ previous = self._seen.get(conversation_key, 0)+ self._seen[conversation_key] = total+ self._seen.move_to_end(conversation_key)+ while len(self._seen) > self._max:+ self._seen.popitem(last=False)++ # A total that went DOWN means the transcript shrank under it: a+ # compaction, or a client that dropped history. Nothing was removed+ # for the first time, and the next turn counts from the lower base+ # rather than waiting for the old high-water mark to be re-reached.+ return max(0, total - previous)+++_default = ConversationSavings()+++def get_conversation_savings() -> ConversationSavings:+ """Process-wide ledger. One conversation spans many requests."""+ return _default+++def reset_conversation_savings() -> None:+ """Forget every conversation. Test helper only."""+ global _default+ _default = ConversationSavings()diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex c2132a51f..398985c54 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -23,6 +23,7 @@ from datetime import datetimefrom typing import TYPE_CHECKING, Anyfrom urllib.parse import quote, unquote, urlparse+from headroom.proxy.conversation_savings import savings_conversation_keyfrom headroom.proxy.helpers import (COMPRESSION_TIMEOUT_SECONDS,_headroom_bypass_enabled,@@ -5850,6 +5851,28 @@ class OpenAIHandlerMixin:)url = _append_request_query(url, request.url.query)+ # Responses re-sends the whole transcript every turn and the router+ # recompresses all of it, so ``tokens_saved`` below is the running+ # total for the CONVERSATION, not for this turn. Carrying the key and+ # the total lets the funnel count each removed token once instead of+ # once per remaining turn (see ``conversation_savings``). Derived+ # before compression so a rewritten first user message cannot move the+ # key mid-conversation. Left None when compression did not run: a+ # bypassed turn saves nothing and must not reset the running total.+ # ``savings_conversation_key`` is None without an explicit conversation+ # id (a body id, a session header) or when the body carries+ # ``previous_response_id``/``conversation`` (incremental input against+ # server-side state); the funnel then books per request.+ responses_conversation_key: str | None = None+ _pre_compression_conversation_key = savings_conversation_key(+ body,+ session_id=(+ request.headers.get("conversation_id")+ or request.headers.get("session_id")+ or request.headers.get("x-headroom-session-id")+ ),+ )+# The standalone Rust proxy has native /v1/responses item handling,# but the default CLI runtime is this Python proxy. Compress the# Python runtime path here by extracting mutable Responses text into@@ -5885,6 +5908,7 @@ class OpenAIHandlerMixin:if _modified:body_mutation_tracker.mark_mutated("responses_compression")tokens_saved = int(_tokens_saved)+ responses_conversation_key = _pre_compression_conversation_keyoptimized_tokens = max(0, original_tokens - tokens_saved)logger.info("[%s] /v1/responses compressed %d→%d bytes "@@ -6067,6 +6091,8 @@ class OpenAIHandlerMixin:body_mutated=body_mutation_tracker.mutated,mutation_reasons=body_mutation_tracker.reasons,waste_signals=waste_signals_dict,+ conversation_key=responses_conversation_key,+ conversation_tokens_saved=tokens_saved,)else:@@ -6532,6 +6558,8 @@ class OpenAIHandlerMixin:waste_signals=waste_signals_dict,num_messages=len(messages) if isinstance(messages, list) else 0,tags=_resp_log_tags,+ conversation_key=responses_conversation_key,+ conversation_tokens_saved=tokens_saved,turn_id=compute_turn_id(model, body.get("instructions"), messages),request_messages=messagesif getattr(self.config, "log_full_messages", False)@@ -7218,6 +7246,14 @@ class OpenAIHandlerMixin:attempted_input_tokens_total = 0transforms_applied: list[str] = []ws_frames_compressed = 0+ # ``tokens_saved`` below SUMS each frame's figure, and each frame's+ # figure is the whole transcript's removals as of that turn. The+ # conversation's running total is therefore the LAST frame's+ # figure, not the sum -- that is what the funnel differences to+ # count a removed token once (see ``conversation_savings``).++ ws_conversation_key: str | None = None+ ws_conversation_tokens_saved: int | None = Nonetry:body = json.loads(first_msg_raw)except json.JSONDecodeError:@@ -7720,6 +7756,10 @@ class OpenAIHandlerMixin:)_record_ws_compression_overhead(_rewrite_ms)tokens_saved += int(_ws_saved)+ ws_conversation_tokens_saved = int(_ws_saved)+ ws_conversation_key = savings_conversation_key(+ _send_body, session_id=f"ws:{session_id}"+ )attempted_input_tokens_total += int(_ws_attempted_tokens)logger.info("[%s] WS /v1/responses compressed "@@ -7928,6 +7968,7 @@ class OpenAIHandlerMixin:frames in the WS session."""nonlocal tokens_saved, transforms_applied, attempted_input_tokens_total+ nonlocal ws_conversation_key, ws_conversation_tokens_savednonlocal ws_frames_compressed_preflight_started = time.perf_counter()try:@@ -8190,6 +8231,10 @@ class OpenAIHandlerMixin:)_record_ws_compression_overhead(_rewrite_ms)tokens_saved += int(frame_saved)+ ws_conversation_tokens_saved = int(frame_saved)+ ws_conversation_key = savings_conversation_key(+ new_inner, session_id=f"ws:{session_id}"+ )attempted_input_tokens_total += int(frame_attempted_tokens)ws_frames_compressed += 1logger.info(@@ -8544,6 +8589,8 @@ class OpenAIHandlerMixin:if isinstance(body, dict)else 0,tags=ws_tags,+ conversation_key=ws_conversation_key,+ conversation_tokens_saved=ws_conversation_tokens_saved,client=client,))@@ -9148,6 +9195,8 @@ class OpenAIHandlerMixin:pipeline_timing=final_pipeline_timing,transforms_applied=tuple(transforms_applied),tags=ws_session_tags,+ conversation_key=ws_conversation_key,+ conversation_tokens_saved=ws_conversation_tokens_saved,client=client,request_messages=ws_messages_for_logif getattr(self.config, "log_full_messages", False)diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.pyindex 334ff389c..7e8d49f7c 100644--- a/headroom/proxy/handlers/streaming.py+++ b/headroom/proxy/handlers/streaming.py@@ -931,6 +931,12 @@ class StreamingMixin:parsed_response: dict[str, Any] | None = None,client: str | None = None,waste_signals: dict[str, int] | None = None,+ # Set only by paths whose ``tokens_saved`` is the CONVERSATION's+ # running total rather than this turn's -- OpenAI ``/v1/responses``,+ # which re-sends and recompresses the whole transcript every turn.+ # See ``conversation_savings``.+ conversation_key: str | None = None,+ conversation_tokens_saved: int | None = None,) -> None:from headroom.proxy.outcome import RequestOutcome@@ -1112,6 +1118,8 @@ class StreamingMixin:pipeline_timing=pipeline_timing,original_messages=original_messages,waste_signals=waste_signals,+ conversation_key=conversation_key,+ conversation_tokens_saved=conversation_tokens_saved,)await self._record_request_outcome(outcome)@@ -1141,6 +1149,8 @@ class StreamingMixin:outcome_provider: str | None = None,waste_signals: dict[str, int] | None = None,session_key: str | None = None,+ conversation_key: str | None = None,+ conversation_tokens_saved: int | None = None,) -> Response | StreamingResponse:"""Stream response with metrics tracking and memory tool handling.@@ -1185,6 +1195,8 @@ class StreamingMixin:outcome_provider=outcome_provider,waste_signals=waste_signals,session_key=session_key,+ conversation_key=conversation_key,+ conversation_tokens_saved=conversation_tokens_saved,)except (Exception, asyncio.CancelledError):self._cleanup_mid_turn_stream(session_key)@@ -1215,6 +1227,8 @@ class StreamingMixin:outcome_provider: str | None,waste_signals: dict[str, int] | None,session_key: str,+ conversation_key: str | None = None,+ conversation_tokens_saved: int | None = None,) -> Response | StreamingResponse:"""Actual streaming implementation, guarded by _stream_response's cleanup wrapper."""from fastapi.responses import Response, StreamingResponse@@ -1518,6 +1532,8 @@ class StreamingMixin:original_messages=original_messages,client=client,waste_signals=waste_signals,+ conversation_key=conversation_key,+ conversation_tokens_saved=conversation_tokens_saved,)self._cleanup_mid_turn_stream(session_key)return Response(@@ -1797,6 +1813,8 @@ class StreamingMixin:parsed_response=parsed_response,client=client,waste_signals=waste_signals,+ conversation_key=conversation_key,+ conversation_tokens_saved=conversation_tokens_saved,)if supports_mid_turn_coalescing(client) and pending_messages:pending_event = json.dumps(diff --git a/headroom/proxy/outcome.py b/headroom/proxy/outcome.pyindex da88e7e58..3f0897f56 100644--- a/headroom/proxy/outcome.py+++ b/headroom/proxy/outcome.py@@ -31,6 +31,7 @@ from dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom typing import Any+from headroom.proxy.conversation_savings import get_conversation_savingsfrom headroom.proxy.tool_schema_savings_policy import (headline_tokens_saved,tool_schema_saved_from_tags,@@ -188,6 +189,20 @@ class RequestOutcome:# one-field-add that proves the refactor pays out: per-# harness visibility appears across EVERY handler with zero# new bookkeeping at the call sites.+ # conversation_key: stable across every turn of one conversation, from+ # ``conversation_key_from_body``. Paired with+ # ``conversation_tokens_saved`` it lets the funnel tell a first-time+ # removal from a re-run of one already counted. Both stay ``None`` on+ # paths whose ``tokens_saved`` is already novel-only -- every provider+ # that freezes its cached prefix, which is all of them except OpenAI's+ # ``/v1/responses``. See ``conversation_savings``.+ # conversation_tokens_saved: the conversation's RUNNING removed-token+ # total as of this request, which on ``/v1/responses`` is what the+ # compressor reports every turn because it recompresses the whole+ # transcript. Not the same quantity as ``tokens_saved`` on the WS+ # path, where the outcome carries a per-turn delta.+ conversation_key: str | None = None+ conversation_tokens_saved: int | None = Nonetransforms_applied: tuple[str, ...] = ()waste_signals: dict[str, int] | None = Nonenum_messages: int = 0@@ -319,6 +334,8 @@ class RequestOutcome:pipeline_timing: dict[str, float] | None = None,waste_signals: dict[str, int] | None = None,original_messages: list[dict] | None = None,+ conversation_key: str | None = None,+ conversation_tokens_saved: int | None = None,) -> RequestOutcome:"""Construct an outcome from the locals available at streamingfinalize. Three streaming finalizers@@ -391,6 +408,8 @@ class RequestOutcome:optimized_tokens=optimized_tokens,output_tokens=output_tokens,tokens_saved=tokens_saved,+ conversation_key=conversation_key,+ conversation_tokens_saved=conversation_tokens_saved,attempted_input_tokens=optimized_tokens + tokens_saved,cache_read_tokens=cache_read_tokens,cache_write_tokens=cache_write_tokens,@@ -567,6 +586,18 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:# HTTP middleware / WS accept captured from ``X-Headroom-Project``.project = outcome.project or get_current_project()+ # Savings that are new to this conversation. Per-request descriptions+ # below keep ``outcome.tokens_saved`` -- the wire truth for THIS request --+ # while everything that accumulates across turns uses this, so a removed+ # token is counted once per conversation instead of once per turn. Falls+ # back to ``tokens_saved`` on paths that do not distinguish, which is+ # already the novel figure there. See ``conversation_savings``.+ novel_tokens_saved = get_conversation_savings().novel(+ outcome.conversation_key, outcome.conversation_tokens_saved+ )+ if novel_tokens_saved is None:+ novel_tokens_saved = outcome.tokens_saved+# Tool-schema savings (deferral + turn-hook tool shrink) live in per-request# tags and never move tok_before/after; aggregate them into Metrics so the# session summary / cost summary / all-layers total can surface the layer.@@ -603,7 +634,7 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:model=outcome.model,input_tokens=billed_input_tokens,output_tokens=outcome.output_tokens,- tokens_saved=outcome.tokens_saved,+ tokens_saved=novel_tokens_saved,latency_ms=outcome.total_latency_ms,cached=outcome.cache_hit,overhead_ms=outcome.overhead_ms,@@ -629,7 +660,7 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:if cost_tracker is not None:cost_tracker.record_tokens(outcome.model,- outcome.tokens_saved,+ novel_tokens_saved,billed_input_tokens,cache_read_tokens=outcome.cache_read_tokens,cache_write_tokens=outcome.cache_write_tokens,@@ -691,6 +722,11 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:# line unchanged, and gives ``headroom perf --client X``# parsers a clean key to filter on.client_part = f" client={outcome.client}" if outcome.client else ""+ # Only when it differs: on every path that reports novel-only savings the+ # two are equal and a second identical number is noise.+ novel_part = (+ f"tok_novel={novel_tokens_saved} " if novel_tokens_saved != outcome.tokens_saved else ""+ )# ``cached=1`` marks a turn answered from Headroom's own response cache.# Such a turn never contacts the upstream, so it has no outbound_request# line, no upstream stage timings, and all-zero token counters — which@@ -713,6 +749,7 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:f"model={outcome.model} msgs={outcome.num_messages} "f"tok_before={outcome.original_tokens} tok_after={outcome.optimized_tokens} "f"tok_saved={outcome.tokens_saved} "+ f"{novel_part}"f"tok_inflated={outcome.tokens_inflated} "f"tool_saved={tool_saved} "f"total_saved={total_saved} "diff --git a/tests/test_openai_codex_routing.py b/tests/test_openai_codex_routing.pyindex 471d0d8ca..5b7d4b0d2 100644--- a/tests/test_openai_codex_routing.py+++ b/tests/test_openai_codex_routing.py@@ -4,7 +4,7 @@ import jsonimport sysfrom copy import deepcopyfrom types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patchimport anyioimport httpx@@ -949,3 +949,110 @@ def test_handle_openai_responses_ws_closes_unconfigured_origin(monkeypatch):assert websocket.close_code == 1008assert websocket.close_reason == "origin not allowed"assert websocket.accepted_subprotocol is None+++# --- conversation savings through the handler and the funnel ----------------++_SHARED_INSTRUCTIONS = "You are Codex, a coding agent running in the user's terminal. " * 20+++def _savings_handler(monkeypatch, saved: int) -> _DummyOpenAIHandler:+ """A responses handler whose compression removes ``saved`` tokens per+ request and whose metrics call is captured, so the funnel's booked+ ``tokens_saved`` can be read back."""+ from headroom.proxy.conversation_savings import reset_conversation_savings++ reset_conversation_savings()+ handler = _DummyOpenAIHandler()+ handler.config.optimize = True+ handler.metrics.record_request = AsyncMock()++ async def compress(payload, **kwargs): # noqa: ANN001, ANN003+ return payload, True, saved, ["router:text"], None, 1_000, 900, 500, {}++ handler._compress_openai_responses_payload_in_executor = compress+ monkeypatch.setattr("headroom.tokenizers.get_tokenizer", lambda model: _DummyTokenizer())+ return handler+++def _post_responses(handler: _DummyOpenAIHandler, body: dict, headers: dict | None = None) -> None:+ request = _build_request(body, {"Authorization": "Bearer sk-test", **(headers or {})})+ response = anyio.run(handler.handle_openai_responses, request)+ assert response.status_code == 200+++def _booked(handler: _DummyOpenAIHandler) -> list[int]:+ return [c.kwargs["tokens_saved"] for c in handler.metrics.record_request.await_args_list]+++def test_responses_savings_keep_per_request_accounting_without_identity(monkeypatch):+ # Two independent conversations: same model, same instructions, different+ # input, no conversation id anywhere. Each books its own 100.+ handler = _savings_handler(monkeypatch, saved=100)+ _post_responses(+ handler,+ {"model": "gpt-5.4", "instructions": _SHARED_INSTRUCTIONS, "input": "fix the failing test"},+ )+ _post_responses(+ handler,+ {"model": "gpt-5.4", "instructions": _SHARED_INSTRUCTIONS, "input": "write the notes"},+ )+ assert _booked(handler) == [100, 100]+++def test_responses_savings_dedupe_full_transcripts_but_not_incremental_input(monkeypatch):+ handler = _savings_handler(monkeypatch, saved=100)+ # Full-transcript replay under an explicit conversation id: the second+ # turn re-sends the first and its 100 is the same 100.+ turn1 = {+ "model": "gpt-5.4",+ "instructions": _SHARED_INSTRUCTIONS,+ "metadata": {"conversation_id": "conv-1"},+ "input": [{"role": "user", "content": "fix the failing test"}],+ }+ turn2 = {**turn1, "input": [*turn1["input"], {"role": "user", "content": "and the lint"}]}+ _post_responses(handler, turn1)+ _post_responses(handler, turn2)+ assert _booked(handler) == [100, 0]+ # Same conversation id, but each request is fresh input against+ # previous_response_id: the provider holds the history, so each 100 is+ # its own removal.+ inc1 = {+ "model": "gpt-5.4",+ "metadata": {"conversation_id": "conv-1"},+ "previous_response_id": "resp_1",+ "input": [{"role": "user", "content": "more"}],+ }+ _post_responses(handler, inc1)+ _post_responses(handler, {**inc1, "previous_response_id": "resp_2"})+ assert _booked(handler) == [100, 0, 100, 100]+++def test_responses_savings_ignore_a_shared_prompt_cache_key(monkeypatch):+ # prompt_cache_key groups cache routing; OpenAI documents one key shared+ # across a user's sessions and forks. Two conversations under one key,+ # with and without distinct session headers, each keep their own 100.+ handler = _savings_handler(monkeypatch, saved=100)+ shared = {"model": "gpt-5.4", "prompt_cache_key": "shared-support-prefix"}+ _post_responses(+ handler, {**shared, "input": "fix the failing test"}, {"session_id": "session-0"}+ )+ _post_responses(handler, {**shared, "input": "write the notes"}, {"session_id": "session-1"})+ assert _booked(handler) == [100, 100]+ _post_responses(handler, {**shared, "input": "fix the failing test"})+ _post_responses(handler, {**shared, "input": "write the notes"})+ assert _booked(handler) == [100, 100, 100, 100]+ # The session header, not the cache key, is what de-duplicates.+ _post_responses(+ handler, {**shared, "input": "fix the failing test"}, {"session_id": "session-0"}+ )+ assert _booked(handler) == [100, 100, 100, 100, 0]+++def test_responses_savings_accept_a_session_header_as_identity(monkeypatch):+ handler = _savings_handler(monkeypatch, saved=100)+ body = {"model": "gpt-5.4", "instructions": _SHARED_INSTRUCTIONS, "input": "fix it"}+ _post_responses(handler, body, {"session_id": "sess-1"})+ _post_responses(handler, body, {"session_id": "sess-1"})+ _post_responses(handler, body, {"session_id": "sess-2"})+ assert _booked(handler) == [100, 0, 100]diff --git a/tests/test_proxy/test_conversation_savings.py b/tests/test_proxy/test_conversation_savings.pynew file mode 100644index 000000000..0d75e4323--- /dev/null+++ b/tests/test_proxy/test_conversation_savings.py@@ -0,0 +1,339 @@+"""Compression savings are counted once per conversation, not once per turn.++OpenAI's ``/v1/responses`` re-sends the whole transcript every turn and the+router recompresses all of it, so a turn's ``tokens_saved`` is the running+total for the conversation. Summing that across turns counts every removed+token again on every remaining turn. Anthropic's frozen cached prefix means+its ``tokens_saved`` is already novel-only, which is why the two providers'+lifetime totals were never comparable.+"""++from __future__ import annotations++from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest++from headroom.proxy.conversation_savings import (+ ConversationSavings,+ get_conversation_savings,+ reset_conversation_savings,+ savings_conversation_key,+)+from headroom.proxy.outcome import RequestOutcome, emit_request_outcome++[email protected](autouse=True)+def _clean_ledger() -> Any:+ reset_conversation_savings()+ yield+ reset_conversation_savings()+++# ── The ledger ─────────────────────────────────────────────────────────+++def test_first_turn_of_a_conversation_is_entirely_novel() -> None:+ ledger = ConversationSavings()+ assert ledger.novel("conv-a", 76_020) == 76_020+++def test_later_turns_count_only_what_the_total_grew_by() -> None:+ """The measured shape: a turn removes 76k from a transcript whose earlier+ turns already accounted for 62k of it."""+ ledger = ConversationSavings()+ ledger.novel("conv-a", 62_806)+ assert ledger.novel("conv-a", 76_020) == 13_214+++def test_a_long_conversation_counts_each_removed_token_once() -> None:+ """The regression itself. Twenty turns of a conversation that removed+ 10k tokens on turn one and nothing new after: the old accounting booked+ 200k, which is also what made the savings rate exceed its own denominator.+ """+ ledger = ConversationSavings()+ total = sum(ledger.novel("conv-a", 10_000) for _ in range(20))+ assert total == 10_000+++def test_conversations_do_not_leak_into_each_other() -> None:+ ledger = ConversationSavings()+ assert ledger.novel("conv-a", 5_000) == 5_000+ assert ledger.novel("conv-b", 8_000) == 8_000+ assert ledger.novel("conv-a", 6_000) == 1_000+++def test_a_shrinking_total_is_a_compaction_not_a_negative_saving() -> None:+ """A compaction (or a client dropping history) shrinks the transcript.+ Nothing was removed for the first time, and the next turn must count from+ the new lower base rather than waiting out the old high-water mark."""+ ledger = ConversationSavings()+ ledger.novel("conv-a", 50_000)+ assert ledger.novel("conv-a", 9_000) == 0+ assert ledger.novel("conv-a", 11_000) == 2_000+++def test_missing_identity_declines_to_answer() -> None:+ """None means "this path does not distinguish" so the funnel falls back to+ ``tokens_saved`` -- which is already novel-only on every provider that+ freezes its cached prefix. Attributing zero here would silently delete+ real savings."""+ ledger = ConversationSavings()+ assert ledger.novel(None, 5_000) is None+ assert ledger.novel("", 5_000) is None+ assert ledger.novel("conv-a", None) is None+++def test_the_oldest_conversation_is_forgotten_first() -> None:+ """Bounded memory. A forgotten conversation re-counts its transcript once,+ which is a one-off overcount, not an unbounded leak."""+ ledger = ConversationSavings(max_conversations=2)+ ledger.novel("conv-a", 1_000)+ ledger.novel("conv-b", 1_000)+ ledger.novel("conv-c", 1_000) # evicts conv-a, the oldest+ # conv-a is gone, so its transcript is re-counted from zero once. Re-+ # admitting it evicts the next-oldest (conv-b); conv-c stays warm.+ assert ledger.novel("conv-a", 1_000) == 1_000+ assert ledger.novel("conv-c", 1_500) == 500+++def test_touching_a_conversation_keeps_it_warm() -> None:+ ledger = ConversationSavings(max_conversations=2)+ ledger.novel("conv-a", 1_000)+ ledger.novel("conv-b", 1_000)+ ledger.novel("conv-a", 2_000) # conv-a is now the most recent+ ledger.novel("conv-c", 1_000) # evicts conv-b, not conv-a+ assert ledger.novel("conv-a", 3_000) == 1_000+++# ── The funnel ─────────────────────────────────────────────────────────+++class _Handler:+ """Minimal stand-in for the parts of HeadroomProxy the funnel touches."""++ def __init__(self) -> None:+ self.metrics = MagicMock()+ self.metrics.record_request = AsyncMock()+ self.cost_tracker = MagicMock()+ self.logger = None+++def _responses_outcome(**overrides: Any) -> RequestOutcome:+ defaults: dict[str, Any] = {+ "request_id": "req-1",+ "provider": "openai",+ "model": "gpt-6-astra",+ "original_tokens": 156_260,+ "optimized_tokens": 80_240,+ "output_tokens": 177,+ "tokens_saved": 76_020,+ "attempted_input_tokens": 90_000,+ "cache_read_tokens": 66_304,+ "conversation_key": "conv-a",+ "conversation_tokens_saved": 76_020,+ }+ defaults.update(overrides)+ return RequestOutcome(**defaults)+++async def test_running_totals_see_the_novel_figure() -> None:+ """Two turns of one conversation whose running total grew by 13,214. The+ savings tracker and the cost tracker must see the growth, not the total+ twice -- that is the inflation the whole change exists to remove."""+ handler = _Handler()+ await emit_request_outcome(+ handler, _responses_outcome(tokens_saved=62_806, conversation_tokens_saved=62_806)+ )+ await emit_request_outcome(handler, _responses_outcome())++ second_call = handler.metrics.record_request.await_args_list[1]+ assert second_call.kwargs["tokens_saved"] == 13_214+ assert handler.cost_tracker.record_tokens.call_args_list[1].args[1] == 13_214+++async def test_the_request_log_keeps_the_wire_truth() -> None:+ """Those 76,020 tokens really did leave this request's payload. Per+ request surfaces describe the wire; only running totals de-duplicate."""+ handler = _Handler()+ handler.logger = MagicMock()+ await emit_request_outcome(handler, _responses_outcome(conversation_tokens_saved=62_806))+ await emit_request_outcome(handler, _responses_outcome())++ logged = handler.logger.log.call_args_list[1].args[0]+ assert logged.tokens_saved == 76_020+ assert logged.input_tokens_original == 156_260+ assert logged.input_tokens_optimized == 80_240+++async def test_paths_without_conversation_identity_are_unchanged() -> None:+ """Anthropic and every other handler leave the pair unset. Their+ ``tokens_saved`` is already novel-only, so it must reach the trackers+ untouched however many turns go by."""+ handler = _Handler()+ for _ in range(3):+ await emit_request_outcome(+ handler,+ RequestOutcome(+ request_id="req-1",+ provider="anthropic",+ model="claude-opus-5",+ original_tokens=114_024,+ optimized_tokens=113_566,+ output_tokens=125,+ tokens_saved=458,+ attempted_input_tokens=1_700,+ ),+ )+ assert [+ call.kwargs["tokens_saved"] for call in handler.metrics.record_request.await_args_list+ ] == [458, 458, 458]+++async def test_a_websocket_residual_does_not_re_book_its_session() -> None:+ """The session-end residual carries the same running total the last+ per-turn record already accounted for, so its novel contribution is zero.+ When no per-turn record fired, it carries the whole figure instead."""+ handler = _Handler()+ await emit_request_outcome(handler, _responses_outcome(conversation_tokens_saved=40_000))+ await emit_request_outcome(+ handler,+ _responses_outcome(tokens_saved=0, conversation_tokens_saved=40_000),+ )+ assert handler.metrics.record_request.await_args_list[1].kwargs["tokens_saved"] == 0+++async def test_the_ledger_is_shared_across_requests() -> None:+ """One conversation spans many requests and, on the HTTP path, many+ handler invocations. A per-request ledger would never see turn N-1."""+ get_conversation_savings().novel("conv-a", 70_000)+ handler = _Handler()+ await emit_request_outcome(handler, _responses_outcome())+ assert handler.metrics.record_request.await_args_list[0].kwargs["tokens_saved"] == 6_020+++def test_the_streaming_constructor_carries_the_pair() -> None:+ """Codex streams ``/v1/responses``, so the streaming finalizer is the path+ that actually books most Codex savings. Dropping the pair there would fix+ the accounting only for non-streaming turns."""+ outcome = RequestOutcome.from_stream(+ body={"model": "gpt-6-astra", "input": []},+ provider="openai",+ model="gpt-6-astra",+ request_id="req-1",+ original_tokens=156_260,+ optimized_tokens=80_240,+ output_tokens=177,+ tokens_saved=76_020,+ transforms_applied=[],+ total_latency_ms=1.0,+ overhead_ms=1.0,+ tags={},+ client="codex",+ conversation_key="conv-a",+ conversation_tokens_saved=76_020,+ )+ assert outcome.conversation_key == "conv-a"+ assert outcome.conversation_tokens_saved == 76_020+++def test_the_streaming_constructor_defaults_the_pair_off() -> None:+ """Every other streaming caller (Anthropic SSE, Bedrock, OpenAI chat via+ backend) must keep reporting novel-only savings unchanged."""+ outcome = RequestOutcome.from_stream(+ body={"model": "claude-opus-5", "messages": []},+ provider="anthropic",+ model="claude-opus-5",+ request_id="req-1",+ original_tokens=114_024,+ optimized_tokens=113_566,+ output_tokens=125,+ tokens_saved=458,+ transforms_applied=[],+ total_latency_ms=1.0,+ overhead_ms=1.0,+ tags={},+ client="claude-code",+ )+ assert outcome.conversation_key is None+ assert outcome.conversation_tokens_saved is None+++# --- identity: real Responses bodies, not an injected key -------------------++_INSTRUCTIONS = "You are Codex, a coding agent running in the user's terminal. " * 20+++def _responses_body(text: str, **extra: Any) -> dict[str, Any]:+ return {+ "model": "gpt-6-astra",+ "instructions": _INSTRUCTIONS,+ "input": [{"role": "user", "content": [{"type": "input_text", "text": text}]}],+ "store": False,+ **extra,+ }+++def test_shared_instructions_with_distinct_input_are_not_one_conversation() -> None:+ """Two ordinary payloads, same model and instructions, different user+ input. The holdout key merges them (its Responses fallback is the+ instructions prefix); the savings key must not, or independent sessions+ suppress each other's savings through the process-wide ledger."""+ from headroom.proxy.output_savings_policy import conversation_key_from_body++ a_body = _responses_body("fix the failing test")+ b_body = _responses_body("write the release notes")+ assert conversation_key_from_body(a_body) == conversation_key_from_body(b_body)+ a, b = savings_conversation_key(a_body), savings_conversation_key(b_body)+ assert a is None and b is None+ ledger = ConversationSavings()+ assert ledger.novel(a, 100) is None and ledger.novel(b, 100) is None+++def test_prompt_cache_key_is_cache_routing_not_identity() -> None:+ """OpenAI documents one prompt_cache_key shared across a user's sessions+ and forks, and across independent single-turn requests. Two conversations+ under one key must not share a running total, so the key alone yields no+ identity; a real session id beside it does, and wins."""+ a = _responses_body("fix the failing test", prompt_cache_key="shared-support-prefix")+ b = _responses_body("write the release notes", prompt_cache_key="shared-support-prefix")+ assert savings_conversation_key(a) is None and savings_conversation_key(b) is None+ a_key = savings_conversation_key(a, session_id="session-0")+ b_key = savings_conversation_key(b, session_id="session-1")+ assert a_key is not None and b_key is not None and a_key != b_key+ assert savings_conversation_key(a, session_id="session-0") == a_key+++def test_explicit_ids_and_caller_vouched_sessions() -> None:+ assert savings_conversation_key(_responses_body("x", metadata={"conversation_id": "c-1"}))+ assert savings_conversation_key(_responses_body("x", thread_id="t-1"))+ ws_a = savings_conversation_key(_responses_body("x"), session_id="ws:a")+ ws_b = savings_conversation_key(_responses_body("x"), session_id="ws:b")+ assert ws_a is not None and ws_b is not None and ws_a != ws_b+ frame = {"type": "response.create", "response": _responses_body("x", prompt_cache_key="c")}+ assert savings_conversation_key(frame) == savings_conversation_key(+ _responses_body("x", prompt_cache_key="c")+ )+++def test_server_side_state_means_incremental_input() -> None:+ """With ``previous_response_id`` or a ``conversation`` the provider holds+ the history and each payload is a fresh increment: its ``tokens_saved``+ is per-request already, even under an explicit conversation id."""+ assert (+ savings_conversation_key(+ _responses_body("more", prompt_cache_key="conv-1", previous_response_id="resp_1")+ )+ is None+ )+ assert savings_conversation_key(_responses_body("more", conversation="conv_abc")) is None+ assert (+ savings_conversation_key(_responses_body("more", conversation={"id": "conv_abc"})) is None+ )+ assert savings_conversation_key({"model": "gpt-6-astra", "messages": []}) is None