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(proxy): isolate image compression in a subprocess so a native SIGSEGV can't take down the proxy (#2107) (#2162)
Rod Boev09e72125b427
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d6a69a647..28485abe8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## Unreleased### Fixed+- **proxy image compression:** run native image compression in a spawned subprocess so an OpenCV or KleidiCV crash now fails open to the original image payload instead of taking down the whole proxy process ([#2107](https://github.com/headroomlabs-ai/headroom/issues/2107)).- **proxy/windows:** support Windows selector-event-loop startup on uvicorn versions older than 0.36. Newer uvicorn accepts `loop="asyncio:SelectorEventLoop"` as a custom loop-factory import path, but older versions treat it as an unknown built-in loop name and raise `KeyError`. Windows now sets `WindowsSelectorEventLoopPolicy` for those older versions instead of passing an unsupported `loop` value ([#1650](https://github.com/headroomlabs-ai/headroom/issues/1650), [#1621](https://github.com/headroomlabs-ai/headroom/issues/1621)).- **backends/litellm:** preserve `cache_control` on `tool_result` blocks when converting Anthropic messages for the Bedrock Converse path, and complete streaming cache-stats surfacing in `stream_message`. Complements [#1390](https://github.com/headroomlabs-ai/headroom/pull/1390), which preserves `cache_control` on the system prompt and plain text blocks but explicitly leaves `tool_result` out of scope — in agent loops the moving cache breakpoint lands on the tail `tool_result` far more often than on the system prompt, so that gap left most of the caching benefit on the table. Separately, `stream_message` never requested `stream_options.include_usage`, so LiteLLM/Bedrock never returned a usage chunk over SSE and `cache_read_input_tokens`/`cache_creation_input_tokens` always reported 0 downstream even when the prompt cache was genuinely engaged; the terminal `message_delta` now carries the real cache values captured from the trailing usage chunk once the stream completes.- **shared_context:** `SharedContext.put` no longer evicts an unrelated entry when it merely updates a key that is already cached at capacity — same defect class fixed for `SemanticCache` in [#2094](https://github.com/headroomlabs-ai/headroom/pull/2094).diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 44e851845..4ee7b5958 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -31,6 +31,7 @@ from headroom.proxy.compression_decision import CompressionDecisionfrom headroom.proxy.forwarded_headers import resolve_client_ipfrom headroom.proxy.handlers._debug_dump import _debug_dump_mode, _redact_debug_valuefrom headroom.proxy.helpers import extract_tags+from headroom.proxy.image_isolation import run_image_compression_isolatedfrom headroom.proxy.memory_decision import MemoryDecisionfrom headroom.proxy.memory_query import MemoryQueryfrom headroom.proxy.outcome import RequestOutcome@@ -1156,19 +1157,18 @@ class AnthropicHandlerMixin:try:compressor = _get_image_compressor()if compressor and compressor.has_images(messages):- # Offload CPU-bound image compression onto the bounded- # executor (same as text compression); inline blocked the loop.- messages = await self._run_compression_in_executor(- lambda: compressor.compress(messages, provider="anthropic"),+ messages, image_result = await run_image_compression_isolated(+ messages,+ provider="anthropic",timeout=COMPRESSION_TIMEOUT_SECONDS,)- body_mutation_tracker.mark_mutated("image_compression")- if compressor.last_result:+ if image_result is not None:+ body_mutation_tracker.mark_mutated("image_compression")logger.info(- f"Image compression: {compressor.last_result.technique.value} "- f"({compressor.last_result.savings_percent:.0f}% saved, "- f"{compressor.last_result.original_tokens} -> "- f"{compressor.last_result.compressed_tokens} tokens)"+ f"Image compression: {image_result['technique']} "+ f"({image_result['savings_percent']:.0f}% saved, "+ f"{image_result['original_tokens']} -> "+ f"{image_result['compressed_tokens']} tokens)")except Exception as e:# Image compression is best-effort — fail open on timeout/error anddiff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex effb7b982..1e6fa37bc 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -69,6 +69,7 @@ from headroom.proxy.auth_mode import (from headroom.proxy.compression_decision import CompressionDecisionfrom headroom.proxy.cost import _summarize_transforms, header_safe_transformsfrom headroom.proxy.handlers._debug_dump import _debug_dump_mode, _redact_debug_value+from headroom.proxy.image_isolation import run_image_compression_isolatedfrom headroom.proxy.outcome import RequestOutcomefrom headroom.proxy.passthrough import (custom_base_passthrough_telemetry as _custom_base_passthrough_telemetry,@@ -2309,18 +2310,17 @@ class OpenAIHandlerMixin:try:compressor = _get_image_compressor()if compressor and compressor.has_images(messages):- # Offload CPU-bound image compression onto the bounded- # executor (same as text compression); inline blocked the loop.- messages = await self._run_compression_in_executor(- lambda: compressor.compress(messages, provider="openai"),+ messages, image_result = await run_image_compression_isolated(+ messages,+ provider="openai",timeout=COMPRESSION_TIMEOUT_SECONDS,)- if compressor.last_result:+ if image_result is not None:logger.info(- f"[{request_id}] Image: {compressor.last_result.technique.value} "- f"({compressor.last_result.savings_percent:.0f}% saved, "- f"{compressor.last_result.original_tokens} → "- f"{compressor.last_result.compressed_tokens} tokens)"+ f"[{request_id}] Image: {image_result['technique']} "+ f"({image_result['savings_percent']:.0f}% saved, "+ f"{image_result['original_tokens']} → "+ f"{image_result['compressed_tokens']} tokens)")except Exception as e:# Image compression is best-effort — fail open on timeout/error anddiff --git a/headroom/proxy/image_isolation.py b/headroom/proxy/image_isolation.pynew file mode 100644index 000000000..b0176ef7a--- /dev/null+++ b/headroom/proxy/image_isolation.py@@ -0,0 +1,129 @@+from __future__ import annotations++import asyncio+import logging+import multiprocessing+import os+import threading+import time+from collections.abc import Callable+from concurrent.futures import ProcessPoolExecutor, TimeoutError+from concurrent.futures.process import BrokenProcessPool+from typing import Any++logger = logging.getLogger("headroom.proxy")++_IMAGE_POOL_LOCK = threading.Lock()+_IMAGE_POOL: ProcessPoolExecutor | None = None+++def _compress_messages_worker(+ messages: list[dict[str, Any]],+ provider: str,+) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:+ from headroom.image import ImageCompressor++ compressor = ImageCompressor()+ try:+ compressed = compressor.compress(messages, provider=provider)+ if compressor.last_result is None:+ return compressed, None+ return compressed, {+ "technique": compressor.last_result.technique.value,+ "original_tokens": compressor.last_result.original_tokens,+ "compressed_tokens": compressor.last_result.compressed_tokens,+ "confidence": compressor.last_result.confidence,+ "savings_percent": compressor.last_result.savings_percent,+ }+ finally:+ compressor.close()+++def _success_worker(+ messages: list[dict[str, Any]],+ provider: str,+) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:+ compressed = [dict(message) for message in messages]+ compressed[-1] = {**compressed[-1], "content": f"compressed:{provider}"}+ return compressed, {+ "technique": "preserve",+ "original_tokens": 100,+ "compressed_tokens": 60,+ "confidence": 1.0,+ "savings_percent": 40.0,+ }+++def _raise_worker(+ messages: list[dict[str, Any]],+ provider: str,+) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:+ raise RuntimeError(f"boom:{provider}")+++def _sleep_worker(+ messages: list[dict[str, Any]],+ provider: str,+) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:+ time.sleep(0.2)+ return messages, None+++def _abort_worker(+ messages: list[dict[str, Any]],+ provider: str,+) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:+ os.abort()+++_IMAGE_WORKER: Callable[+ [list[dict[str, Any]], str],+ tuple[list[dict[str, Any]], dict[str, Any] | None],+] = _compress_messages_worker+++def _image_pool() -> ProcessPoolExecutor:+ global _IMAGE_POOL+ with _IMAGE_POOL_LOCK:+ if _IMAGE_POOL is None:+ _IMAGE_POOL = ProcessPoolExecutor(+ max_workers=1,+ mp_context=multiprocessing.get_context("spawn"),+ )+ return _IMAGE_POOL+++def _reset_image_pool() -> None:+ global _IMAGE_POOL+ with _IMAGE_POOL_LOCK:+ pool = _IMAGE_POOL+ _IMAGE_POOL = None+ if pool is not None:+ pool.shutdown(wait=False, cancel_futures=True)+++async def run_image_compression_isolated(+ messages: list[dict[str, Any]],+ provider: str,+ *,+ timeout: float,+) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:+ loop = asyncio.get_running_loop()+ try:+ future = loop.run_in_executor(_image_pool(), _IMAGE_WORKER, messages, provider)+ return await asyncio.wait_for(future, timeout=timeout)+ except BrokenProcessPool:+ logger.warning("Image compression worker crashed; forwarding original image payload")+ _reset_image_pool()+ return messages, None+ except TimeoutError:+ logger.warning("Image compression worker timed out; forwarding original image payload")+ _reset_image_pool()+ return messages, None+ except Exception as exc:+ logger.warning(+ "Image compression worker failed (%s); forwarding original image payload",+ type(exc).__name__,+ )+ _reset_image_pool()+ return messages, Nonediff --git a/tests/test_image_compression_isolation.py b/tests/test_image_compression_isolation.pynew file mode 100644index 000000000..8509f13bc--- /dev/null+++ b/tests/test_image_compression_isolation.py@@ -0,0 +1,117 @@+from __future__ import annotations++import inspect++import pytest++from headroom.proxy import image_isolation+from headroom.proxy.handlers.anthropic import AnthropicHandlerMixin+from headroom.proxy.handlers.openai import OpenAIHandlerMixin++[email protected](autouse=True)+def _reset_image_pool() -> None:+ image_isolation._reset_image_pool()+ try:+ yield+ finally:+ image_isolation._reset_image_pool()+ image_isolation._IMAGE_WORKER = image_isolation._compress_messages_worker+++def _messages() -> list[dict[str, object]]:+ return [{"role": "user", "content": "image payload"}]+++async def test_worker_sigsegv_fails_open_parent_survives(monkeypatch) -> None:+ messages = _messages()+ monkeypatch.setattr(image_isolation, "_IMAGE_WORKER", image_isolation._abort_worker)++ returned, result = await image_isolation.run_image_compression_isolated(+ messages,+ provider="openai",+ timeout=5.0,+ )++ assert returned is messages+ assert result is None++ monkeypatch.setattr(image_isolation, "_IMAGE_WORKER", image_isolation._success_worker)+ recovered, recovered_result = await image_isolation.run_image_compression_isolated(+ messages,+ provider="openai",+ timeout=5.0,+ )++ assert recovered[-1]["content"] == "compressed:openai"+ assert recovered_result is not None+++async def test_worker_exception_fails_open(monkeypatch) -> None:+ messages = _messages()+ monkeypatch.setattr(image_isolation, "_IMAGE_WORKER", image_isolation._raise_worker)++ returned, result = await image_isolation.run_image_compression_isolated(+ messages,+ provider="anthropic",+ timeout=5.0,+ )++ assert returned is messages+ assert result is None+++async def test_worker_timeout_fails_open(monkeypatch) -> None:+ messages = _messages()+ monkeypatch.setattr(image_isolation, "_IMAGE_WORKER", image_isolation._sleep_worker)++ returned, result = await image_isolation.run_image_compression_isolated(+ messages,+ provider="openai",+ timeout=0.05,+ )++ assert returned is messages+ assert result is None++ monkeypatch.setattr(image_isolation, "_IMAGE_WORKER", image_isolation._success_worker)+ recovered, recovered_result = await image_isolation.run_image_compression_isolated(+ messages,+ provider="openai",+ timeout=5.0,+ )++ assert recovered[-1]["content"] == "compressed:openai"+ assert recovered_result is not None+++async def test_worker_success_returns_compressed(monkeypatch) -> None:+ messages = _messages()+ monkeypatch.setattr(image_isolation, "_IMAGE_WORKER", image_isolation._success_worker)++ returned, result = await image_isolation.run_image_compression_isolated(+ messages,+ provider="anthropic",+ timeout=5.0,+ )++ assert returned[-1]["content"] == "compressed:anthropic"+ assert result == {+ "technique": "preserve",+ "original_tokens": 100,+ "compressed_tokens": 60,+ "confidence": 1.0,+ "savings_percent": 40.0,+ }+++def test_success_marks_mutation_and_logs() -> None:+ anthropic_src = inspect.getsource(AnthropicHandlerMixin.handle_anthropic_messages)+ openai_src = inspect.getsource(OpenAIHandlerMixin.handle_openai_chat)++ assert "run_image_compression_isolated(" in anthropic_src+ assert 'body_mutation_tracker.mark_mutated("image_compression")' in anthropic_src+ assert "Image compression:" in anthropic_src++ assert "run_image_compression_isolated(" in openai_src+ assert "Image:" in openai_srcdiff --git a/tests/test_image_compression_offload.py b/tests/test_image_compression_offload.pyindex 0794bb05e..ae29cea7d 100644--- a/tests/test_image_compression_offload.py+++ b/tests/test_image_compression_offload.py@@ -1,78 +1,49 @@-"""Image compression offload (perf): the Anthropic and OpenAI handlers must run the-CPU-bound `ImageCompressor.compress()` on the bounded compression executor, not inline-on the event loop, and fail open if it raises — matching the text-compression path.+"""Image compression must stay off the event loop and behind the isolation runner.-Mirrors test_gemini_compression_offload.py. The wiring (each image block awaits-`_run_compression_in_executor(lambda: compressor.compress(...))`) reuses the proven-text path; these tests assert the observable properties that wiring delivers: the-blocks are async + offloaded + fail open, and the executor keeps the loop responsive-while a slow compression runs on a worker thread.+The handlers no longer call `compressor.compress(...)` on the thread pool. They+delegate to `run_image_compression_isolated(...)`, which moves the native image+stack into a spawned subprocess so OpenCV crashes fail open without taking down+the proxy."""from __future__ import annotationsimport asyncioimport inspect-import threading-import time+import pytest++from headroom.proxy import image_isolationfrom headroom.proxy.handlers.anthropic import AnthropicHandlerMixinfrom headroom.proxy.handlers.openai import OpenAIHandlerMixin-from headroom.proxy.server import ProxyConfig, create_app-def _make_proxy(): # noqa: ANN202 — returns the internal HeadroomProxy- app = create_app(- ProxyConfig(- optimize=True,- cache_enabled=False,- rate_limit_enabled=False,- cost_tracking_enabled=False,- )- )- return app.state.proxy[email protected](autouse=True)+def _reset_image_pool() -> None:+ image_isolation._reset_image_pool()+ try:+ yield+ finally:+ image_isolation._reset_image_pool()+ image_isolation._IMAGE_WORKER = image_isolation._compress_messages_worker-def test_image_blocks_offload_compress_and_fail_open() -> None:- """Each image-compress block must be async, offload compress() onto the executor with a- timeout, and fail open. Guards a future refactor from silently re-inlining compress()."""+def test_image_blocks_use_isolation_runner_and_fail_open() -> None:for mixin, method in ((AnthropicHandlerMixin, "handle_anthropic_messages"),(OpenAIHandlerMixin, "handle_openai_chat"),):fn = getattr(mixin, method)- assert inspect.iscoroutinefunction(fn), f"{method} must be async to await the offload"+ assert inspect.iscoroutinefunction(fn), f"{method} must be async to await the isolation"src = inspect.getsource(fn)- assert "compressor.compress(" in src, f"{method}: image compress call missing"- assert "_run_compression_in_executor(" in src, f"{method}: compress not offloaded"- assert "COMPRESSION_TIMEOUT_SECONDS" in src, f"{method}: offload missing a timeout"+ assert "run_image_compression_isolated(" in src, f"{method}: isolation runner missing"+ assert "COMPRESSION_TIMEOUT_SECONDS" in src, f"{method}: isolation missing a timeout"assert "Image compression failed" in src, f"{method}: image compress not fail-open"-async def test_image_compress_offload_runs_on_worker_thread() -> None:- """The exact call the image blocks make — _run_compression_in_executor(lambda: compress()) —- runs compress() on a 'headroom-compress' executor thread, not the event-loop thread."""- proxy = _make_proxy()- loop_thread = threading.current_thread().name- seen: dict[str, str] = {}-- def _slow_compress(): # noqa: ANN202 — stands in for ImageCompressor.compress- seen["thread"] = threading.current_thread().name- time.sleep(0.1)- return [{"role": "user", "content": "compressed"}]-- result = await proxy._run_compression_in_executor(_slow_compress, timeout=10)-- assert result == [{"role": "user", "content": "compressed"}]- assert seen["thread"].startswith("headroom-compress")- assert seen["thread"] != loop_thread---async def test_image_compress_offload_keeps_event_loop_responsive() -> None:- """While a slow image compression runs on the executor, the loop keeps scheduling- coroutines. The bug this fixes — a bare inline compress() — would starve them to ~0 ticks."""- proxy = _make_proxy()+async def test_image_isolation_keeps_event_loop_responsive() -> None:ticks = 0+ image_isolation._IMAGE_WORKER = image_isolation._sleep_workerasync def _ticker() -> None:nonlocal ticks@@ -80,15 +51,16 @@ async def test_image_compress_offload_keeps_event_loop_responsive() -> None:await asyncio.sleep(0.01)ticks += 1- def _slow_compress(): # noqa: ANN202- time.sleep(0.3)- return "x"-tick_task = asyncio.create_task(_ticker())try:- result = await proxy._run_compression_in_executor(_slow_compress, timeout=10)+ returned, result = await image_isolation.run_image_compression_isolated(+ [{"role": "user", "content": "image payload"}],+ provider="openai",+ timeout=1.0,+ )finally:tick_task.cancel()- assert result == "x"- assert ticks >= 5 # ~30 expected at 10ms over 0.3s; a blocked loop yields near zero+ assert returned == [{"role": "user", "content": "image payload"}]+ assert result is None+ assert ticks >= 5