fix(proxy): turn off the image stage when --compressor leaves out image (#4723)

## Description

`headroom proxy --compressor` / `HEADROOM_COMPRESSORS` lists `image` and
says unselected built-ins are disabled. The selection only sets
`ContentRouterConfig.enable_image_optimizer`, which the proxy does not
consult. The Anthropic and OpenAI handlers gate their image stage on
`ProxyConfig.image_optimize`, and nothing set it from a selection. So
`--compressor smart_crusher` still sent every screenshot through the
image stage.

This PR makes the image gate honor the selection.
`ImageCompressionDecision`, which both handlers already call, reads
`config.compressors` on each request and skips the image stage with a
new reason, `image_not_selected`, when a selection leaves out `image`.
The operator's `image_optimize` is never written, and
`image_optimize=False` still wins. This is Gap 1 from #4613, agreed with
the reporter there. Gap 2 (Windows self-update while a proxy is running)
will be a separate PR.

Refs #4613

## 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)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/proxy/image_compression_policy.py`:
- `image_compressor_selected(compressors)` follows the same rules as
`_apply_compressor_selection`: no selection, an empty one or `*` keeps
images; otherwise `image` must be named.
- `decide_image_compression` takes `image_selected` (default `True`) and
adds `image_not_selected`, which comes after `image_optimize_disabled`
and before `no_messages`.
- `headroom/proxy/image_compression_decision.py`: `decide` passes the
selection from `config.compressors` and exposes `image_selected` next to
the other inputs it saw. The new reason appears in `image_skip_reason`.
- `tests/test_compressor_selection_image_stage.py`: sends a screenshot
request through the real proxy app with only the upstream faked. It runs
on two routes: Anthropic in token mode, and OpenAI chat in cache mode,
which still compresses images in cache mode. The cases are:
  - a selection without `image` never enters the image stage;
  - a selection with `image`, `*`, and no selection each enter it once;
  - a config reused across two proxies follows the current selection;
  - `image_optimize=False` with `image` selected still skips the stage.
- `tests/test_image_compression_decision.py`: covers the new reason, its
precedence, the wildcard and blank selections, and a config with no
`compressors` attribute.
- `docs/content/docs/proxy.mdx`: the `--compressor` row says that
leaving out `image` also turns off the image stage.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`): see Additional Notes
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

The new tests against `main`'s source (b21479e0):

```text
FAILED tests/test_compressor_selection_image_stage.py::TestImageStageFollowsSelection::test_selection_without_image_skips_the_image_stage[anthropic-token]
FAILED tests/test_compressor_selection_image_stage.py::TestImageStageFollowsSelection::test_selection_without_image_skips_the_image_stage[openai-cache]
FAILED tests/test_compressor_selection_image_stage.py::TestImageStageFollowsSelection::test_reused_config_follows_the_current_selection[anthropic-token]
FAILED tests/test_compressor_selection_image_stage.py::TestImageStageFollowsSelection::test_reused_config_follows_the_current_selection[openai-cache]
4 failed, 8 passed
```

At this head:

```text
$ pytest tests/test_compressor_selection.py tests/test_compressor_selection_image_stage.py tests/test_image_compression_decision.py tests/test_image_compression_policy.py tests/test_router_external_dispatch.py tests/test_proxy_eager_preload_bind.py -q
99 passed

$ pytest <every test file that mentions image_skip_reason, ImageCompressionDecision, image_optimize or compressors> -m "not live" -q
12 failed, 1994 passed, 26 skipped

$ ruff check <changed files> && ruff format --check <changed files>
All checks passed!
```

The 12 failures are in `tests/test_image_compressor.py`,
`tests/test_ccr_batch_processor.py`,
`tests/test_garbled_compression_fixes.py` and
`tests/test_transforms/test_content_router.py`. The same 12 fail on
`main` in my environment (the image ones because the venv has Pillow
12), so they are not from this change.

## Real Behavior Proof

- Environment: macOS (Darwin 24.6.0, arm64), Python 3.12.3, Pillow
13.0.0. Older Pillow makes the proxy forward images unchanged.
- Exact command / steps: the real proxy app in token mode on the
Anthropic route, with the real image compressor and image worker; only
the upstream model is faked, and it answers instantly. Each setting
sends the same 2560x1600 PNG screenshot ("what is the exact error text
in this screenshot?") 5 times. Per request, the script records
image-stage entries, what reached the upstream, and the time the proxy
took. Run once on `main` (b21479e0) and once on this branch.
- Observed result: on `main`, `--compressor smart_crusher` still ran the
image stage on 5 of 5 requests and downscaled every screenshot
(`full_low`, 1,870 → 255 tokens) at about 45 ms each. With this PR it
ran on 0 of 5, the original image went upstream unchanged, and each
request took 4.6 ms. With no selection or with `image` selected, both
builds behave the same. `image_optimize` stays `True` in every run.

| Build | Setting | Image-stage runs | Image sent upstream | Proxy time
p50 |
|---|---|---|---|---|
| `main` | no `--compressor` | 5 of 5 | downscaled (`full_low`, 1,870 →
255 tokens) | 45.4 ms |
| `main` | `--compressor smart_crusher` | **5 of 5** | **downscaled** |
**45.2 ms** |
| `main` | `--compressor smart_crusher,image` | 5 of 5 | downscaled |
46.9 ms |
| this PR | no `--compressor` | 5 of 5 | downscaled | 48.2 ms |
| this PR | `--compressor smart_crusher` | **0 of 5** | **original,
unchanged** | **4.6 ms** |
| this PR | `--compressor smart_crusher,image` | 5 of 5 | downscaled |
47.6 ms |

The first image request of each process also loads the image models
(about 1.0–1.3 s here). With `image` left out, that load doesn't happen.
- Not tested: a live upstream, the OCR (`transcode`) technique (the
router picked `full_low` for this screenshot), and Windows.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: only for a `--compressor` /
`HEADROOM_COMPRESSORS` selection that leaves out `image`. Those proxies
now forward images unchanged, as the help text already says. With no
selection, a selection that includes `image`, or `*`, nothing changes.
- Kill switch / disable path: add `image` to the selection, or remove
the selection
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert the PR's commits

## 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
- [x] 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)

## Screenshots (if applicable)

n/a

## Additional Notes

- Review follow-up: the first revision (619ea4ad) wrote
`image_optimize=False` into the caller's `ProxyConfig`. Now the decision
reads the selection on each request, so a reused config follows its
current selection, and an explicit `image_optimize=False` is kept.
- #1327 proposes a separate `HEADROOM_DISABLE_IMAGE_OPTIMIZER` variable.
This PR doesn't add one; it makes the existing option behave as its help
text says.
- `mypy headroom/proxy/server.py` stops in my local environment on a
`numpy` stub (`Type statement is only supported in Python 3.12 and
greater`) before reaching project code. CI runs mypy.
This commit is contained in:
SD
2026-11-10 10:39:18 -06:00
committed by GitHub
parent acb58a0c00
commit 8f04221b2d
5 changed files with 273 additions and 7 deletions
+1 -1
View File
@@ -337,7 +337,7 @@ Fine-grained control over what gets compressed and how hard. Most users pick a [
| `HEADROOM_COMPRESS_SYSTEM_MESSAGES` | unset | Compress system prompts. Off by default to keep the hottest cache prefix stable. |
| `HEADROOM_PROTECT_RECENT` | profile | Never compress the N most recent turns. |
| `--protect-tool-results` / `HEADROOM_PROTECT_TOOL_RESULTS` | empty | Comma-separated tool names whose output is never lossy-compressed. |
| `--compressor` (repeatable) / `HEADROOM_COMPRESSORS` | all | Restrict to specific compressors: `smart_crusher,kompress,code_aware,search,log,tabular,config,html,image`. |
| `--compressor` (repeatable) / `HEADROOM_COMPRESSORS` | all | Restrict to specific compressors: `smart_crusher,kompress,code_aware,search,log,tabular,config,html,image`. Leaving out `image` also turns off the proxy's image stage. |
| `--code-aware` / `--no-code-aware` | off | AST-based [code compression](/docs/code-compression). Requires `headroom-ai[code]`. |
### Kompress (ML compression)
+11 -3
View File
@@ -17,8 +17,9 @@ Precedence (highest first):
1. ``bypass_header`` — user's explicit opt-out
2. ``image_optimize_disabled`` — operator ``config.image_optimize=False``
3. ``no_messages`` — empty / missing messages
4. otherwise → ``should_compress=True``
3. ``image_not_selected`` — a ``--compressor`` selection without ``image``
4. ``no_messages`` — empty / missing messages
5. otherwise → ``should_compress=True``
Distinct from text :class:`CompressionDecision`'s
``compression_disabled`` reason: operators can enable text + disable
@@ -34,6 +35,7 @@ from typing import Any
from headroom.proxy.image_compression_policy import (
apply_image_skip_reason,
decide_image_compression,
image_compressor_selected,
)
@@ -55,6 +57,7 @@ class ImageCompressionDecision:
# can slice image-skipped traffic by cause. One of:
# * "bypass_header" — user set x-headroom-bypass/mode
# * "image_optimize_disabled" — operator config off
# * "image_not_selected" — compressor selection leaves out image
# * "no_messages" — empty / missing messages
# When ``should_compress`` is True, this is None.
passthrough_reason: str | None
@@ -63,6 +66,7 @@ class ImageCompressionDecision:
# answer "what did the decision see?" without re-running it.
bypass_header_set: bool
image_optimize_enabled: bool
image_selected: bool
has_messages: bool
@classmethod
@@ -83,7 +87,9 @@ class ImageCompressionDecision:
Bypass detected via ``_headroom_bypass_enabled``.
config
``HeadroomConfig``-shaped object; only ``image_optimize``
is read.
and ``compressors`` are read. The selection is read here rather
than folded into ``image_optimize`` so the operator's setting is
never overwritten (#4613).
messages
Request messages. ``None`` and ``[]`` are equivalent.
"""
@@ -91,6 +97,7 @@ class ImageCompressionDecision:
headers=headers,
image_optimize_enabled=bool(getattr(config, "image_optimize", False)),
has_messages=bool(messages),
image_selected=image_compressor_selected(getattr(config, "compressors", None)),
)
return cls(
@@ -98,6 +105,7 @@ class ImageCompressionDecision:
passthrough_reason=decision.passthrough_reason,
bypass_header_set=decision.bypass_header_set,
image_optimize_enabled=decision.image_optimize_enabled,
image_selected=decision.image_selected,
has_messages=decision.has_messages,
)
@@ -16,14 +16,29 @@ class ImageCompressionPolicyResult:
passthrough_reason: str | None
bypass_header_set: bool
image_optimize_enabled: bool
image_selected: bool
has_messages: bool
def image_compressor_selected(compressors: Any) -> bool:
"""Whether a ``--compressor`` selection leaves the image compressor on.
Mirrors how the proxy maps a selection onto the router's ``enable_*``
flags: no selection (``None``, empty, or only blank names) keeps every built-in,
``"*"`` selects all, and otherwise ``image`` must be named.
"""
if not isinstance(compressors, (set, frozenset, list, tuple)) or not compressors:
return True
selected = {name.strip() for name in compressors if name.strip()}
return not selected or "*" in selected or "image" in selected
def decide_image_compression(
*,
headers: Any,
image_optimize_enabled: bool,
has_messages: bool,
image_selected: bool = True,
) -> ImageCompressionPolicyResult:
"""Compute the canonical image-compression gate."""
bypass = _headroom_bypass_enabled(headers)
@@ -34,6 +49,9 @@ def decide_image_compression(
elif not image_optimize_enabled:
reason = "image_optimize_disabled"
should = False
elif not image_selected:
reason = "image_not_selected"
should = False
elif not has_messages:
reason = "no_messages"
should = False
@@ -46,6 +64,7 @@ def decide_image_compression(
passthrough_reason=reason,
bypass_header_set=bypass,
image_optimize_enabled=image_optimize_enabled,
image_selected=image_selected,
has_messages=has_messages,
)
@@ -0,0 +1,191 @@
"""A compressor selection without ``image`` turns off the proxy image stage (#4613).
``--compressor`` / ``HEADROOM_COMPRESSORS`` maps a selection onto the router's
``enable_*`` flags, but the provider handlers gate image compression through
``ImageCompressionDecision``. That decision has to honor the selection too, or
screenshots still go through the image stage. It reads the selection on each
request and never overwrites the operator's ``image_optimize``.
"""
from __future__ import annotations
from typing import Any
import httpx
import pytest
fastapi = pytest.importorskip("fastapi")
from fastapi.testclient import TestClient # noqa: E402
import headroom.proxy.helpers as helpers # noqa: E402
from headroom.proxy.server import ProxyConfig, create_app # noqa: E402
# A 1x1 PNG; the stub below never decodes it.
PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
class _CountingCompressor:
"""Stands in for the image compressor and counts image-stage entries."""
def __init__(self) -> None:
self.calls = 0
def has_images(self, messages: Any) -> bool:
self.calls += 1
return False
@pytest.fixture
def image_stage(monkeypatch: pytest.MonkeyPatch) -> _CountingCompressor:
stub = _CountingCompressor()
monkeypatch.setattr(helpers, "_get_image_compressor", lambda: stub)
return stub
def _config(mode: str, compressors: set[str] | None, *, image_optimize: bool = True) -> ProxyConfig:
return ProxyConfig(
mode=mode,
image_optimize=image_optimize,
optimize=False,
cache_enabled=False,
rate_limit_enabled=False,
memory_enabled=False,
compressors=compressors,
)
async def _fake_retry(method, url, headers, body, *args, **kwargs): # noqa: ANN001
if "chat/completions" in url:
payload: dict[str, Any] = {
"id": "chatcmpl-1",
"object": "chat.completion",
"model": "gpt-test",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "a screenshot"},
"finish_reason": "stop",
}
],
"usage": {"prompt_tokens": 10, "completion_tokens": 3, "total_tokens": 13},
}
else:
payload = {
"id": "msg_1",
"type": "message",
"role": "assistant",
"model": "sonnet-test",
"content": [{"type": "text", "text": "a screenshot"}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 10, "output_tokens": 3},
}
return httpx.Response(200, json=payload, headers={"content-type": "application/json"})
def _anthropic_image_request(client: TestClient) -> httpx.Response:
return client.post(
"/v1/messages",
headers={"x-api-key": "test-key", "anthropic-version": "2023-06-01"},
json={
"model": "sonnet-test",
"max_tokens": 32,
"messages": [
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": PNG_B64,
},
},
{"type": "text", "text": "what is on this screen?"},
],
}
],
},
)
def _openai_image_request(client: TestClient) -> httpx.Response:
return client.post(
"/v1/chat/completions",
headers={"authorization": "Bearer test-key"},
json={
"model": "gpt-test",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{PNG_B64}"},
},
{"type": "text", "text": "what is on this screen?"},
],
}
],
},
)
def _image_stage_runs(config: ProxyConfig, send: Any, image_stage: _CountingCompressor) -> int:
"""Send one image request through a fresh proxy; return image-stage entries."""
before = image_stage.calls
with TestClient(create_app(config)) as client:
client.app.state.proxy._retry_request = _fake_retry
response = send(client)
assert response.status_code == 200, response.text
return image_stage.calls - before
@pytest.mark.parametrize(
("mode", "send"),
[
# Anthropic skips the image stage in cache mode, so token mode exercises it.
("token", _anthropic_image_request),
# The OpenAI route compresses images in either mode.
("cache", _openai_image_request),
],
ids=["anthropic-token", "openai-cache"],
)
class TestImageStageFollowsSelection:
def test_selection_without_image_skips_the_image_stage(
self, mode: str, send: Any, image_stage: _CountingCompressor
) -> None:
config = _config(mode, {"smart_crusher"})
assert _image_stage_runs(config, send, image_stage) == 0
# The operator's setting is left as given.
assert config.image_optimize is True
def test_selection_with_image_keeps_the_image_stage(
self, mode: str, send: Any, image_stage: _CountingCompressor
) -> None:
assert _image_stage_runs(_config(mode, {"smart_crusher", "image"}), send, image_stage) == 1
def test_wildcard_keeps_the_image_stage(
self, mode: str, send: Any, image_stage: _CountingCompressor
) -> None:
assert _image_stage_runs(_config(mode, {"*"}), send, image_stage) == 1
def test_no_selection_keeps_the_image_stage(
self, mode: str, send: Any, image_stage: _CountingCompressor
) -> None:
assert _image_stage_runs(_config(mode, None), send, image_stage) == 1
def test_reused_config_follows_the_current_selection(
self, mode: str, send: Any, image_stage: _CountingCompressor
) -> None:
config = _config(mode, {"smart_crusher"})
assert _image_stage_runs(config, send, image_stage) == 0
config.compressors = {"image"}
assert _image_stage_runs(config, send, image_stage) == 1
def test_image_optimize_off_wins_over_selecting_image(
self, mode: str, send: Any, image_stage: _CountingCompressor
) -> None:
config = _config(mode, {"image"}, image_optimize=False)
assert _image_stage_runs(config, send, image_stage) == 0
+51 -3
View File
@@ -29,10 +29,10 @@ from headroom.proxy.image_compression_decision import ImageCompressionDecision
# ── Helpers ───────────────────────────────────────────────────────────
def _config(*, image_optimize: bool = True) -> Any:
"""Minimal stand-in for ``HeadroomConfig`` — only the field the
def _config(*, image_optimize: bool = True, compressors: set[str] | None = None) -> Any:
"""Minimal stand-in for ``HeadroomConfig`` — only the fields the
decision reads."""
return SimpleNamespace(image_optimize=image_optimize)
return SimpleNamespace(image_optimize=image_optimize, compressors=compressors)
def _msgs(n: int = 1) -> list[dict[str, str]]:
@@ -105,6 +105,49 @@ def test_image_optimize_disabled_is_skip() -> None:
assert d.passthrough_reason == "image_optimize_disabled"
def test_selection_without_image_is_skip() -> None:
"""A ``--compressor`` selection that leaves out ``image`` (#4613)."""
d = ImageCompressionDecision.decide(
headers={}, config=_config(compressors={"smart_crusher"}), messages=_msgs()
)
assert d.should_compress is False
assert d.passthrough_reason == "image_not_selected"
assert d.image_selected is False
assert d.image_optimize_enabled is True
def test_selection_with_image_or_wildcard_compresses() -> None:
for compressors in ({"image"}, {"smart_crusher", " image "}, {"*"}, set(), {" "}):
d = ImageCompressionDecision.decide(
headers={}, config=_config(compressors=compressors), messages=_msgs()
)
assert d.should_compress is True, compressors
assert d.image_selected is True
def test_config_without_compressors_attribute_compresses() -> None:
d = ImageCompressionDecision.decide(
headers={}, config=SimpleNamespace(image_optimize=True), messages=_msgs()
)
assert d.should_compress is True
def test_image_optimize_disabled_beats_image_not_selected() -> None:
d = ImageCompressionDecision.decide(
headers={},
config=_config(image_optimize=False, compressors={"smart_crusher"}),
messages=_msgs(),
)
assert d.passthrough_reason == "image_optimize_disabled"
def test_image_not_selected_beats_no_messages() -> None:
d = ImageCompressionDecision.decide(
headers={}, config=_config(compressors={"smart_crusher"}), messages=[]
)
assert d.passthrough_reason == "image_not_selected"
def test_no_messages_is_skip() -> None:
"""Empty or missing messages — nothing to look at. Same shape as
CompressionDecision's no_messages reason."""
@@ -228,6 +271,11 @@ def test_apply_to_tags_for_every_skip_reason() -> None:
"config": _config(image_optimize=False),
"messages": _msgs(),
},
"image_not_selected": {
"headers": {},
"config": _config(compressors={"smart_crusher"}),
"messages": _msgs(),
},
"no_messages": {
"headers": {},
"config": _config(),