mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 03:16:20 +08:00
feat/https-compose-caddy
3
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
40cd7e7503 |
fix(transforms): enforce role, mutable, and cache zone guards in batch compression (#4480) (#4494)
## Description Enforce role, mutable, cache zone, and user/assistant message protection guards in small-unit batch compression. Previously, `compress_unit_with_router` enforced these guards on individual units, but `build_compression_batches` and `compress_batch_with_router` bypassed them for batched small units, allowing protected messages (e.g., system, developer, unpermitted user/assistant, immutable, non-live cache zones) to be compressed when grouped. Closes #4480 ## 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 - Extracted `check_unit_protection(unit)` in `headroom/transforms/compression_units.py` to share early refusal checks between single-unit and batch paths. - Updated `build_compression_batches` in `headroom/transforms/compression_batches.py` to skip protected units, leaving them in `skipped` so callers process them through the single-unit path. - Updated `compress_batch_with_router` in `headroom/transforms/compression_batches.py` to refuse batches containing protected units, returning verbatim passthrough results with the corresponding refusal reasons and reason categories. - Added comprehensive regression tests in `tests/test_compression_batches.py` covering all 6 protection guard scenarios and verifying that permitted user and assistant messages can each be batched. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text ============================= test session starts ============================== platform linux -- Python 3.14.8, pytest-9.0.3, pluggy-1.6.0 collected 14 items tests/test_compression_batches.py::test_small_units_over_floor_form_one_batch PASSED [ 7%] tests/test_compression_batches.py::test_batch_compresses_entries_with_one_router_call PASSED [ 14%] tests/test_compression_batches.py::test_under_floor_tail_is_skipped_without_a_batch PASSED [ 21%] tests/test_compression_batches.py::test_sixteen_under_floor_entries_are_skipped_before_a_new_batch_starts PASSED [ 28%] tests/test_compression_batches.py::test_missing_batch_tags_passes_through_every_entry PASSED [ 35%] tests/test_compression_batches.py::test_many_small_entries_create_no_more_than_sixteen_per_batch PASSED [ 42%] tests/test_compression_batches.py::test_batch_keeps_structured_shell_output_without_a_ccr_marker PASSED [ 50%] tests/test_compression_batches.py::test_batch_preserves_ccr_markers_when_router_would_remove_them PASSED [ 57%] tests/test_compression_batches.py::test_batch_rejects_ccr_marker_moved_to_another_entry PASSED [ 64%] tests/test_compression_batches.py::test_batch_uses_utf8_bytes_for_cjk_small_units PASSED [ 71%] tests/test_compression_batches.py::test_batch_after_the_request_deadline_passes_through_without_routing PASSED [ 78%] tests/test_compression_batches.py::test_build_compression_batches_skips_protected_units PASSED [ 85%] tests/test_compression_batches.py::test_batch_refuses_protected_units_without_routing PASSED [ 92%] tests/test_compression_batches.py::test_batch_allows_permitted_user_and_assistant_units PASSED [100%] ======================== 14 passed, 1 warning in 0.38s ========================= ``` ## Real Behavior Proof - Environment: Ubuntu 24.04 x86_64, Python 3.14.8, real `headroom._core` Rust extension, ContentRouter and TiktokenCounter - Exact command / steps: Executed standalone probe script initializing `ContentRouter()` and `TiktokenCounter('gpt-4o')` with 2 small developer messages (`role="developer"`, 396 bytes total). Ran `build_compression_batches` and `compress_batch_with_router`. - Observed result: `build_compression_batches` returned `batches=0, skipped=2`. `compress_batch_with_router` returned `modified=False, reason="protected_system_message", reason_category="protected_role"` for both slots without altering text. ```text build_compression_batches (developer): batches = 0 skipped = 2 slot=(0, None) modified=False reason=protected_system_message category=protected_role slot=(1, None) modified=False reason=protected_system_message category=protected_role ``` - Not tested: Live external LLM API endpoints requiring network credentials. ## Runtime Rollout Safety - Rollout-managed feature(s): None - Minimum rollout channel: stable - Stable/default behavior changed: Protected units that are smaller than unit min_bytes will no longer be erroneously compressed when grouped into batches. - Kill switch / disable path: N/A - Unsafe override required: None - Qualification impact: None - Rollback path: Revert this PR ## 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) ## Additional Notes AI-assisted contribution: investigated, patched, and verified with Antigravity / Gemini. --------- Co-authored-by: pei711 <199601925+pei711@users.noreply.github.com> Co-authored-by: JD Davis <mxjerrett@gmail.com> |
||
|
|
4d27d024b0 |
fix(proxy): share one compression deadline across a Responses request (#3938)
## Description #3693 made `HEADROOM_COMPRESSION_DEADLINE_MS` bound a request instead of a block, but only inside `ContentRouter.apply()`. OpenAI Responses requests (Codex HTTP, the Codex WebSocket path, the Responses passthrough) never call `apply()`: the adapter compresses each text unit and each small-unit batch with its own `ContentRouter.compress()` call, several at a time on `_openai_responses_unit_executor()`. No deadline origin exists on that path, so every Kompress call starts a fresh 20s clock. A request with many tool outputs runs far past its compression timeout; the awaiter gives up and forwards it uncompressed while the worker keeps running inference, and that timeout debt quarantines compression for every other request until it finishes. This PR reuses #3693's mechanism on the Responses path: one deadline origin per request, bound as the router's per-request `kompress_deadline_started_at`, for every unit and batch, including the ones on the unit pool. Closes #3937 ## 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 - `_compress_openai_responses_payload_in_executor` stamps one origin per request (`_openai_responses_deadline_started_at`) before the job is queued, because the caller's `timeout` counts queue wait too, and passes it down through `_compress_openai_responses_payload` and `_compress_openai_responses_live_text_units_with_router`. `deadline_started_at` joins the existing list of optional keywords the TypeError retry drops, so a narrow compressor override keeps working. - The budget is `min(HEADROOM_COMPRESSION_DEADLINE_MS, 0.75 * timeout)`. With the defaults (20s, 30s) that is the 20s deadline unchanged. On the Codex WebSocket path, which awaits at most 5s, it is 3.75s; before, each Kompress call allowed itself 20s there. Kompress checks the deadline only at chunk boundaries, so the chunk in flight at expiry, the splice and the output serialization need the remaining 25%. Kompress measures `now - origin > deadline`, so the cap is expressed as a backdated origin and Kompress itself is unchanged. `HEADROOM_COMPRESSION_DEADLINE_MS=0` still disables the deadline (no origin). - `ContentRouter.share_request_deadline(started_at)` binds a fresh `_PerRequestRuntimeState(kompress_deadline_started_at=started_at)` in the current Context, the same state `apply()` binds, so `_try_ml_compressor` forwards the origin to Kompress unchanged. It returns `False` and binds nothing once the deadline has passed. - `compress_unit_with_router` and `compress_batch_with_router` take an optional `deadline_started_at` and call it before entering the router. A unit or batch that has not started by the deadline comes back unchanged with reason `deadline_exceeded` (new unit reason category `deadline`), without entering the router. Default `None` keeps every other caller as before. - The two unit-pool `submit` calls run each task in `contextvars.copy_context()`. Each task binds fresh state (a shared state object would race on the `_runtime_target_ratio` set/restore in `compress_unit_with_router`), and the copy keeps that binding from outliving the task on a long-lived pool thread. - Finished units are kept, no thread is interrupted, and the unit result cache and replay policy are untouched: the cache still stores exactly what was forwarded, including a unit passed through because of the deadline, so the next turn forwards the same bytes. - Tests: `test_openai_responses_units_share_one_kompress_deadline` (parallel fan-out, every Kompress call gets one non-`None` origin), `test_openai_responses_units_after_the_deadline_pass_through_unchanged` (finished unit kept, later units byte-identical, Kompress entered once), `test_openai_responses_deadline_budget_stays_inside_the_timeout` (cap and opt-out), `test_batch_after_the_request_deadline_passes_through_without_routing`. Three exact-kwargs assertions in `tests/test_proxy_openai.py` now also ignore `deadline_started_at`, the same way they already ignore `timing`. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed Unit tests: targeted files only (the new tests plus the existing suites for every module touched), not the whole suite. Lint and types: `ruff check`, `ruff format --check` and `mypy` on the changed files, not the whole tree. ### Test Output New behavioural tests with only the `headroom/` changes reverted (upstream `main` |
||
|
|
09c66ac212 |
fix(proxy): batch small Codex Responses tool outputs (#2239)
## Description Batches small Codex/OpenAI Responses tool-output units through the existing ContentRouter instead of skipping each unit individually below the 512-byte floor. This fixes sessions where many small tool outputs are collectively worth compressing, but no single output clears the per-unit threshold. The change keeps larger units on the existing independent compression path, preserves CCR retrieval markers and protected tags across the batch envelope, rejects structurally invalid batch output, and leaves under-floor tails as size-floor passthroughs. Fixes #2234 ## 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 `headroom/transforms/compression_batches.py` for bounded compatible-unit batching, batch envelope parsing, tag/CCR marker preservation, and per-entry result splitting. - Updated the OpenAI Responses compression adapter to batch small tool-output text slots while keeping larger units on the existing cached per-unit path. - Switched the unit size floor to UTF-8 bytes so CJK and other multibyte text are measured consistently with the byte threshold. - Added regression coverage for batching, CJK byte floors, CCR marker preservation, malformed batch rejection, array output parts, and under-floor tails. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check`) - [x] Type checking passes (`mypy`) - [x] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text $ uv run --with pytest --with fastapi --with httpx --with anyio --with uvicorn --with h2 pytest tests/test_compression_batches.py tests/test_compression_units.py tests/test_openai_responses_compression_units.py -q 47 passed, 1 warning $ uvx ruff==0.15.17 check headroom/proxy/handlers/openai.py headroom/transforms/compression_batches.py headroom/transforms/compression_units.py tests/test_compression_batches.py tests/test_compression_units.py tests/test_openai_responses_compression_units.py --output-format concise All checks passed! $ uvx ruff==0.15.17 format --check headroom/proxy/handlers/openai.py headroom/transforms/compression_batches.py headroom/transforms/compression_units.py tests/test_compression_batches.py tests/test_compression_units.py tests/test_openai_responses_compression_units.py 6 files already formatted $ uv run --with mypy mypy headroom/transforms/compression_batches.py Success: no issues found in 1 source file ``` ## Real Behavior Proof - Environment: Windows 11, Python 3.13.3, local checkout of this PR branch. - Exact command / steps: ran the focused batching/unit/OpenAI Responses test suites above, including cases where four individually-small tool outputs collectively exceed the shared floor and where output arrays contain multiple text parts plus non-text parts. - Observed result: small outputs are sent through one router call and applied back to their original slots; under-floor tails remain unmodified; non-text parts are preserved; CCR markers are retained or the entire batch is rejected if moved/corrupted. - Not tested: a live Codex Responses proxy session against an upstream model; full-suite collection was not run locally. ## 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 - [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 if applicable --------- Co-authored-by: JerrettDavis <mxjerrett@gmail.com> |