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
Speed up OpenAI Responses compression units
jamesx0416d160f391d557
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex 1ce372396..dcfe6f8a1 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -13,8 +13,12 @@ import hashlibimport jsonimport loggingimport os+import threadingimport timeimport uuid+from collections import OrderedDict+from concurrent.futures import ThreadPoolExecutor, as_completed+from dataclasses import replacefrom datetime import datetimefrom typing import TYPE_CHECKING, Any@@ -46,6 +50,72 @@ from headroom.proxy.outcome import RequestOutcomelogger = logging.getLogger("headroom.proxy")+_OPENAI_RESPONSES_UNIT_CACHE_MAX_ENTRIES = 10_000+_OPENAI_RESPONSES_UNIT_CACHE_VERSION = "openai_responses_unit_v1"+_OPENAI_RESPONSES_UNIT_PARALLELISM_ENV = "HEADROOM_OPENAI_RESPONSES_UNIT_PARALLELISM"+_OPENAI_RESPONSES_UNIT_PARALLELISM_DEFAULT = 4+_OPENAI_RESPONSES_UNIT_PARALLELISM_MAX = 16+_OPENAI_RESPONSES_UNIT_CACHE_INIT_LOCK = threading.RLock()+_OPENAI_RESPONSES_UNIT_EXECUTOR_LOCK = threading.RLock()+_OPENAI_RESPONSES_UNIT_EXECUTOR: ThreadPoolExecutor | None = None+++def _openai_responses_unit_parallelism() -> int:+ raw = os.getenv(_OPENAI_RESPONSES_UNIT_PARALLELISM_ENV)+ if raw is None or raw.strip() == "":+ return _OPENAI_RESPONSES_UNIT_PARALLELISM_DEFAULT+ try:+ requested = int(raw)+ except ValueError:+ logger.warning(+ "Invalid %s=%r; using default %d",+ _OPENAI_RESPONSES_UNIT_PARALLELISM_ENV,+ raw,+ _OPENAI_RESPONSES_UNIT_PARALLELISM_DEFAULT,+ )+ return _OPENAI_RESPONSES_UNIT_PARALLELISM_DEFAULT+ return max(1, min(_OPENAI_RESPONSES_UNIT_PARALLELISM_MAX, requested))+++def _openai_responses_unit_executor() -> ThreadPoolExecutor:+ global _OPENAI_RESPONSES_UNIT_EXECUTOR+ with _OPENAI_RESPONSES_UNIT_EXECUTOR_LOCK:+ if _OPENAI_RESPONSES_UNIT_EXECUTOR is None:+ _OPENAI_RESPONSES_UNIT_EXECUTOR = ThreadPoolExecutor(+ max_workers=_OPENAI_RESPONSES_UNIT_PARALLELISM_MAX,+ thread_name_prefix="headroom-openai-unit",+ )+ return _OPENAI_RESPONSES_UNIT_EXECUTOR+++def _openai_responses_unit_cache_key(unit: Any, *, model: str) -> str:+ text_hash = hashlib.sha256(unit.text.encode("utf-8", errors="replace")).hexdigest()+ key_payload = {+ "version": _OPENAI_RESPONSES_UNIT_CACHE_VERSION,+ "model": model,+ "provider": unit.provider,+ "endpoint": unit.endpoint,+ "role": unit.role,+ "item_type": unit.item_type,+ "cache_zone": unit.cache_zone,+ "mutable": unit.mutable,+ "min_bytes": unit.min_bytes,+ "context": unit.context,+ "question": unit.question,+ "bias": unit.bias,+ "metadata": unit.metadata,+ "text_sha256": text_hash,+ }+ serialized = json.dumps(key_payload, sort_keys=True, separators=(",", ":"), default=str)+ return hashlib.sha256(serialized.encode("utf-8")).hexdigest()+++def _openai_responses_result_with_cache_hit(result: Any) -> Any:+ router_result = getattr(result, "router_result", None)+ if router_result is None:+ return result+ return replace(result, router_result=replace(router_result, cache_hit=True))+def _codex_ws_text_shape(text: str) -> str:stripped = text.strip()@@ -366,6 +436,35 @@ class OpenAIHandlerMixin:"apply_patch_call_output",}+ def _openai_responses_unit_cache(self) -> tuple[Any, OrderedDict[str, Any]]:+ with _OPENAI_RESPONSES_UNIT_CACHE_INIT_LOCK:+ lock = getattr(self, "_openai_responses_unit_cache_lock", None)+ if lock is None:+ lock = threading.RLock()+ self._openai_responses_unit_cache_lock = lock+ cache = getattr(self, "_openai_responses_unit_result_cache", None)+ if cache is None:+ cache = OrderedDict()+ self._openai_responses_unit_result_cache = cache+ return lock, cache++ def _get_openai_responses_cached_unit(self, key: str) -> Any | None:+ lock, cache = self._openai_responses_unit_cache()+ with lock:+ result = cache.get(key)+ if result is None:+ return None+ cache.move_to_end(key)+ return _openai_responses_result_with_cache_hit(result)++ def _store_openai_responses_cached_unit(self, key: str, result: Any) -> None:+ lock, cache = self._openai_responses_unit_cache()+ with lock:+ cache[key] = result+ cache.move_to_end(key)+ while len(cache) > _OPENAI_RESPONSES_UNIT_CACHE_MAX_ENTRIES:+ cache.popitem(last=False)+@staticmethoddef _headroom_bypass_enabled(headers: Any) -> bool:"""Return True when inbound headers request full passthrough."""@@ -698,18 +797,65 @@ class OpenAIHandlerMixin:elapsed_ms = (time.perf_counter() - unit_started) * 1000.0return routed.slot, result, elapsed_ms- # Units run serially within the frame-level worker thread. Frame-- # level parallelism is already provided by- # ``self._compression_executor`` (32 workers, sized- # ``min(32, cpu*4)``), which `_run_compression_in_executor`- # dispatches each frame onto. The prior per-call- # ``ThreadPoolExecutor`` + module-global- # ``threading.BoundedSemaphore(10)`` caused production cascades- # under ≥10 concurrent Codex sessions; both are deleted.router_total_started = time.perf_counter()- routed_results = [_compress_routed_unit(routed) for routed in routed_units]+ routed_results: list[tuple[object, Any, float] | None] = [None] * len(routed_units)+ cache_misses: list[tuple[int, str, RoutedCompressionUnit]] = []+ cache_miss_followers: dict[str, list[int]] = {}+ for unit_idx, routed in enumerate(routed_units):+ cache_key = _openai_responses_unit_cache_key(routed.unit, model=model)+ cached = self._get_openai_responses_cached_unit(cache_key)+ if cached is not None:+ routed_results[unit_idx] = (routed.slot, cached, 0.0)+ continue+ if cache_key in cache_miss_followers:+ cache_miss_followers[cache_key].append(unit_idx)+ continue+ cache_miss_followers[cache_key] = []+ cache_misses.append((unit_idx, cache_key, routed))++ def _compress_and_store(+ unit_idx: int,+ cache_key: str,+ routed: RoutedCompressionUnit,+ ) -> tuple[int, str, tuple[object, Any, float]]:+ slot, result, elapsed_ms = _compress_routed_unit(routed)+ self._store_openai_responses_cached_unit(cache_key, result)+ return unit_idx, cache_key, (slot, result, elapsed_ms)++ def _record_routed_result(+ unit_idx: int,+ cache_key: str,+ routed_result: tuple[object, Any, float],+ ) -> None:+ routed_results[unit_idx] = routed_result+ _slot, result, _elapsed_ms = routed_result+ for follower_idx in cache_miss_followers.get(cache_key, []):+ routed_results[follower_idx] = (+ routed_units[follower_idx].slot,+ _openai_responses_result_with_cache_hit(result),+ 0.0,+ )++ parallelism = _openai_responses_unit_parallelism()+ if len(cache_misses) > 1 and parallelism > 1:+ executor = _openai_responses_unit_executor()+ for start in range(0, len(cache_misses), parallelism):+ batch = cache_misses[start : start + parallelism]+ futures = [executor.submit(_compress_and_store, *item) for item in batch]+ for future in as_completed(futures):+ unit_idx, cache_key, routed_result = future.result()+ _record_routed_result(unit_idx, cache_key, routed_result)+ else:+ for unit_idx, cache_key, routed in cache_misses:+ _record_routed_result(+ unit_idx,+ cache_key,+ _compress_and_store(unit_idx, cache_key, routed)[2],+ )++ ordered_routed_results = [result for result in routed_results if result is not None]- for _, result, elapsed_ms in routed_results:+ for _, result, elapsed_ms in ordered_routed_results:router_chain = list(result.router_result.strategy_chain) if result.router_result else []router_content_type = (result.router_result.routing_log[0].content_type.value@@ -766,7 +912,7 @@ class OpenAIHandlerMixin:_add_timing("compression_units_router_loop", router_total_started)apply_started = time.perf_counter()- for slot, result, _elapsed_ms in routed_results:+ for slot, result, _elapsed_ms in ordered_routed_results:item_idx, slot_ref = slotrouter_chain = list(result.router_result.strategy_chain) if result.router_result else []for s in router_chain:diff --git a/tests/test_openai_responses_compression_units.py b/tests/test_openai_responses_compression_units.pyindex 80b06d3d8..b9939d468 100644--- a/tests/test_openai_responses_compression_units.py+++ b/tests/test_openai_responses_compression_units.py@@ -1,5 +1,6 @@from __future__ import annotations+import threadingfrom types import MethodType, SimpleNamespacefrom headroom.proxy.handlers.openai import OpenAIHandlerMixin@@ -110,6 +111,122 @@ def test_openai_responses_adapter_compresses_custom_tool_call_output():assert strategy_chain == []+def test_openai_responses_adapter_reuses_exact_tool_output_cache():+ router = ContentRouter()+ calls = {"count": 0}++ def compress(self, content: str, **_kwargs):+ calls["count"] += 1+ return RouterCompressionResult(+ compressed="cached output summary",+ original=content,+ strategy_used=CompressionStrategy.KOMPRESS,+ )++ router.compress = MethodType(compress, router)+ handler = _handler_with_router(router)+ long_text = " ".join(f"word{i}" for i in range(180))++ payload_one = {+ "model": "gpt-5",+ "input": [+ {"type": "local_shell_call_output", "call_id": "c1", "output": long_text},+ ],+ }+ payload_two = {+ "model": "gpt-5",+ "input": [+ {"type": "message", "role": "user", "content": "changed envelope"},+ {"type": "local_shell_call_output", "call_id": "c2", "output": long_text},+ ],+ }++ new_payload_one, modified_one, saved_one, *_ = (+ handler._compress_openai_responses_live_text_units_with_router(+ payload_one,+ model="gpt-5",+ request_id="req_cache_one",+ )+ )+ new_payload_two, modified_two, saved_two, *_ = (+ handler._compress_openai_responses_live_text_units_with_router(+ payload_two,+ model="gpt-5",+ request_id="req_cache_two",+ )+ )++ assert calls["count"] == 1+ assert modified_one is True+ assert modified_two is True+ assert saved_one > 0+ assert saved_two == saved_one+ assert new_payload_one["input"][0]["output"] == "cached output summary"+ assert new_payload_two["input"][1]["output"] == "cached output summary"+++def test_openai_responses_adapter_parallelizes_cache_misses_preserving_order(monkeypatch):+ monkeypatch.setenv("HEADROOM_OPENAI_RESPONSES_UNIT_PARALLELISM", "4")+ router = ContentRouter()+ lock = threading.Lock()+ release = threading.Event()+ active = {"count": 0, "max": 0}++ def compress(self, content: str, **_kwargs):+ with lock:+ active["count"] += 1+ active["max"] = max(active["max"], active["count"])+ if active["count"] >= 2:+ release.set()+ release.wait(0.05)+ try:+ marker = content.rsplit(" marker", 1)[1]+ return RouterCompressionResult(+ compressed=f"summary marker{marker}",+ original=content,+ strategy_used=CompressionStrategy.KOMPRESS,+ )+ finally:+ with lock:+ active["count"] -= 1++ router.compress = MethodType(compress, router)+ handler = _handler_with_router(router)++ def long_text(index: int) -> str:+ return " ".join(f"word{index}_{j}" for j in range(180)) + f" marker{index}"++ payload = {+ "model": "gpt-5",+ "input": [+ {+ "type": "local_shell_call_output",+ "call_id": f"c{i}",+ "output": long_text(i),+ }+ for i in range(4)+ ],+ }++ new_payload, modified, saved, *_ = (+ handler._compress_openai_responses_live_text_units_with_router(+ payload,+ model="gpt-5",+ request_id="req_parallel",+ )+ )++ assert active["max"] >= 2+ assert modified is True+ assert saved > 0+ assert [item["output"] for item in new_payload["input"]] == [+ "summary marker0",+ "summary marker1",+ "summary marker2",+ "summary marker3",+ ]++def test_openai_responses_adapter_accepts_empty_input_list():router = ContentRouter()handler = _handler_with_router(router)diff --git a/tests/test_openai_responses_t3_replay_regression.py b/tests/test_openai_responses_t3_replay_regression.pynew file mode 100644index 000000000..494062536--- /dev/null+++ b/tests/test_openai_responses_t3_replay_regression.py@@ -0,0 +1,216 @@+from __future__ import annotations++import json+import threading+from dataclasses import dataclass+from types import MethodType, SimpleNamespace++from headroom.proxy.handlers.openai import OpenAIHandlerMixin+from headroom.transforms.content_router import (+ CompressionStrategy,+ ContentRouter,+ RouterCompressionResult,+)+++@dataclass(frozen=True)+class T3FailureCase:+ provider_log: str+ turn_id: str+ request_bytes: int+ unit_count: int+++# T3 provider logs keep the Headroom 413 metadata, not the raw /v1/responses+# body. These cases recreate the failing byte scale and Responses item shape.+T3_FAILED_CASES = (+ T3FailureCase(+ provider_log="2b38b84f-b6b0-4d92-8ff0-42f83b59dd70.log",+ turn_id="019e8c3f-91d9-73b3-a6f8-4e6ae312f91b",+ request_bytes=674_436,+ unit_count=8,+ ),+ T3FailureCase(+ provider_log="cc084653-feba-4241-a8fd-6655c0dfa799.log",+ turn_id="019e8bdd-ffb3-7f31-9182-51b2bdb96f52",+ request_bytes=1_288_876,+ unit_count=12,+ ),+)+++class TokenCounter:+ def count_text(self, text: str) -> int:+ return max(1, len(text) // 4)+++def _handler_with_router(router: ContentRouter) -> OpenAIHandlerMixin:+ handler = OpenAIHandlerMixin()+ handler.openai_pipeline = SimpleNamespace(transforms=[router])+ handler.openai_provider = SimpleNamespace(+ get_token_counter=lambda _model: TokenCounter(),+ )+ return handler+++def _tool_output(case: T3FailureCase, index: int, target_bytes: int) -> str:+ line = (+ f"{case.turn_id} {case.provider_log} "+ f"tool={index} path=/tmp/t3-live-output-{index}.txt status=ok "+ "alpha beta gamma delta epsilon zeta eta theta iota kappa\n"+ )+ return (line * ((target_bytes // len(line)) + 1))[:target_bytes]+++def _payload_for_case(case: T3FailureCase) -> dict:+ envelope_budget = 2_500+ per_unit_bytes = max(2_048, (case.request_bytes - envelope_budget) // case.unit_count)+ return {+ "model": "gpt-5.4-mini",+ "input": [+ {+ "type": "message",+ "role": "user",+ "content": "continue after tool output",+ },+ {+ "type": "function_call",+ "call_id": "call-shell",+ "name": "shell",+ "arguments": "{}",+ },+ *[+ {+ "type": "function_call_output",+ "call_id": f"call-shell-{index}",+ "output": _tool_output(case, index, per_unit_bytes),+ }+ for index in range(case.unit_count)+ ],+ ],+ }+++def _json_bytes(value: object) -> int:+ return len(json.dumps(value, separators=(",", ":"), default=str).encode("utf-8"))+++def test_t3_failed_size_responses_payload_parallelizes_uncached_tool_outputs(monkeypatch):+ monkeypatch.setenv("HEADROOM_OPENAI_RESPONSES_UNIT_PARALLELISM", "4")+ case = T3_FAILED_CASES[0]+ router = ContentRouter()+ lock = threading.Lock()+ release = threading.Event()+ active = {"count": 0, "max": 0, "calls": 0}++ def compress(self, content: str, **_kwargs):+ with lock:+ active["count"] += 1+ active["calls"] += 1+ active["max"] = max(active["max"], active["count"])+ if active["count"] >= 2:+ release.set()+ release.wait(0.05)+ try:+ marker = content.split(" tool=", 1)[1].split(" ", 1)[0]+ return RouterCompressionResult(+ compressed=f"summary for tool={marker}",+ original=content,+ strategy_used=CompressionStrategy.KOMPRESS,+ )+ finally:+ with lock:+ active["count"] -= 1++ router.compress = MethodType(compress, router)+ handler = _handler_with_router(router)+ payload = _payload_for_case(case)++ new_payload, modified, saved, transforms, units_by_category, _strategy_chain, attempted = (+ handler._compress_openai_responses_live_text_units_with_router(+ payload,+ model="gpt-5.4-mini",+ request_id=f"t3_replay_{case.turn_id}",+ )+ )++ assert _json_bytes(payload) >= case.request_bytes * 0.95+ assert attempted > 0+ assert modified is True+ assert saved > 0+ assert active["calls"] == case.unit_count+ assert active["max"] >= 2+ assert units_by_category == {"applied": case.unit_count}+ assert "router:openai:responses:function_call_output:kompress" in transforms+ outputs = [+ item["output"]+ for item in new_payload["input"]+ if item.get("type") == "function_call_output"+ ]+ assert outputs == [f"summary for tool={index}" for index in range(case.unit_count)]+++def test_t3_failed_size_exact_tool_output_cache_survives_history_changes():+ case = T3_FAILED_CASES[1]+ router = ContentRouter()+ calls = {"count": 0}++ def compress(self, content: str, **_kwargs):+ calls["count"] += 1+ marker = content.split(" tool=", 1)[1].split(" ", 1)[0]+ return RouterCompressionResult(+ compressed=f"cached summary for tool={marker}",+ original=content,+ strategy_used=CompressionStrategy.KOMPRESS,+ )++ router.compress = MethodType(compress, router)+ handler = _handler_with_router(router)+ first_payload = _payload_for_case(case)+ second_payload = {+ "model": "gpt-5.4-mini",+ "input": [+ # Simulate a harness that changed/trimmed the ancient envelope.+ {"type": "message", "role": "user", "content": "history compacted"},+ *first_payload["input"][2:],+ {+ "type": "function_call_output",+ "call_id": "call-shell-new",+ "output": _tool_output(case, case.unit_count, 32_000),+ },+ ],+ }++ first_new_payload, first_modified, first_saved, *_ = (+ handler._compress_openai_responses_live_text_units_with_router(+ first_payload,+ model="gpt-5.4-mini",+ request_id=f"t3_replay_cache_first_{case.turn_id}",+ )+ )+ second_new_payload, second_modified, second_saved, *_ = (+ handler._compress_openai_responses_live_text_units_with_router(+ second_payload,+ model="gpt-5.4-mini",+ request_id=f"t3_replay_cache_second_{case.turn_id}",+ )+ )++ assert first_modified is True+ assert second_modified is True+ assert first_saved > 0+ assert second_saved > 0+ assert calls["count"] == case.unit_count + 1+ assert [+ item["output"]+ for item in first_new_payload["input"]+ if item.get("type") == "function_call_output"+ ] == [f"cached summary for tool={index}" for index in range(case.unit_count)]+ assert [+ item["output"]+ for item in second_new_payload["input"]+ if item.get("type") == "function_call_output"+ ] == [+ *[f"cached summary for tool={index}" for index in range(case.unit_count)],+ f"cached summary for tool={case.unit_count}",+ ]