feat(proxy): select built-in compressors via --compressor + registry inventory (#2373)
## What
- Adds an opt-in `--compressor` / `HEADROOM_COMPRESSORS` selection that
narrows the active built-in compressors, mapped onto the existing
`ContentRouterConfig` `enable_*` flags at the proxy config seam.
Recognized names: `smart_crusher, kompress, code_aware, search, log,
tabular, config, html, image`; `"*"` selects all.
- Builds a name-addressable compressor registry in `ContentRouter`: a
metadata-only descriptor per built-in plus opt-in discovery of
`headroom.compressor` entry points (the seam added in #2370).
## Why
Built-in compressors were only reachable through a hardcoded if/elif;
there was no supported way to select a subset (7 of the `enable_*` flags
had no external surface) or to see the built-ins as a name-addressable
set alongside third-party ones.
## Behavior change
**None by default.** `--compressor` unset (the default) leaves every
`enable_*` flag at its dataclass default, so the request path is
byte-identical to today. The registry is inventory-only — built-ins are
still constructed and dispatched by the existing if/elif;
`_BuiltinCompressorEntry.compress` deliberately raises (never called),
and registry construction is fail-open. Routing an external compressor
*through* the pipeline is a deliberate follow-up.
## How
- `server.py`: `BUILTIN_COMPRESSOR_FLAGS` map +
`_apply_compressor_selection(router_config, compressors)` (no-op when
`None`/empty; runs before the `disable_kompress` override so that stays
authoritative).
- `models.py`: `ProxyConfig.compressors: set[str] | None = None`.
- `cli/proxy.py`: `--compressor` (repeatable, comma-split,
`HEADROOM_COMPRESSORS`), mirroring `--proxy-extension`.
- `content_router.py`: built-in descriptors +
`_build_compressor_registry()` (register built-ins, then fail-open
`discover()`), exposed as `self.compressor_registry`. Dispatch
unchanged.
## Testing
`tests/test_compressor_selection.py` — 23 tests: selection mapping
(None/empty/whitespace = byte-identical defaults, single/multi/wildcard,
external-only disables built-ins, unrecognized ignored), `ProxyConfig`
field, registry inventory (descriptors cover the 9 names, valid cost
tiers, router exposes registry, inventory doesn't auto-activate,
built-in `compress` guard, discovery merges external, fail-open on
discovery error). Local: 23 passed; ruff + mypy clean on changed files.
Full suite runs in CI.
Stacks conceptually on #2370 (registry seam); rebased onto `main` after
that merged.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-18 01:30:37 -07:00
|
|
|
"""Tests for compressor selection (swap-OUT built-ins) + registry inventory.
|
|
|
|
|
|
|
|
|
|
Covers the two behavior-safe halves of the router/registry integration:
|
|
|
|
|
|
|
|
|
|
1. Selection surface: ``ProxyConfig.compressors`` mapped onto the router's
|
|
|
|
|
``enable_*`` flags at the proxy seam (``_apply_compressor_selection``).
|
|
|
|
|
Default (``None``) must leave every flag at its dataclass default so the
|
|
|
|
|
request path is byte-identical to today.
|
|
|
|
|
2. Registry inventory: ``ContentRouter`` builds a ``CompressorRegistry`` with a
|
|
|
|
|
metadata-only entry for every built-in plus opt-in entry-point discovery,
|
|
|
|
|
without changing dispatch.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import dataclasses
|
fix(proxy): warn when --compressor selection matches no built-in (#2385)
## Description
A `--compressor` selection that matches no built-in name (e.g.
`smart_krusher`, a typo of `smart_crusher`) silently disables **all**
built-in compression: the proxy starts healthy, the dashboard shows ~0
savings, and nothing explains why.
The all-off *semantics* is deliberate and stays untouched —
`test_only_external_name_disables_all_builtins` pins the opt-in "exactly
these" contract, and external/registry names are a legitimate input
class. What's missing is any **signal**: a typo and an external
compressor name are indistinguishable at this seam, and the registry's
own unregistered-name warning (`CompressorRegistry.select`) never runs
on this path.
Fix: `_apply_compressor_selection` now logs one warning when the
selection contains unmatched names —
- **nothing matched** (the typo case): says plainly that every built-in
compressor is now disabled and lists the valid names + `*`;
- **mixed**: names the unmatched entries as assumed registry names.
Selection results are byte-identical before/after.
Fixes #2384.
## Type of Change
- [x] Bug fix (observability for a silent misconfiguration; no behavior
change)
## Changes Made
- `headroom/proxy/server.py`: `_apply_compressor_selection` computes the
unmatched set and emits one `headroom.proxy` warning (two phrasings:
nothing-matched vs mixed); docstring updated.
- `tests/test_compressor_selection.py`: 3 new tests — typo-only
selection warns (and flags stay all-off, pinning the unchanged
contract), mixed selection warns only about the unmatched name,
matched/wildcard selections stay warning-free.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff` + `mypy`, CI-pinned settings)
- [x] Wrote the failing tests first, then the warning
### Test Output
```text
$ .venv/bin/python -m pytest tests/test_compressor_selection.py -q
26 passed
# Before the fix the two new warning tests fail (no log records emitted).
$ ruff check headroom/proxy/server.py tests/test_compressor_selection.py # All checks passed!
$ ruff format --check <both> # formatted
$ mypy headroom/proxy/server.py --ignore-missing-imports # Success: no issues
```
## Real Behavior Proof
- Environment: macOS (Darwin), Python in a uv venv, branch
`fix/compressor-selection-warn` off `main` (`56c7d4a5`).
- Exact command / steps: configured stdlib logging at WARNING and called
`_apply_compressor_selection(ContentRouterConfig(), {"smart_krusher"})`
— the exact typo scenario from #2384.
- Observed result: `WARNING headroom.proxy: compressor selection
smart_krusher matches no built-in compressor — every built-in compressor
is now disabled. If this is a typo, valid names are: code_aware, config,
html, image, kompress, log, search, smart_crusher, tabular (or '*' for
all).` with `enable_smart_crusher = False` (contract unchanged). Before
the fix the same call produced zero log output.
- Not tested: a full `headroom proxy --compressor smart_krusher` process
launch; the seam is exercised directly and the proxy wires it
unconditionally.
## 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
- [ ] I have made corresponding changes to the documentation — N/A
(docstring updated)
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective
- [x] New and existing unit tests pass locally with my changes
- [ ] I have updated the CHANGELOG.md — N/A
## Additional Notes
- Deliberately warn-only: erroring here would break legitimate
external/registry selections and could brick startup on a stale
`HEADROOM_COMPRESSORS` settings value. If you'd rather hard-fail just
the CLI-typed path, happy to follow up.
2026-07-19 00:51:05 +08:00
|
|
|
import logging
|
feat(proxy): select built-in compressors via --compressor + registry inventory (#2373)
## What
- Adds an opt-in `--compressor` / `HEADROOM_COMPRESSORS` selection that
narrows the active built-in compressors, mapped onto the existing
`ContentRouterConfig` `enable_*` flags at the proxy config seam.
Recognized names: `smart_crusher, kompress, code_aware, search, log,
tabular, config, html, image`; `"*"` selects all.
- Builds a name-addressable compressor registry in `ContentRouter`: a
metadata-only descriptor per built-in plus opt-in discovery of
`headroom.compressor` entry points (the seam added in #2370).
## Why
Built-in compressors were only reachable through a hardcoded if/elif;
there was no supported way to select a subset (7 of the `enable_*` flags
had no external surface) or to see the built-ins as a name-addressable
set alongside third-party ones.
## Behavior change
**None by default.** `--compressor` unset (the default) leaves every
`enable_*` flag at its dataclass default, so the request path is
byte-identical to today. The registry is inventory-only — built-ins are
still constructed and dispatched by the existing if/elif;
`_BuiltinCompressorEntry.compress` deliberately raises (never called),
and registry construction is fail-open. Routing an external compressor
*through* the pipeline is a deliberate follow-up.
## How
- `server.py`: `BUILTIN_COMPRESSOR_FLAGS` map +
`_apply_compressor_selection(router_config, compressors)` (no-op when
`None`/empty; runs before the `disable_kompress` override so that stays
authoritative).
- `models.py`: `ProxyConfig.compressors: set[str] | None = None`.
- `cli/proxy.py`: `--compressor` (repeatable, comma-split,
`HEADROOM_COMPRESSORS`), mirroring `--proxy-extension`.
- `content_router.py`: built-in descriptors +
`_build_compressor_registry()` (register built-ins, then fail-open
`discover()`), exposed as `self.compressor_registry`. Dispatch
unchanged.
## Testing
`tests/test_compressor_selection.py` — 23 tests: selection mapping
(None/empty/whitespace = byte-identical defaults, single/multi/wildcard,
external-only disables built-ins, unrecognized ignored), `ProxyConfig`
field, registry inventory (descriptors cover the 9 names, valid cost
tiers, router exposes registry, inventory doesn't auto-activate,
built-in `compress` guard, discovery merges external, fail-open on
discovery error). Local: 23 passed; ruff + mypy clean on changed files.
Full suite runs in CI.
Stacks conceptually on #2370 (registry seam); rebased onto `main` after
that merged.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-18 01:30:37 -07:00
|
|
|
|
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
|
|
from headroom.proxy.models import ProxyConfig
|
|
|
|
|
from headroom.proxy.server import (
|
|
|
|
|
BUILTIN_COMPRESSOR_FLAGS,
|
|
|
|
|
_apply_compressor_selection,
|
|
|
|
|
)
|
|
|
|
|
from headroom.transforms import compressor_registry as cr_module
|
|
|
|
|
from headroom.transforms.compressor_registry import (
|
|
|
|
|
CompressInput,
|
|
|
|
|
CompressorDescriptor,
|
|
|
|
|
CompressOutput,
|
|
|
|
|
)
|
|
|
|
|
from headroom.transforms.content_router import (
|
|
|
|
|
_BUILTIN_COMPRESSOR_DESCRIPTORS,
|
|
|
|
|
ContentRouter,
|
|
|
|
|
ContentRouterConfig,
|
|
|
|
|
_build_compressor_registry,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# The nine recognized built-in selection names.
|
|
|
|
|
_BUILTIN_NAMES = {
|
|
|
|
|
"smart_crusher",
|
|
|
|
|
"kompress",
|
|
|
|
|
"code_aware",
|
|
|
|
|
"search",
|
|
|
|
|
"log",
|
|
|
|
|
"tabular",
|
|
|
|
|
"config",
|
|
|
|
|
"html",
|
|
|
|
|
"image",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _enable_flags(config: ContentRouterConfig) -> dict[str, bool]:
|
|
|
|
|
return {flag: getattr(config, flag) for flag in BUILTIN_COMPRESSOR_FLAGS.values()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ─────────────────────────── selection mapping ───────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_flag_map_covers_the_nine_recognized_names() -> None:
|
|
|
|
|
assert set(BUILTIN_COMPRESSOR_FLAGS) == _BUILTIN_NAMES
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_flag_map_targets_real_config_fields() -> None:
|
|
|
|
|
fields = {f.name for f in dataclasses.fields(ContentRouterConfig)}
|
|
|
|
|
for flag in BUILTIN_COMPRESSOR_FLAGS.values():
|
|
|
|
|
assert flag in fields, f"{flag} is not a ContentRouterConfig field"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_none_selection_is_a_noop_byte_identical_defaults() -> None:
|
|
|
|
|
"""Default (no --compressor) must leave every enable_* at its default."""
|
|
|
|
|
baseline = _enable_flags(ContentRouterConfig())
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
_apply_compressor_selection(config, None)
|
|
|
|
|
assert _enable_flags(config) == baseline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_empty_selection_is_a_noop() -> None:
|
|
|
|
|
baseline = _enable_flags(ContentRouterConfig())
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
_apply_compressor_selection(config, set())
|
|
|
|
|
assert _enable_flags(config) == baseline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_whitespace_only_selection_is_a_noop() -> None:
|
|
|
|
|
baseline = _enable_flags(ContentRouterConfig())
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
_apply_compressor_selection(config, {"", " "})
|
|
|
|
|
assert _enable_flags(config) == baseline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_single_selection_enables_only_that_builtin() -> None:
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
_apply_compressor_selection(config, {"kompress"})
|
|
|
|
|
flags = _enable_flags(config)
|
|
|
|
|
assert flags["enable_kompress"] is True
|
|
|
|
|
for name, flag in BUILTIN_COMPRESSOR_FLAGS.items():
|
|
|
|
|
if name != "kompress":
|
|
|
|
|
assert flags[flag] is False, f"{flag} should be disabled"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_multi_selection_enables_exactly_those() -> None:
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
_apply_compressor_selection(config, {"smart_crusher", "log"})
|
|
|
|
|
flags = _enable_flags(config)
|
|
|
|
|
enabled = {name for name, flag in BUILTIN_COMPRESSOR_FLAGS.items() if flags[flag]}
|
|
|
|
|
assert enabled == {"smart_crusher", "log"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_selecting_code_aware_enables_it_even_though_it_defaults_off() -> None:
|
|
|
|
|
# enable_code_aware defaults to False; an explicit selection turns it on.
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
assert config.enable_code_aware is False
|
|
|
|
|
_apply_compressor_selection(config, {"code_aware"})
|
|
|
|
|
assert config.enable_code_aware is True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_wildcard_enables_all_builtins() -> None:
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
_apply_compressor_selection(config, {"*"})
|
|
|
|
|
assert all(_enable_flags(config).values())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_selection_strips_whitespace() -> None:
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
_apply_compressor_selection(config, {" kompress ", " search"})
|
|
|
|
|
flags = _enable_flags(config)
|
|
|
|
|
enabled = {name for name, flag in BUILTIN_COMPRESSOR_FLAGS.items() if flags[flag]}
|
|
|
|
|
assert enabled == {"kompress", "search"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_only_external_name_disables_all_builtins() -> None:
|
|
|
|
|
# Selecting only a non-builtin (an external/registry name) disables every
|
|
|
|
|
# recognized built-in — the opt-in "exactly these" contract.
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
_apply_compressor_selection(config, {"my_external_compressor"})
|
|
|
|
|
assert not any(_enable_flags(config).values())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_unrecognized_names_are_ignored_but_recognized_still_apply() -> None:
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
_apply_compressor_selection(config, {"kompress", "does_not_exist"})
|
|
|
|
|
flags = _enable_flags(config)
|
|
|
|
|
assert flags["enable_kompress"] is True
|
|
|
|
|
# No crash / no spurious flag creation for the unknown name.
|
|
|
|
|
|
|
|
|
|
|
fix(proxy): warn when --compressor selection matches no built-in (#2385)
## Description
A `--compressor` selection that matches no built-in name (e.g.
`smart_krusher`, a typo of `smart_crusher`) silently disables **all**
built-in compression: the proxy starts healthy, the dashboard shows ~0
savings, and nothing explains why.
The all-off *semantics* is deliberate and stays untouched —
`test_only_external_name_disables_all_builtins` pins the opt-in "exactly
these" contract, and external/registry names are a legitimate input
class. What's missing is any **signal**: a typo and an external
compressor name are indistinguishable at this seam, and the registry's
own unregistered-name warning (`CompressorRegistry.select`) never runs
on this path.
Fix: `_apply_compressor_selection` now logs one warning when the
selection contains unmatched names —
- **nothing matched** (the typo case): says plainly that every built-in
compressor is now disabled and lists the valid names + `*`;
- **mixed**: names the unmatched entries as assumed registry names.
Selection results are byte-identical before/after.
Fixes #2384.
## Type of Change
- [x] Bug fix (observability for a silent misconfiguration; no behavior
change)
## Changes Made
- `headroom/proxy/server.py`: `_apply_compressor_selection` computes the
unmatched set and emits one `headroom.proxy` warning (two phrasings:
nothing-matched vs mixed); docstring updated.
- `tests/test_compressor_selection.py`: 3 new tests — typo-only
selection warns (and flags stay all-off, pinning the unchanged
contract), mixed selection warns only about the unmatched name,
matched/wildcard selections stay warning-free.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff` + `mypy`, CI-pinned settings)
- [x] Wrote the failing tests first, then the warning
### Test Output
```text
$ .venv/bin/python -m pytest tests/test_compressor_selection.py -q
26 passed
# Before the fix the two new warning tests fail (no log records emitted).
$ ruff check headroom/proxy/server.py tests/test_compressor_selection.py # All checks passed!
$ ruff format --check <both> # formatted
$ mypy headroom/proxy/server.py --ignore-missing-imports # Success: no issues
```
## Real Behavior Proof
- Environment: macOS (Darwin), Python in a uv venv, branch
`fix/compressor-selection-warn` off `main` (`56c7d4a5`).
- Exact command / steps: configured stdlib logging at WARNING and called
`_apply_compressor_selection(ContentRouterConfig(), {"smart_krusher"})`
— the exact typo scenario from #2384.
- Observed result: `WARNING headroom.proxy: compressor selection
smart_krusher matches no built-in compressor — every built-in compressor
is now disabled. If this is a typo, valid names are: code_aware, config,
html, image, kompress, log, search, smart_crusher, tabular (or '*' for
all).` with `enable_smart_crusher = False` (contract unchanged). Before
the fix the same call produced zero log output.
- Not tested: a full `headroom proxy --compressor smart_krusher` process
launch; the seam is exercised directly and the proxy wires it
unconditionally.
## 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
- [ ] I have made corresponding changes to the documentation — N/A
(docstring updated)
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective
- [x] New and existing unit tests pass locally with my changes
- [ ] I have updated the CHANGELOG.md — N/A
## Additional Notes
- Deliberately warn-only: erroring here would break legitimate
external/registry selections and could brick startup on a stale
`HEADROOM_COMPRESSORS` settings value. If you'd rather hard-fail just
the CLI-typed path, happy to follow up.
2026-07-19 00:51:05 +08:00
|
|
|
# ────────────────── unmatched-name warning (#2384, no behavior change) ────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_only_unmatched_selection_warns_that_builtins_are_disabled(
|
|
|
|
|
caplog: pytest.LogCaptureFixture,
|
|
|
|
|
) -> None:
|
|
|
|
|
"""A typo'd selection must be diagnosable from the startup log."""
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
with caplog.at_level(logging.WARNING, logger="headroom.proxy"):
|
|
|
|
|
_apply_compressor_selection(config, {"smart_krusher"})
|
|
|
|
|
# Behavior is unchanged — the opt-in "exactly these" contract still holds.
|
|
|
|
|
assert not any(_enable_flags(config).values())
|
|
|
|
|
text = " ".join(r.getMessage() for r in caplog.records)
|
|
|
|
|
assert "smart_krusher" in text
|
|
|
|
|
assert "disabled" in text.lower()
|
|
|
|
|
assert "smart_crusher" in text # valid names listed for the typo case
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_mixed_selection_warns_only_about_unmatched_names(
|
|
|
|
|
caplog: pytest.LogCaptureFixture,
|
|
|
|
|
) -> None:
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
with caplog.at_level(logging.WARNING, logger="headroom.proxy"):
|
|
|
|
|
_apply_compressor_selection(config, {"kompress", "does_not_exist"})
|
|
|
|
|
assert _enable_flags(config)["enable_kompress"] is True
|
|
|
|
|
text = " ".join(r.getMessage() for r in caplog.records)
|
|
|
|
|
assert "does_not_exist" in text
|
|
|
|
|
assert "disabled" not in text.lower() # built-ins were not all turned off
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_matched_selection_emits_no_warning(caplog: pytest.LogCaptureFixture) -> None:
|
|
|
|
|
for selection in ({"kompress"}, {"*"}):
|
|
|
|
|
config = ContentRouterConfig()
|
|
|
|
|
with caplog.at_level(logging.WARNING, logger="headroom.proxy"):
|
|
|
|
|
_apply_compressor_selection(config, selection)
|
|
|
|
|
assert not caplog.records
|
|
|
|
|
|
|
|
|
|
|
feat(proxy): select built-in compressors via --compressor + registry inventory (#2373)
## What
- Adds an opt-in `--compressor` / `HEADROOM_COMPRESSORS` selection that
narrows the active built-in compressors, mapped onto the existing
`ContentRouterConfig` `enable_*` flags at the proxy config seam.
Recognized names: `smart_crusher, kompress, code_aware, search, log,
tabular, config, html, image`; `"*"` selects all.
- Builds a name-addressable compressor registry in `ContentRouter`: a
metadata-only descriptor per built-in plus opt-in discovery of
`headroom.compressor` entry points (the seam added in #2370).
## Why
Built-in compressors were only reachable through a hardcoded if/elif;
there was no supported way to select a subset (7 of the `enable_*` flags
had no external surface) or to see the built-ins as a name-addressable
set alongside third-party ones.
## Behavior change
**None by default.** `--compressor` unset (the default) leaves every
`enable_*` flag at its dataclass default, so the request path is
byte-identical to today. The registry is inventory-only — built-ins are
still constructed and dispatched by the existing if/elif;
`_BuiltinCompressorEntry.compress` deliberately raises (never called),
and registry construction is fail-open. Routing an external compressor
*through* the pipeline is a deliberate follow-up.
## How
- `server.py`: `BUILTIN_COMPRESSOR_FLAGS` map +
`_apply_compressor_selection(router_config, compressors)` (no-op when
`None`/empty; runs before the `disable_kompress` override so that stays
authoritative).
- `models.py`: `ProxyConfig.compressors: set[str] | None = None`.
- `cli/proxy.py`: `--compressor` (repeatable, comma-split,
`HEADROOM_COMPRESSORS`), mirroring `--proxy-extension`.
- `content_router.py`: built-in descriptors +
`_build_compressor_registry()` (register built-ins, then fail-open
`discover()`), exposed as `self.compressor_registry`. Dispatch
unchanged.
## Testing
`tests/test_compressor_selection.py` — 23 tests: selection mapping
(None/empty/whitespace = byte-identical defaults, single/multi/wildcard,
external-only disables built-ins, unrecognized ignored), `ProxyConfig`
field, registry inventory (descriptors cover the 9 names, valid cost
tiers, router exposes registry, inventory doesn't auto-activate,
built-in `compress` guard, discovery merges external, fail-open on
discovery error). Local: 23 passed; ruff + mypy clean on changed files.
Full suite runs in CI.
Stacks conceptually on #2370 (registry seam); rebased onto `main` after
that merged.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-18 01:30:37 -07:00
|
|
|
# ─────────────────────────── ProxyConfig field ───────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_proxyconfig_compressors_defaults_to_none() -> None:
|
|
|
|
|
assert ProxyConfig().compressors is None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_proxyconfig_accepts_compressor_set() -> None:
|
|
|
|
|
config = ProxyConfig(compressors={"kompress", "smart_crusher"})
|
|
|
|
|
assert config.compressors == {"kompress", "smart_crusher"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ─────────────────────────── registry inventory ──────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_builtin_descriptors_cover_the_nine_names() -> None:
|
|
|
|
|
names = {d.name for d in _BUILTIN_COMPRESSOR_DESCRIPTORS}
|
|
|
|
|
assert names == _BUILTIN_NAMES
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_builtin_descriptor_names_match_selection_flag_map() -> None:
|
|
|
|
|
names = {d.name for d in _BUILTIN_COMPRESSOR_DESCRIPTORS}
|
|
|
|
|
assert names == set(BUILTIN_COMPRESSOR_FLAGS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_builtin_descriptors_have_valid_cost_tiers() -> None:
|
|
|
|
|
for d in _BUILTIN_COMPRESSOR_DESCRIPTORS:
|
|
|
|
|
assert d.cost_tier in cr_module.COST_TIERS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_build_registry_registers_all_builtins() -> None:
|
|
|
|
|
registry = _build_compressor_registry()
|
|
|
|
|
assert set(registry.names()) >= _BUILTIN_NAMES
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_content_router_exposes_populated_registry() -> None:
|
|
|
|
|
router = ContentRouter(ContentRouterConfig())
|
|
|
|
|
assert set(router.compressor_registry.names()) >= _BUILTIN_NAMES
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_registry_inventory_does_not_enable_selection() -> None:
|
|
|
|
|
# Inventory is metadata only: with no selection resolved, nothing is active.
|
|
|
|
|
registry = _build_compressor_registry()
|
|
|
|
|
assert registry.active(None) == []
|
|
|
|
|
|
|
|
|
|
|
feat(transforms): make built-in compressors real Compressor implementations (adapters) (#2391)
## What
Turns each built-in registry entry into a working `Compressor` (the
`compressor_registry` contract): `compress(CompressInput) ->
CompressOutput` delegates to the same underlying built-in method the
content router already invokes in `_apply_strategy_to_content`, reached
through the router's own `_get_*` getter so config flows through
identically. Token counts use the router's `_estimate_tokens`;
`lossless` mirrors the descriptor; `recoverable` is `{}` (built-ins
persist CCR recovery to the store as a side effect, not via their return
value).
Adapted: `smart_crusher, code_aware, search, log, tabular, config, html,
kompress`.
## Behavior change
**None — additive by construction.** Dispatch, the `_get_*` getters,
fallback chains, the reversibility gate, and config are all unchanged.
The router still dispatches built-ins via its existing if/elif and never
routes a request through the registry;
`_resolve_active_external_compressors` filters built-in entries out of
the opt-in external-dispatch path *by type* (the class name
`_BuiltinCompressorEntry` is load-bearing). A default request is
byte-identical: `_active_external_compressors == []`, external dispatch
is an inert guard, and adapters are reachable only via
`compressor_registry.get()/active()`.
## `image` — documented passthrough (not a guess)
`ImageCompressor.compress(messages)` operates on image blocks inside
message dicts, not `str` content, and isn't on the
`_apply_strategy_to_content` path, so there's no faithful `str→str`
delegation. Its adapter is a documented non-raising passthrough rather
than a fabricated one.
## Testing
`tests/test_builtin_compressor_adapters.py` — differential tests
asserting each adapter's output matches the built-in's direct output
(JSON→smart_crusher, CSV→tabular, log lines→log, grep→search,
config→config, Python→code_aware, HTML→html); kompress is mocked (no ML
inference); every registry entry has a working non-raising `compress`.
Updated the obsolete guard test in `test_compressor_selection.py`.
Offline suite: 72 passed; ruff + mypy clean. (Broad
content-router/compression suite deferred to CI — it needs HF-Hub/ONNX
model loads.)
This is PR-A of the adapter phase (built-ins become Compressor
implementations); flipping the router's dispatch to registry-resolved is
the follow-up. Builds on #2370/#2371/#2373/#2388.
2026-07-18 12:59:49 -07:00
|
|
|
def test_builtin_entry_compress_delegates_via_router() -> None:
|
|
|
|
|
# The built-in entries now expose a WORKING (non-raising) compress that
|
|
|
|
|
# delegates to the router's own dispatch path. kompress with ML disabled is a
|
|
|
|
|
# passthrough (no model load), proving the entry runs without raising.
|
|
|
|
|
router = ContentRouter(ContentRouterConfig(enable_kompress=False))
|
|
|
|
|
entry = router.compressor_registry.get("kompress")
|
|
|
|
|
assert entry is not None
|
|
|
|
|
out = entry.compress(CompressInput(content="hello world", content_type="text/plain"))
|
|
|
|
|
assert isinstance(out, CompressOutput)
|
|
|
|
|
assert out.content == "hello world" # ML disabled → passthrough, never raises
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_builtin_entry_without_router_is_inert_passthrough() -> None:
|
|
|
|
|
# A registry built with no bound router (module-level inventory use) has
|
|
|
|
|
# nothing to delegate to, so compress is an inert passthrough — still working
|
|
|
|
|
# (non-raising), never a fabricated result.
|
feat(proxy): select built-in compressors via --compressor + registry inventory (#2373)
## What
- Adds an opt-in `--compressor` / `HEADROOM_COMPRESSORS` selection that
narrows the active built-in compressors, mapped onto the existing
`ContentRouterConfig` `enable_*` flags at the proxy config seam.
Recognized names: `smart_crusher, kompress, code_aware, search, log,
tabular, config, html, image`; `"*"` selects all.
- Builds a name-addressable compressor registry in `ContentRouter`: a
metadata-only descriptor per built-in plus opt-in discovery of
`headroom.compressor` entry points (the seam added in #2370).
## Why
Built-in compressors were only reachable through a hardcoded if/elif;
there was no supported way to select a subset (7 of the `enable_*` flags
had no external surface) or to see the built-ins as a name-addressable
set alongside third-party ones.
## Behavior change
**None by default.** `--compressor` unset (the default) leaves every
`enable_*` flag at its dataclass default, so the request path is
byte-identical to today. The registry is inventory-only — built-ins are
still constructed and dispatched by the existing if/elif;
`_BuiltinCompressorEntry.compress` deliberately raises (never called),
and registry construction is fail-open. Routing an external compressor
*through* the pipeline is a deliberate follow-up.
## How
- `server.py`: `BUILTIN_COMPRESSOR_FLAGS` map +
`_apply_compressor_selection(router_config, compressors)` (no-op when
`None`/empty; runs before the `disable_kompress` override so that stays
authoritative).
- `models.py`: `ProxyConfig.compressors: set[str] | None = None`.
- `cli/proxy.py`: `--compressor` (repeatable, comma-split,
`HEADROOM_COMPRESSORS`), mirroring `--proxy-extension`.
- `content_router.py`: built-in descriptors +
`_build_compressor_registry()` (register built-ins, then fail-open
`discover()`), exposed as `self.compressor_registry`. Dispatch
unchanged.
## Testing
`tests/test_compressor_selection.py` — 23 tests: selection mapping
(None/empty/whitespace = byte-identical defaults, single/multi/wildcard,
external-only disables built-ins, unrecognized ignored), `ProxyConfig`
field, registry inventory (descriptors cover the 9 names, valid cost
tiers, router exposes registry, inventory doesn't auto-activate,
built-in `compress` guard, discovery merges external, fail-open on
discovery error). Local: 23 passed; ruff + mypy clean on changed files.
Full suite runs in CI.
Stacks conceptually on #2370 (registry seam); rebased onto `main` after
that merged.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-18 01:30:37 -07:00
|
|
|
registry = _build_compressor_registry()
|
|
|
|
|
entry = registry.get("kompress")
|
|
|
|
|
assert entry is not None
|
feat(transforms): make built-in compressors real Compressor implementations (adapters) (#2391)
## What
Turns each built-in registry entry into a working `Compressor` (the
`compressor_registry` contract): `compress(CompressInput) ->
CompressOutput` delegates to the same underlying built-in method the
content router already invokes in `_apply_strategy_to_content`, reached
through the router's own `_get_*` getter so config flows through
identically. Token counts use the router's `_estimate_tokens`;
`lossless` mirrors the descriptor; `recoverable` is `{}` (built-ins
persist CCR recovery to the store as a side effect, not via their return
value).
Adapted: `smart_crusher, code_aware, search, log, tabular, config, html,
kompress`.
## Behavior change
**None — additive by construction.** Dispatch, the `_get_*` getters,
fallback chains, the reversibility gate, and config are all unchanged.
The router still dispatches built-ins via its existing if/elif and never
routes a request through the registry;
`_resolve_active_external_compressors` filters built-in entries out of
the opt-in external-dispatch path *by type* (the class name
`_BuiltinCompressorEntry` is load-bearing). A default request is
byte-identical: `_active_external_compressors == []`, external dispatch
is an inert guard, and adapters are reachable only via
`compressor_registry.get()/active()`.
## `image` — documented passthrough (not a guess)
`ImageCompressor.compress(messages)` operates on image blocks inside
message dicts, not `str` content, and isn't on the
`_apply_strategy_to_content` path, so there's no faithful `str→str`
delegation. Its adapter is a documented non-raising passthrough rather
than a fabricated one.
## Testing
`tests/test_builtin_compressor_adapters.py` — differential tests
asserting each adapter's output matches the built-in's direct output
(JSON→smart_crusher, CSV→tabular, log lines→log, grep→search,
config→config, Python→code_aware, HTML→html); kompress is mocked (no ML
inference); every registry entry has a working non-raising `compress`.
Updated the obsolete guard test in `test_compressor_selection.py`.
Offline suite: 72 passed; ruff + mypy clean. (Broad
content-router/compression suite deferred to CI — it needs HF-Hub/ONNX
model loads.)
This is PR-A of the adapter phase (built-ins become Compressor
implementations); flipping the router's dispatch to registry-resolved is
the follow-up. Builds on #2370/#2371/#2373/#2388.
2026-07-18 12:59:49 -07:00
|
|
|
out = entry.compress(CompressInput(content="x", content_type="text/plain"))
|
|
|
|
|
assert isinstance(out, CompressOutput)
|
|
|
|
|
assert out.content == "x"
|
feat(proxy): select built-in compressors via --compressor + registry inventory (#2373)
## What
- Adds an opt-in `--compressor` / `HEADROOM_COMPRESSORS` selection that
narrows the active built-in compressors, mapped onto the existing
`ContentRouterConfig` `enable_*` flags at the proxy config seam.
Recognized names: `smart_crusher, kompress, code_aware, search, log,
tabular, config, html, image`; `"*"` selects all.
- Builds a name-addressable compressor registry in `ContentRouter`: a
metadata-only descriptor per built-in plus opt-in discovery of
`headroom.compressor` entry points (the seam added in #2370).
## Why
Built-in compressors were only reachable through a hardcoded if/elif;
there was no supported way to select a subset (7 of the `enable_*` flags
had no external surface) or to see the built-ins as a name-addressable
set alongside third-party ones.
## Behavior change
**None by default.** `--compressor` unset (the default) leaves every
`enable_*` flag at its dataclass default, so the request path is
byte-identical to today. The registry is inventory-only — built-ins are
still constructed and dispatched by the existing if/elif;
`_BuiltinCompressorEntry.compress` deliberately raises (never called),
and registry construction is fail-open. Routing an external compressor
*through* the pipeline is a deliberate follow-up.
## How
- `server.py`: `BUILTIN_COMPRESSOR_FLAGS` map +
`_apply_compressor_selection(router_config, compressors)` (no-op when
`None`/empty; runs before the `disable_kompress` override so that stays
authoritative).
- `models.py`: `ProxyConfig.compressors: set[str] | None = None`.
- `cli/proxy.py`: `--compressor` (repeatable, comma-split,
`HEADROOM_COMPRESSORS`), mirroring `--proxy-extension`.
- `content_router.py`: built-in descriptors +
`_build_compressor_registry()` (register built-ins, then fail-open
`discover()`), exposed as `self.compressor_registry`. Dispatch
unchanged.
## Testing
`tests/test_compressor_selection.py` — 23 tests: selection mapping
(None/empty/whitespace = byte-identical defaults, single/multi/wildcard,
external-only disables built-ins, unrecognized ignored), `ProxyConfig`
field, registry inventory (descriptors cover the 9 names, valid cost
tiers, router exposes registry, inventory doesn't auto-activate,
built-in `compress` guard, discovery merges external, fail-open on
discovery error). Local: 23 passed; ruff + mypy clean on changed files.
Full suite runs in CI.
Stacks conceptually on #2370 (registry seam); rebased onto `main` after
that merged.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-18 01:30:37 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_discovery_merges_external_compressor(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
|
|
|
"""A discovered `headroom.compressor` entry point joins the built-in inventory."""
|
|
|
|
|
|
|
|
|
|
class _FakeExternal:
|
|
|
|
|
@property
|
|
|
|
|
def descriptor(self) -> CompressorDescriptor:
|
|
|
|
|
return CompressorDescriptor(
|
|
|
|
|
name="fake_external",
|
|
|
|
|
content_types=["text/plain"],
|
|
|
|
|
lossless=True,
|
|
|
|
|
cost_tier="fast",
|
|
|
|
|
recoverable=False,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def compress(self, inp: CompressInput) -> CompressOutput:
|
|
|
|
|
return CompressOutput(
|
|
|
|
|
content=inp.content,
|
|
|
|
|
tokens_before=1,
|
|
|
|
|
tokens_after=1,
|
|
|
|
|
lossless=True,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
class _FakeEntry:
|
|
|
|
|
name = "fake_external"
|
|
|
|
|
|
|
|
|
|
def load(self) -> type[_FakeExternal]:
|
|
|
|
|
return _FakeExternal
|
|
|
|
|
|
|
|
|
|
def _fake_entry_points(*, group: str) -> list[_FakeEntry]:
|
|
|
|
|
assert group == cr_module.ENTRY_POINT_GROUP
|
|
|
|
|
return [_FakeEntry()]
|
|
|
|
|
|
|
|
|
|
monkeypatch.setattr(cr_module.importlib.metadata, "entry_points", _fake_entry_points)
|
|
|
|
|
|
|
|
|
|
registry = _build_compressor_registry()
|
|
|
|
|
assert "fake_external" in registry.names()
|
|
|
|
|
assert set(registry.names()) >= _BUILTIN_NAMES
|
|
|
|
|
# The external one is selectable/active; built-ins are inventory-only.
|
|
|
|
|
active = registry.active({"fake_external"})
|
|
|
|
|
assert [c.descriptor.name for c in active] == ["fake_external"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_router_construction_is_unchanged_by_default_registry(
|
|
|
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
|
|
|
) -> None:
|
|
|
|
|
# Even if discovery raises, the router still constructs with an empty-but-
|
|
|
|
|
# present registry (fail-open) — never breaking the request path.
|
|
|
|
|
def _boom(*, group: str) -> list[object]:
|
|
|
|
|
raise RuntimeError("discovery blew up")
|
|
|
|
|
|
|
|
|
|
monkeypatch.setattr(cr_module.importlib.metadata, "entry_points", _boom)
|
|
|
|
|
router = ContentRouter(ContentRouterConfig())
|
|
|
|
|
# discover() itself is fail-open, so built-ins are still registered.
|
|
|
|
|
assert set(router.compressor_registry.names()) >= _BUILTIN_NAMES
|