Commit Graph
4 Commits
Author SHA1 Message Date
NAZIYAandJerrettDavis a656eb4370 fix(kompress): prevent loading model when enable_kompress is False (#4667)
## Description

Fixes an issue where setting `HEADROOM_DISABLE_KOMPRESS=1` (or
configuring `ContentRouterConfig(enable_kompress=False)`) still loaded
the Kompress ONNX model when `_get_kompress()` was accessed (such as
during `/v1/compress` pipelines or reasoning compaction handlers). When
Kompress is disabled, `_get_kompress()` now returns `None` immediately
without downloading or loading ONNX model weights into memory, saving ~1
GB of resident memory.

Closes #4666

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

## Changes Made

- Added `if not self.config.enable_kompress: return None` at the entry
of `ContentRouter._get_kompress()` in
`headroom/transforms/content_router.py`.
- Added check `and _rc_router.config.enable_kompress` before querying
`_rc_kompress` in `headroom/proxy/handlers/openai.py`.
- Explicitly passed `enable_kompress=False` in `ContentRouterConfig`
during `cold_recompact_messages()` in
`headroom/transforms/cold_prefix.py`.
- Added test cases in `tests/test_proxy_disable_kompress.py` asserting
that when `enable_kompress=False`, neither `is_kompress_available()`,
`KompressCompressor()`, nor `_get_remote_kompress()` are ever called or
instantiated.

## Testing

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

### Test Output

```text
============================= test session starts =============================
platform win32 -- Python 3.14.5, pytest-9.0.3, pluggy-1.6.0
rootdir: C:\Users\dorni\OneDrive\Desktop\New folder\scratch\headroom
configfile: pyproject.toml
plugins: anyio-4.13.0, hypothesis-6.165.9, cov-7.1.0, schemathesis-4.24.3
collected 8 items

tests\test_proxy_disable_kompress.py ........                            [100%]

======================== 8 passed, 1 warning in 4.91s =========================
```

## Real Behavior Proof

- Environment: Windows 11 x64, Python 3.14.5, pytest 9.0.3
- Exact command / steps: python -c "from
headroom.transforms.content_router import ContentRouter,
ContentRouterConfig; r =
ContentRouter(ContentRouterConfig(enable_kompress=False));
print('Kompress instance with enable_kompress=False:',
r._get_kompress())"
- Observed result: Kompress instance with enable_kompress=False: None.
Verified via mock spied call sites that is_kompress_available(),
KompressCompressor(), and _get_remote_kompress() are never invoked when
enable_kompress=False.
- Not tested: Live Kubernetes cluster deployment, GPU ONNX execution
provider.

## Runtime Rollout Safety

- Rollout-managed feature(s): Kompress ONNX model loader bypass on
ContentRouter
- Minimum rollout channel: dev
- Stable/default behavior changed: No (when enable_kompress is True or
default, existing Kompress instantiation logic executes unchanged)
- Kill switch / disable path: HEADROOM_DISABLE_KOMPRESS=1 /
--disable-kompress
- Unsafe override required: None
- Qualification impact: Low (purely safeguards the disabled codepath
from unintended initialization)
- Rollback path: Revert commit cleanly

## 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

Closes #4666. All tests verified locally and CI governance checks
conform to repository standards.


### Maintainer current-main requalification

Exact head `be97f120eb9926e99d4008471d09bd93972564c1`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Maintainer current-main review against
c01cf07d94. Clean mechanical
synchronization preserves all contributor production changes. Added only
a real reasoning-request regression test: actual /v1/chat/completions
routing reaches a controlled upstream, forwards reasoning unchanged when
disabled, and never queries the remote loader. Isolating the old handler
guard makes that test fail with one unwanted loader call; restoring
exact contributor bytes passes. All55
disable/cold-prefix/sticky-reasoning/remote-Kompress tests pass with the
fresh main native DLL; touched test Ruff/format and whitespace pass. No
production logic rewritten.

### Maintainer independent live HTTP proof

Environment: Windows x64, Python3.12.13, fresh native binding whose Rust
input tree matches current main; real Uvicorn HTTP listener plus two
disposable localhost HTTP fixtures (upstream and remote Kompress). No ML
model weights or cloud service are needed. This is separate from the
pytest assertions.

Observed results:
- Current main control, disable_kompress=True: HTTP200,1upstream
request,1remote inference request,remote client constructed,plaintext
reasoning changed. The disabled-state assertion fails as expected.
- Reviewed PR, disable_kompress=True: HTTP200,1upstream request,0remote
inference requests,no local or remote Kompress instance,original
reasoning preserved.
- Reviewed PR, disable_kompress=False positive control:
HTTP200,1upstream request,1remote inference request,remote client
constructed,reasoning compacted.

The untested scope is local ONNX/GPU inference, quantitative RSS savings
and deployed Kubernetes; this proves disabled request
routing/initialization and preserves enabled remote inference.

Reproduction: in an isolated checkout install the proxy extra (`python
-m pip install -e ".[proxy]"`), save the code below as
`kompress_probe.py`, then run `python kompress_probe.py disabled` and
`python kompress_probe.py enabled`. The same disabled command on main
c01cf07d reproduces the baseline failure. The script binds only
ephemeral loopback ports and shuts all servers down.

<details>
<summary>Standalone live HTTP probe</summary>

```python
import json
import os
from pathlib import Path
import socket
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

disabled = sys.argv[1] == 'disabled'
for key in ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'HEADROOM_KOMPRESS_ENDPOINT_TOKEN', 'HEADROOM_KOMPRESS_ENDPOINT_HEADERS_JSON']:
    os.environ.pop(key, None)
os.environ.update(HEADROOM_OFFLINE='0', HEADROOM_NO_TELEMETRY='1', HEADROOM_SKIP_UPSTREAM_CHECK='1', HEADROOM_REQUIRE_RUST_CORE='false', HEADROOM_HTTP2='false', HEADROOM_DETECT_BACKEND='python', HEADROOM_THINKING_COMPACT='1', HEADROOM_THINKING_COMPACT_KEEP_LAST='0', HEADROOM_KOMPRESS_ENDPOINT_PATH='/compress', NO_PROXY='127.0.0.1,localhost')
sys.path.insert(0, str(Path.cwd()))
import httpx
import uvicorn
from headroom.proxy.server import ProxyConfig, create_app
from headroom.transforms.compression_units import find_content_router

seen = {'remote_calls': 0, 'upstream': []}
class Fixture(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass
    def do_POST(self):
        body=json.loads(self.rfile.read(int(self.headers['content-length'])))
        if self.server.remote:
            seen['remote_calls']+=1
            result={'compressed':'concise reasoning', 'original_tokens':300, 'compressed_tokens':2}
        else:
            seen['upstream'].append(body)
            result={'id':'fixture','object':'chat.completion','model':body['model'],'choices':[{'index':0,'message':{'role':'assistant','content':'ok'},'finish_reason':'stop'}],'usage':{'prompt_tokens':300,'completion_tokens':1,'total_tokens':301}}
        data=json.dumps(result).encode();self.send_response(200);self.send_header('content-type','application/json');self.send_header('content-length',str(len(data)));self.end_headers();self.wfile.write(data)

upstream=ThreadingHTTPServer(('127.0.0.1',0),Fixture);upstream.remote=False
remote=ThreadingHTTPServer(('127.0.0.1',0),Fixture);remote.remote=True
for fixture in [upstream,remote]:threading.Thread(target=fixture.serve_forever,daemon=True).start()
os.environ['HEADROOM_KOMPRESS_ENDPOINT']='http://127.0.0.1:'+str(remote.server_port)
app=create_app(ProxyConfig(optimize=True, disable_kompress=disabled, openai_api_url='http://127.0.0.1:'+str(upstream.server_port), cache_enabled=False,rate_limit_enabled=False,cost_tracking_enabled=False,log_requests=False,ccr_inject_tool=False,ccr_handle_responses=False,ccr_context_tracking=False,image_optimize=False))
listener=socket.socket();listener.bind(('127.0.0.1',0));listener.listen(128)
port=listener.getsockname()[1]
server=uvicorn.Server(uvicorn.Config(app,log_level='error',lifespan='on'))
thread=threading.Thread(target=server.run,kwargs={'sockets':[listener]},daemon=True);thread.start()
reasoning=' '.join('reason'+str(i) for i in range(100))
try:
    deadline=time.monotonic()+30
    while not server.started and thread.is_alive() and time.monotonic()<deadline:time.sleep(.02)
    assert server.started,'proxy failed to start'
    with httpx.Client(trust_env=False,timeout=30) as client:
        response=client.post('http://127.0.0.1:'+str(port)+'/v1/chat/completions',headers={'authorization':'Bearer local-fixture'},json={'model':'kimi-k2.7','messages':[{'role':'user','content':'question'},{'role':'assistant','content':'answer','reasoning_content':reasoning},{'role':'user','content':'continue'}]})
    assert response.status_code==200,(response.status_code,response.text)
    assert len(seen['upstream'])==1
    forwarded=seen['upstream'][0]['messages'][1].get('reasoning_content')
    router=find_content_router(app.state.proxy.openai_pipeline)
    result={'disabled':disabled,'status':response.status_code,'upstream_calls':len(seen['upstream']),'remote_calls':seen['remote_calls'],'remote_constructed':getattr(router,'_kompress_remote',None) is not None,'local_constructed':router._kompress is not None,'reasoning_preserved':forwarded==reasoning}
    print('RUNTIME_RESULT '+json.dumps(result),flush=True)
    if disabled:
        assert seen['remote_calls']==0 and not result['remote_constructed'] and not result['local_constructed']
        assert result['reasoning_preserved']
    else:
        assert seen['remote_calls']>0 and result['remote_constructed'] and not result['reasoning_preserved']
finally:
    server.should_exit=True;thread.join(10)
    upstream.shutdown();remote.shutdown();upstream.server_close();remote.server_close()

```
</details>

Exact-head hosted qualification is handled by maintainers; approval
remains pending that result. No contributor CI action or merge
requested.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-06 08:43:44 -06:00
AKT99!andJerrettDavis f309244a77 feat: add --disable-kompress-fallback to restore legacy PASSTHROUGH fallback (#1185)
## Description

Follow-up to #1046. That PR stopped `--disable-kompress` from forcing
`fallback_strategy = CompressionStrategy.PASSTHROUGH`, so
ContentRouter's rule-based
passes keep running when the ML model is off. As noted in review, that
is a behaviour
change for callers who relied on the old passthrough-everything
fallback.

This adds an opt-in `--disable-kompress-fallback` flag (env
`HEADROOM_DISABLE_KOMPRESS_FALLBACK`) that, together with
`--disable-kompress`, restores
the previous behaviour by routing fall-through content to `PASSTHROUGH`.
It defaults to
off, so the corrected behaviour from #1046 is unchanged unless a caller
explicitly opts
back in. The flag is a no-op unless `--disable-kompress` is also set.

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/proxy/models.py`: added `disable_kompress_fallback: bool =
False` to `ProxyConfig`.
- `headroom/proxy/server.py`: when `disable_kompress` and
`disable_kompress_fallback` are both set, restore
`router_config.fallback_strategy = CompressionStrategy.PASSTHROUGH`
(re-adding the `CompressionStrategy` import); wired the new field
through the env factory, the `__main__` argparse path
(`--disable-kompress-fallback`), and the `/health` config payload.
- `headroom/cli/proxy.py`: added the `--disable-kompress-fallback` Click
option (with `HEADROOM_DISABLE_KOMPRESS_FALLBACK` envvar) and passed it
into `ProxyConfig`.
- `tests/test_proxy_disable_kompress.py`: added tests for the flag
restoring `PASSTHROUGH`, for it being a no-op without
`--disable-kompress`, and for the `/health` config payload exposing the
field.
- `tests/test_cli_proxy_env.py`: added a test that the env factory
honours `HEADROOM_DISABLE_KOMPRESS_FALLBACK`.

## Testing

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

### Test Output

```text
$ pytest tests/test_proxy_disable_kompress.py -v
collected 5 items

tests/test_proxy_disable_kompress.py::test_disable_kompress_config_keeps_optimization_but_disables_ml_fallback PASSED [ 20%]
tests/test_proxy_disable_kompress.py::test_disable_kompress_defaults_to_existing_kompress_behavior PASSED [ 40%]
tests/test_proxy_disable_kompress.py::test_health_config_reports_disable_kompress_fallback PASSED [ 60%]
tests/test_proxy_disable_kompress.py::test_disable_kompress_fallback_restores_passthrough PASSED [ 80%]
tests/test_proxy_disable_kompress.py::test_disable_kompress_fallback_without_disable_kompress_is_noop PASSED [100%]

5 passed

$ ruff check headroom/proxy/server.py headroom/proxy/models.py headroom/cli/proxy.py tests/
All checks passed!
```

## Real Behavior Proof

- Environment: local clone, Python 3.13.7 venv, headroom core deps +
fastapi/uvicorn/httpx[http2].
- Exact command / steps: booted the app in-process with FastAPI
`TestClient` across four flag combinations and inspected both the live
`ContentRouter` config and the `/health` config payload.
- Observed result: both flags -> enable_kompress=False and
fallback_strategy=PASSTHROUGH (/health reports
disable_kompress_fallback=true); --disable-kompress alone ->
fallback_strategy stays KOMPRESS (the #1046 default, /health reports
false); --disable-kompress-fallback alone -> no-op
(enable_kompress=True, KOMPRESS); neither flag -> defaults
(enable_kompress=True, KOMPRESS).
- Not tested: full live-proxy `/stats` run against a real LLM backend.

## 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
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] 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
- [ ] I have updated the CHANGELOG.md if applicable

## Additional Notes

The flag is intentionally a no-op unless `--disable-kompress` is also
set, mirroring where
the original override lived. Happy to add a short note to the
docs/README flag list if you'd
like it documented there.

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-06-22 22:51:55 -05:00
AKT99! 64ca95361a fix: --disable-kompress should not override fallback_strategy to PASSTHROUGH (#1046)
## Description

`--disable-kompress` correctly disabled the ML model via
`enable_kompress = False`, but it
also forced `router_config.fallback_strategy =
CompressionStrategy.PASSTHROUGH`. That
override suppressed ContentRouter's rule-based passes — including the
`exclude_tools` gate —
for content that falls through to the fallback, so
`HEADROOM_EXCLUDE_TOOLS` had no effect
when `--disable-kompress` was set. Removing the override leaves
`fallback_strategy` at its
default (`KOMPRESS`); ContentRouter keeps running its rule-based passes
and only Kompress
inference is disabled.

Closes #955

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

## Changes Made

- `headroom/proxy/server.py`: removed the
`router_config.fallback_strategy = CompressionStrategy.PASSTHROUGH` line
inside the `if config.disable_kompress:` block; `enable_kompress =
False` is kept.
- `headroom/proxy/server.py`: dropped the now-unused
`CompressionStrategy` import (it was only referenced by the removed
line).
- `tests/test_proxy_disable_kompress.py`: updated the assertion to
expect `fallback_strategy == CompressionStrategy.KOMPRESS` (the
default), matching the corrected behaviour.

## Testing

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

### Test Output

```text
$ pytest tests/test_proxy_disable_kompress.py -v
============================= test session starts ==============================
platform darwin -- Python 3.13.7, pytest-9.1.0, pluggy-1.6.0
rootdir: /.../headroom
configfile: pyproject.toml
plugins: anyio-4.14.0, asyncio-1.4.0
collected 2 items

tests/test_proxy_disable_kompress.py::test_disable_kompress_config_keeps_optimization_but_disables_ml_fallback PASSED [ 50%]
tests/test_proxy_disable_kompress.py::test_disable_kompress_defaults_to_existing_kompress_behavior PASSED [100%]

============================== 2 passed in 1.37s ==============================

$ ruff check headroom/proxy/server.py tests/test_proxy_disable_kompress.py
All checks passed!
```

## Real Behavior Proof

- Environment: local clone, Python 3.13.7 venv, headroom core deps +
fastapi/uvicorn/httpx.
- Exact command / steps: built the proxy router via
`create_app(ProxyConfig(optimize=True, ...))` with `disable_kompress`
set and inspected the resulting `ContentRouter` config; ran `pytest
tests/test_proxy_disable_kompress.py -v` and `ruff check` on the changed
files.
- Observed result: with `--disable-kompress`, `enable_kompress` is
`False` and `fallback_strategy` is `KOMPRESS` (the default) instead of
`PASSTHROUGH`; ContentRouter stays in the pipeline. Both config tests
pass and lint is clean.
- Not tested: full live-proxy `/stats` run against an LLM backend. The
issue reporter observed `router_content_router_activations` 0→22 and
exclude-tool hits 0→10 after this change (see #955).

## 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
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] 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
- [ ] I have updated the CHANGELOG.md if applicable

## Additional Notes

This removes the override line plus its now-unused import, and updates
the existing test that
asserted the old behaviour; no new test was added because the corrected
behaviour is covered
by that existing test. The live `/stats` reproduction is described in
#955.
2026-06-16 14:47:45 -05:00
kiyo-e 6d30054f82 Add option to disable Kompress fallback (#514)
## Summary
- add HEADROOM_DISABLE_KOMPRESS / --disable-kompress to disable only
Kompress ML fallback
- keep the proxy optimization pipeline enabled so structural compressors
can still run
- expose the setting in proxy health output and direct env config path

## Tests
- uv run --with pytest --with fastapi --with click --with httpx --with
uvicorn pytest tests/test_cli_proxy_env.py
tests/test_proxy_disable_kompress.py
- uv run --with ruff ruff check headroom/cli/proxy.py
headroom/proxy/models.py headroom/proxy/server.py
tests/test_cli_proxy_env.py tests/test_proxy_disable_kompress.py
- git diff --check

Reviewed by local agent before PR; no blocking findings.
2026-06-10 22:02:13 -05:00