mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-25 03:56:10 +08:00
feat/https-compose-caddy
6
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
31d378b0e5 |
refactor(proxy): remove test-only and dead helpers from the handlers (#4117)
## Description This removes proxy handler helpers that production code never calls, and one test that always skipped. Behaviour does not change. Refs #4136 ## Type of Change - [ ] 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 - [x] Code refactoring (no functional changes) ## Changes Made - `headroom/proxy/handlers/openai.py`: removed `_compact_openai_tool_schema_value`. It had no callers anywhere. - `headroom/proxy/handlers/streaming.py`: - Removed `StreamingMixin._parse_sse_usage`, the 92-line single-chunk SSE usage parser. Production only calls `_parse_sse_usage_from_buffer`. - Removed `_sse_contains_error_event`, a 5-line wrapper over `_sse_event_outcome` that only `tests/test_route_advice.py` called. - `headroom/proxy/handlers/gemini.py`: removed `GeminiHandlerMixin._count_texts_offloaded`, which only tests called. `tests/test_tokenizer_count_offload.py:77` already asserts that no handler uses it. - Test changes: - `tests/test_proxy_cache_ttl_metrics.py`: the TTL-bucket test now drives `_parse_sse_usage_from_buffer`. - `tests/test_streaming_sse_malformed_events.py`: dropped the chunk-parser variants. The buffered-parser variants of the same cases stay. - `tests/test_route_advice.py`: carries the error-event helper locally, so its `_sse_event_outcome` coverage is unchanged. - `tests/test_tokenizer_count_offload.py`: calls `token_counting.count_texts_offloaded(proxy, ...)` directly, still on a real proxy and its worker thread. - `tests/test_codex_ws_compression_scheduler.py`: removed `test_codex_ws_emits_perf_log_with_cache_keys`, which called `pytest.skip` unconditionally ("Pending: full WS lifecycle harness"), along with the fixtures only it used. ## 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 $ uvx ruff@0.16.8 check headroom/proxy/handlers tests/test_codex_ws_compression_scheduler.py tests/test_tokenizer_count_offload.py tests/test_route_advice.py tests/test_streaming_sse_malformed_events.py tests/test_proxy_cache_ttl_metrics.py All checks passed! $ pytest -q tests/test_streaming_sse_malformed_events.py tests/test_proxy_cache_ttl_metrics.py tests/test_route_advice.py tests/test_tokenizer_count_offload.py tests/test_codex_ws_compression_scheduler.py tests/test_openai_responses_context_compaction.py tests/test_openai_responses_additional_tools.py tests/test_gemini_compression_offload.py tests/test_proxy_gemini_integration.py tests/test_proxy_gemini_native_integration.py 470 passed, 27 skipped in 24.13s ``` ## Real Behavior Proof - Environment: macOS, Python 3.12, repo venv, branch `cleanup/proxy-handlers-dead-helpers` @ |
||
|
|
0ad996a82e |
feat(proxy): route Gemini plugin traffic through native transforms (#2697)
## Description OpenCode-routed Gemini requests now reach the tagged gateway and use the shared transform pipeline used by direct Gemini requests. Unsafe caller-supplied destinations stop with 400 before a handler can connect to them. Previously, the transport preserved `x-headroom-base-url` and the upstream pathname, but route matching sent native `:streamGenerateContent` through a handler that did not accept the tagged base and skipped transforms. `handle_gemini_generate_content` already accepts an `upstream_base_url`, runs the OpenAI pipeline over converted `contents`, and handles streaming by URL shape. `handle_gemini_count_tokens` already accepts one too. This adds an opt-in capability on the route spec, checks the caller-supplied base with the shared upstream guard, and sends both direct and plugin-routed native streaming through the shared transform-capable handler. Native parts, incoming query parameters, and the SSE selector are preserved. Wire formats with no native handler keep the existing custom-base passthrough branch. Loopback and private destinations receive a 400 response unless the operator explicitly allowlists them. Closes #2602 ## 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 - `ProviderHandlerRoute` gains `supports_custom_base_url`, defaulting to `False` so every existing handler route keeps its current behavior - `GEMINI_HANDLER_ROUTES` opts in all three model endpoints: `:generateContent`, `:streamGenerateContent`, and `:countTokens`. Counting has to follow the same upstream as generating, or the client gets counts from a host that is not serving the request - `_register_provider_handler_route` reads `x-headroom-base-url` and forwards it as `upstream_base_url` for routes that opted in - The route validates each custom base with the shared upstream guard before handler dispatch, rejecting unsafe destinations unless an operator allowlist permits them - `handle_gemini_stream_generate_content` delegates unconditionally to `handle_gemini_generate_content`, which runs the transform pipeline and builds the SSE URL from the request path for both direct and plugin-routed traffic - regressions for direct and plugin production-composed routes, mixed native parts, raw query preservation with one `alt=sse`, and adjacent paths that stay on passthrough ## 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 `uv run pytest tests/test_proxy/test_gemini_plugin_routed_streaming.py tests/test_provider_proxy_routes.py tests/test_provider_route_specs.py tests/test_tokenizer_count_offload.py -q` ```text 62 passed ``` `uv run ruff check . && uv run ruff format . --check` ```text All checks passed! 1600 files already formatted ``` ## Real Behavior Proof - Environment: Windows 11, Python 3.13.13, no live Google credentials; production `create_app` routes use fake upstream callbacks - Exact command / steps: `uv run pytest tests/test_proxy/test_gemini_plugin_routed_streaming.py tests/test_provider_proxy_routes.py tests/test_provider_route_specs.py tests/test_tokenizer_count_offload.py -q` - Observed result: direct and plugin-routed `:streamGenerateContent` requests reach the same transform pipeline, preserve native parts and query parameters, add one `alt=sse`, and strip `x-headroom-*` headers. All three native Gemini routes reject loopback when the allowlist is unset without calling their handlers; an explicitly allowlisted fake gateway still reaches the handlers. `:countTokens` follows the tagged upstream, and adjacent custom-base routes remain passthrough. - Not tested: live Google endpoint ## Runtime Rollout Safety - Rollout-managed feature(s): None; upstream validation applies to every opted-in Gemini request - Minimum rollout channel: Standard proxy release containing this change - Stable/default behavior changed: Native Gemini routes reject loopback and private custom bases by default; public gateways and explicitly allowlisted destinations continue to work - Kill switch / disable path: No runtime kill switch; `HEADROOM_ALLOWED_BASE_URLS` allows an operator to approve a private gateway - Unsafe override required: Only when a private deployment gateway must be used - Qualification impact: None - Rollback path: Revert this change; the prior route behavior returns ## 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 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) Not applicable; this change has no rendered UI. ## Additional Notes Scope note: this covers Gemini's three model endpoints, including direct and plugin-routed `:streamGenerateContent`. Gemini's other routes still use `generativelanguage.googleapis.com` regardless of the tag. Batch routes need handler support for a custom upstream; model listing and passthrough routes use a different registrar. `cachedContents` stays separate because a tagged client could create a cache entry at Google and reference it from a `:generateContent` request sent to a gateway. A follow-up can cover those routes. The tokenizer and pricing entries the issue also asks for, and adapters for other non-Anthropic/non-OpenAI wire formats, are not here. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/2697" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> --------- Co-authored-by: JD Davis <mxjerrett@gmail.com> |
||
|
|
be2b205c51 |
fix(proxy): quarantine compression only once half the pool is stuck (#3932)
## Description The timeout-debt quarantine in `HeadroomProxy._run_compression_in_executor` refused every new compression call while even one timed-out worker was still running. On an auto-sized pool (one worker per CPU, 8 on a typical laptop) a single straggler forwarded every other request uncompressed for up to the 60s cap while 7 of 8 workers sat idle. A common trigger is the cold-start fast pass missing its deliberately short 10s fail-open budget. The quarantine exists so timed-out work cannot saturate the executor (#2292, #2360). That risk starts near saturation, not at the first straggler, so the check now engages only once timed-out workers hold half the pool (`max(1, max_workers // 2)`). Pools of 1-3 workers keep today's behaviour. Closes #3931 Related, not closed by this PR: #3711 (what makes one Kompress stage overrun its budget; this PR narrows how far one overrun spreads, not the overrun itself) and #3653 (thread/fd reclamation for stuck workers; see Additional Notes for why this change does not add to it). ## 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`: new `_compression_quarantine_threshold`, defaulting to `max(1, compression_max_workers // 2)` and overridable with `HEADROOM_COMPRESSION_QUARANTINE_THRESHOLD` (read with the existing `_get_env_int`, `min_value=1`; `=1` restores the old any-straggler behaviour). - The quarantine check and its 60s time-cap release both key on `timed_out_in_flight >= threshold` instead of `> 0`. The cap is still re-armed on every fresh timeout, as before. - `quarantine_activations_total` (and the `activated` Prometheus event and warning) now fire on the transition into the quarantined state, i.e. when debt reaches the threshold, or when a fresh timeout re-arms it after the time cap released it. Previously a re-arm after a release while debt still stood was not counted. - "Quarantine cleared" is logged when debt drops back below the threshold, with the number of timed-out workers still running. - `/health` `runtime.compression_executor.quarantine_active` now reports the condition the check enforces (debt at or above the threshold and the cap not lapsed). It used to report `timed_out_workers > 0`, which was already wrong after a time-cap release. - Tests: `test_quarantine_waits_for_half_the_pool_to_be_stuck` (8-worker pool: 1 and 3 stuck still compress, 4 stuck refuses, `/health` matches, re-arm after release counts as a second activation) and `test_quarantine_threshold_is_half_the_pool_unless_overridden` (default sizing and the env override). Two tests in `tests/test_tokenizer_count_offload.py` that forced a quarantine with a debt of 1 on an auto-sized pool now set the debt to the threshold. ## Testing - [x] Unit tests pass (`pytest`) - targeted files only, listed below; the full suite was not run - [x] Linting passes (`ruff check .`) - on the changed files, plus `ruff format --check` - [x] Type checking passes (`mypy headroom`) - `mypy headroom/proxy/server.py` - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output Before the fix (new tests against unmodified `server.py`; the two tokenizer tests fail only because they read the new attribute): ```text $ python -m pytest tests/test_proxy_compression_executor.py tests/test_tokenizer_count_offload.py -q -p no:cacheprovider FAILED tests/test_proxy_compression_executor.py::test_quarantine_waits_for_half_the_pool_to_be_stuck FAILED tests/test_proxy_compression_executor.py::test_quarantine_threshold_is_half_the_pool_unless_overridden[8-None-4] FAILED tests/test_proxy_compression_executor.py::test_quarantine_threshold_is_half_the_pool_unless_overridden[3-None-1] FAILED tests/test_proxy_compression_executor.py::test_quarantine_threshold_is_half_the_pool_unless_overridden[1-None-1] FAILED tests/test_proxy_compression_executor.py::test_quarantine_threshold_is_half_the_pool_unless_overridden[8-1-1] FAILED tests/test_proxy_compression_executor.py::test_quarantine_threshold_is_half_the_pool_unless_overridden[8-0-4] FAILED tests/test_tokenizer_count_offload.py::test_count_tokens_offloaded_fails_open_on_executor_quarantine FAILED tests/test_tokenizer_count_offload.py::test_count_tokens_offloaded_returns_count_text_capable_tokenizer =================== 8 failed, 20 passed, 1 warning in 20.73s =================== ``` The behavioural failure on main is: ```text tests/test_proxy_compression_executor.py:336: in test_quarantine_waits_for_half_the_pool_to_be_stuck E headroom.proxy.server.CompressionQuarantinedError: compression quarantined: 1 timed-out worker(s) still running ``` After the fix: ```text $ python -m pytest tests/test_proxy_compression_executor.py tests/test_tokenizer_count_offload.py tests/test_platform_stabilization_functional.py tests/test_prometheus_obs_counters.py -q -p no:cacheprovider ======================== 51 passed, 1 warning in 28.02s ======================== $ ruff check headroom/proxy/server.py tests/test_proxy_compression_executor.py tests/test_tokenizer_count_offload.py All checks passed! $ ruff format --check headroom/proxy/server.py tests/test_proxy_compression_executor.py tests/test_tokenizer_count_offload.py 3 files already formatted $ mypy headroom/proxy/server.py Success: no issues found in 1 source file ``` ## Real Behavior Proof - Environment: macOS arm64, Python 3.11, upstream main `d5318ac2` (before) and the same commit plus this branch (after). Proxy booted through `headroom.proxy.server.run_server(ProxyConfig(port=..., compression_max_workers=8, disable_kompress=True, cache_enabled=False, rate_limit_enabled=False, log_requests=False))`, which is what `headroom proxy` calls after argument parsing (the local venv lacked the `mcp`/`magika`/`onnxruntime` extras that the CLI's dependency preflight requires). Env: `HEADROOM_SKIP_UPSTREAM_CHECK=1 HEADROOM_COMPRESSION_TIMEOUT_SECONDS=3 HEADROOM_TELEMETRY=off`, a fresh `HEADROOM_WORKSPACE_DIR` per run. - Exact command / steps: over HTTP, one warm-up `/v1/compress` (200-row JSON `tool_result`, 10,623 tokens), one oversized `/v1/compress` (40,000 rows, about 22s of work against the 3s budget, so its worker keeps running after the request fails open), then three small `/v1/compress` calls while that worker is still running, reading `/health` `runtime.compression_executor` in between. A second run fires four oversized calls concurrently to strand 4 of 8 workers, sends a small call, waits until one stuck worker exits, and sends another. - Observed result: on main one straggler refuses every following request; on this branch the other 7 workers keep compressing, and half the pool stuck still quarantines and clears again (output below). Before (main), one straggler refuses everything: ```text health after big timed out: {'max_workers': 8, 'running': 1, 'timed_out_workers': 1, 'quarantine_active': True, 'quarantine_activations_total': 1, 'quarantine_skips_total': 0} small request 1: 0.02s tokens_before=0 tokens_saved=0 skipped=True reason=compression_timeout small request 2: 0.01s tokens_before=0 tokens_saved=0 skipped=True reason=compression_timeout small request 3: 0.01s tokens_before=0 tokens_saved=0 skipped=True reason=compression_timeout health after small requests: {'max_workers': 8, 'running': 1, 'timed_out_workers': 1, 'quarantine_active': True, 'quarantine_activations_total': 1, 'quarantine_skips_total': 3} ``` After, the same straggler leaves the other 7 workers serving: ```text health after big timed out: {'max_workers': 8, 'running': 1, 'timed_out_workers': 1, 'quarantine_active': False, 'quarantine_activations_total': 0, 'quarantine_skips_total': 0} small request 1: 0.12s tokens_before=10623 tokens_saved=4411 skipped=False reason=None small request 2: 0.12s tokens_before=10623 tokens_saved=4411 skipped=False reason=None small request 3: 0.18s tokens_before=10623 tokens_saved=4411 skipped=False reason=None health after small requests: {'max_workers': 8, 'running': 1, 'timed_out_workers': 1, 'quarantine_active': False, 'quarantine_activations_total': 0, 'quarantine_skips_total': 0} ``` After, half the pool stuck still quarantines, and it clears when debt drops below half: ```text health after 4 concurrent big requests timed out: {'max_workers': 8, 'running': 4, 'timed_out_workers': 4, 'quarantine_active': True, 'quarantine_activations_total': 1, 'quarantine_skips_total': 0} small request while 4 of 8 stuck: 0.10s tokens_before=0 tokens_saved=0 skipped=True reason=compression_timeout health once a stuck worker exited: {'max_workers': 8, 'running': 3, 'timed_out_workers': 3, 'quarantine_active': False, 'quarantine_activations_total': 1, 'quarantine_skips_total': 1} small request with 3 stuck: 0.19s tokens_before=10623 tokens_saved=4411 skipped=False reason=None ``` ```text WARNING - Compression worker exceeded its request deadline and is still running; new compression is quarantined until fewer than 4 timed-out workers remain INFO - Compression quarantine cleared; 3 timed-out worker(s) still running ``` - Not tested: the `headroom proxy` CLI entry point itself (booted via `run_server`, see Environment); the `/v1/messages`, `/v1/responses` and Codex WS paths end to end (they share the same `_run_compression_in_executor`, but I only drove `/v1/compress`); Windows and Linux (the field evidence covers them, my repro does not); the 60s time-cap release over HTTP (covered by `test_compression_quarantine_releases_after_time_cap` and the new re-arm assertion, not by a live run); a long soak sampling OS thread and fd counts. ## Runtime Rollout Safety - Rollout-managed feature(s): none. The quarantine is not in `rollout.py` FEATURES. - Minimum rollout channel: n/a (applies on every channel). - Stable/default behavior changed: yes. On pools of 4 or more workers, compression keeps running while fewer than half the workers are held by timed-out jobs; previously the first timed-out job refused all compression for up to 60s. Pools of 1-3 workers are unchanged. - Kill switch / disable path: `HEADROOM_COMPRESSION_QUARANTINE_THRESHOLD=1` restores the previous behaviour on any pool size. - Unsafe override required: no. - Qualification impact: more requests get compressed while a straggler runs, so `tokens_saved` rises and the `skipped` quarantine counter falls on affected installs; no change to what compression does to a request it runs on, and no change to provider cache behaviour beyond the requests that are now compressed instead of forwarded raw. - Rollback path: set `HEADROOM_COMPRESSION_QUARANTINE_THRESHOLD=1`, or revert this commit. ## 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 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 Pool capacity and #3653. The compression executor is a `ThreadPoolExecutor` with a fixed `max_workers`; it never creates threads beyond that cap, and a stuck worker keeps the thread it already holds. Admitting work while a straggler runs only puts that work on the pool's idle threads, which finish and release their resources normally, so this change cannot raise the process's thread count above `max_workers` or add a leaked thread/fd per quarantine event. What it does change is how many timed-out jobs can stand before new work is refused: up to `threshold - 1` (3 on an 8-worker pool) instead of 0. That bound is no looser than today's in practice: the old rule never prevented requests that were already admitted from timing out together (it only refuses calls that arrive after a timeout is recorded), and the 60s cap already lets work back in while debt stands. At `threshold` stuck workers the quarantine engages exactly as before, so at least half the pool stays free for work that is not stuck. Field evidence that motivated this (Headroom Desktop fleet canary, 2026-09-21 to 2026-09-23): 9 hosts on macOS, Windows and Linux had between 2.1% and 38.9% of requests refused compression by the quarantine. On one machine's proxy logs, 211 of 262 refusals happened with ONE stuck worker and none with more than 3 of 8 stuck; on 0.37.0 that machine forwarded 42 of 180 requests (23%) uncompressed in a day while `/health` showed `max_workers` 8, `queued_max` 1 and `queue_wait_seconds_max` 0.23, i.e. an idle pool. Headroom Desktop has shipped an equivalent downstream patch (standing the quarantine down below half the pool) since 2026-09-23 (desktop 0.9.22-rc.1); this PR implements it in the check itself so it can be dropped there. Documentation: `HEADROOM_COMPRESSION_QUARANTINE_THRESHOLD` follows the existing undocumented `HEADROOM_COMPRESSION_QUARANTINE_MAX_SECONDS`, so no docs page was updated; happy to add both to the proxy env reference if wanted. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3932" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: JD Davis <mxjerrett@gmail.com> |
||
|
|
039cd2431a |
fix(proxy): preserve merged session and quarantine contracts (#2943)
## Description Forward-fixes two integration contracts exposed while auditing the large August 12 merge batch on `main`. The Codex WebSocket request-ID hardening correctly gave every emitted dashboard/feed row a unique ID, but it also changed the human-readable `PERF` prefix from the stable WebSocket session ID to that per-emission ID. That broke operator correlation and the contract documented by the original merge. This PR separates storage identity from log correlation: rows remain unique, while `PERF` lines remain grouped under the session ID. The same audit found two tokenizer quarantine tests still modeling the pre-time-cap behavior. Timeout debt no longer activates quarantine after its deadline expires. The tests now establish a live deadline and therefore continue to exercise the intended fail-open branch without weakening the production guard. ## Changes - Add an optional `RequestOutcome.perf_request_id` correlation field, defaulting to the existing `request_id` behavior for all current callers. - Set that field to the stable session ID for both per-turn and residual Codex WebSocket emissions. - Strengthen the lifecycle regression test to prove the unique feed-row ID is not used as the `PERF` prefix. - Update tokenizer quarantine tests to model an active, time-capped quarantine. This is a forward fix; it does not revert the unique WebSocket request IDs or the time-capped quarantine behavior. ## Merge-batch audit context - Audited 48 squash merges from `12149f74466c08b69be8d5fe751425be63c2fda4` through `941c25d31e6c6e0b436c307cbe212771ff76b45f`. - Reviewed repeated-touch hotspots in the OpenAI/Anthropic handlers and proxy server. - Confirmed the batch has no deleted or renamed paths and no revert/supersession commits. - Reproduced the deterministic failures on the merged head and confirmed the corresponding pre-batch tokenizer tests passed; the new WebSocket assertion was introduced by the batch and exposed the dropped correlation contract. ## Validation - `ruff check` — passed - `ruff format --check` — passed - `mypy headroom` — passed (517 source files) - Focused proxy/outcome/tokenizer suite — 99 passed - CI-equivalent Python suite in four `pytest-split` shards — 10,797 passed, 603 skipped - `cargo fmt --all -- --check` — passed - `cargo clippy --workspace -- -D warnings` — passed - New beta-sticky integration suite — 9 passed - Simulator-backed proxy E2E — 7 passed - Real local Headroom process against a real local FastAPI upstream: - `/livez` healthy - `/readyz` ready (Kompress correctly optional/degraded in minimal passthrough mode) - OpenAI `/v1/chat/completions` round trip passed - Anthropic `/v1/messages` round trip passed - Local `act` exercised the push workflow's change-detection job and entered the real lint job. `act` required local no-op cache/setup shims because its runner action post-hooks/pip pairing are incompatible with this macOS Docker environment; the actual Ruff/mypy validations above were run natively and passed. ## Risk Low. The new field is optional and preserves existing behavior by default. Only Codex WebSocket outcome emitters opt into a separate log correlation ID; dashboard/feed row identity remains unchanged. --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
806d2e468a |
fix(proxy): offload OpenAI and Gemini tokenizer counting off the event loop (#2498)
## Description The OpenAI and Gemini handlers resolved the tokenizer and counted the conversation inline on the event loop. When a model resolves to a HuggingFace tokenizer (the registry routes qwen, deepseek, llama, phi, falcon, and more there) a cold cache runs `AutoTokenizer.from_pretrained` behind a 10s `thread.join`, which freezes the whole server. That is the GH #1701 stall, now reachable from OpenAI and Gemini because `/v1/chat/completions` and `/v1/responses` are documented multi-provider passthroughs and receive those models. Anthropic already routed the same call through a fail-open `_count_tokens_offloaded` helper. This hoists that helper to the shared `HeadroomProxy` base and sends the OpenAI and Gemini sites through it too. No linked issue. This is the OpenAI and Gemini follow-on to #1738, which offloaded the Anthropic and batch paths. GH #1701 is the original freeze report. ## 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 - Hoisted `_count_tokens_offloaded` from `AnthropicHandlerMixin` to the shared `HeadroomProxy` base, next to `_run_compression_in_executor`. It resolves and counts on the bounded compression executor and fails open to estimation on timeout, error, or executor quarantine. - Routed 6 inline sites through it: `handle_openai_chat`, `handle_openai_responses`, `handle_gemini_generate_content`, `handle_google_cloudcode_stream`, `handle_gemini_count_tokens`, and `handle_gemini_stream_generate_content` (resolve only, keeps its per-part `count_text` loop). - Removed 6 now-dead local `get_tokenizer` imports. - Left batch's per-line counts inline on purpose. They run on an already-warm tokenizer, so offloading them adds executor churn without touching the cold load. Batch's `pipeline.apply` was already offloaded in #1738. - Extended the wiring guard to all 7 provider handlers, added a quarantine fail-open test and a `count_text` fail-open test, and stubbed the method on 2 mixin-only handler doubles. ## 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 $ ruff check headroom/proxy/server.py headroom/proxy/handlers/{anthropic,openai,gemini}.py tests/test_tokenizer_count_offload.py All checks passed! $ pytest tests/test_tokenizer_count_offload.py 6 passed in 4.39s # offload suite + all 26 handler-calling test files + handler-helpers/batch/tokenizers $ pytest tests/test_tokenizer_count_offload.py tests/test_openai_codex_routing.py tests/test_gemini_nonjson_status.py ... tests/test_tokenizers.py 377 passed, 15 skipped, 15 warnings in 86.60s (0:01:26) ``` ## Real Behavior Proof - Environment: macOS (Darwin), Python 3.13, proxy built from this branch. A synthetic tokenizer that sleeps 0.5s on resolve+count stands in for a cold HuggingFace `from_pretrained` load, with a 10ms asyncio loop-canary running alongside. - Exact command / steps: monkeypatch `headroom.tokenizers.get_tokenizer` to the 0.5s-sleeping tokenizer, then time a concurrent canary across two counts, the offloaded `await proxy._count_tokens_offloaded("qwen2.5-coder", messages)` and the old inline `get_tokenizer(model).count_messages(messages)`. - Observed result: the offloaded path kept the loop live at 41 canary ticks during the 509ms count, the inline path froze it to 0 ticks over 502ms, and both returned the same token count. Full run was 377 passed, 15 skipped, 0 failed. The new quarantine test confirms an unrelated compression timeout downgrades counting to estimation instead of raising a 500. - Not tested: live HuggingFace downloads and real qwen/deepseek traffic. No API keys in this environment, so the Gemini and OpenAI integration tests skip on `GEMINI_API_KEY`/`OPENAI_API_KEY`. `mypy headroom` did not finish locally (cold-times-out past 10 minutes on this box), so type-checking is left to CI. ## 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 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 - No linked issue. Follow-on to #1738. - Batch per-line counts stay inline: they run on an already-warm tokenizer, so offloading them adds executor churn without addressing the cold load. - Found a 6th site mid-implementation. `handle_gemini_stream_generate_content` also resolved the tokenizer inline but counts via a `count_text` loop, so it takes the resolve-only path. Verified `EstimatingTokenCounter.count_text` exists, so its fail-open branch does not crash. - `mypy headroom` cold-times-out locally (server.py pulls the full graph). Deferred to CI's Linux shards, same as prior PRs on this file. `ruff` and `pytest` run clean. - Documentation checkbox left unchecked: this change ships no user-facing doc update. --------- Co-authored-by: JerrettDavis <mxjerrett@gmail.com> |
||
|
|
46d5d685d9 |
fix(proxy): bound HF tokenizer load and offload token counting off event loop (#1738)
## Description Fixes #1701. On Windows, `headroom proxy --anthropic-api-url https://api.deepseek.com/anthropic` froze: the first `/v1/messages` request took ~610s (`optimization_latency_ms=609972`) with only router/lifecycle markers, and afterwards the whole server was a zombie — `/livez`, `/readyz` and `/health` hung until the process was killed. `HEADROOM_DETECT_BACKEND=python` was already set, so this was not the #575/#845 native-detect deadlock. Root cause: DeepSeek model names route to the HuggingFace tokenizer backend (`MODEL_PATTERNS` in `headroom/tokenizers/registry.py`). `HuggingFaceTokenizer` loads lazily, so the registry's construction-time fallback never fires; the first `count_messages` calls `AutoTokenizer.from_pretrained(..., trust_remote_code=True)` — unbounded network downloads/retries — and this ran **synchronously inside the async Anthropic messages handler** (`get_tokenizer(model)` + `tokenizer.count_messages(messages)`), outside the 30s `_run_compression_in_executor` bound. huggingface_hub retry chains on a restricted network easily reach ~10 minutes, blocking the entire asyncio event loop; subsequent on-loop counting kept it pinned. tiktoken got a bounded eager load for the same bug class long ago (#956); the HF backend never did. ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Refactoring (no functional changes) ## Changes Made - `headroom/tokenizers/huggingface.py`: `_load_tokenizer` now tries the local HF cache first (`local_files_only=True`, no network), then bounds the network load with `HEADROOM_HF_TOKENIZER_LOAD_TIMEOUT_SECS` (default 10s; `0` disables network loads) on a daemon thread. Timeouts/failures return `None` (cached by `lru_cache`, so the hub is probed at most once per process per tokenizer) and `count_messages` fails open to char-based estimation via the existing `_use_fallback()` path. - `headroom/proxy/handlers/anthropic.py`: new `AnthropicHandlerMixin._count_tokens_offloaded(model, messages)` runs `get_tokenizer` + `count_messages` on the compression executor bounded by `COMPRESSION_TIMEOUT_SECONDS`, failing open to `EstimatingTokenCounter` (downgrade logged once per model). Used in `handle_anthropic_messages` (the issue's hot path, both count sites) and `handle_anthropic_batch_create`; the batch path's inline `anthropic_pipeline.apply()` is now offloaded via `_run_compression_in_executor` (mirrors the #1612 image-compression offload). - `headroom/proxy/handlers/batch.py`: the two remaining inline `openai_pipeline.apply()` calls (`handle_google_batch_create`, `_compress_batch_jsonl`) are offloaded the same way; existing `except` blocks keep the pass-through fail-open semantics. - Tests: `tests/test_huggingface_tokenizer_timeout.py` (cache-first, bounded timeout, failure caching, timeout=0, fail-open estimation), `tests/test_tokenizer_count_offload.py` (wiring guards, runs on `headroom-compress` worker, event loop stays responsive during slow tokenizer work, fail-open), plus `_run_compression_in_executor` stub on the batch test double. ## Testing - [x] All existing tests pass - [x] Added new tests for the changes - [ ] Manual testing performed ``` $ python -m pytest tests/test_huggingface_tokenizer_timeout.py tests/test_tokenizer_count_offload.py tests/test_image_compression_offload.py tests/test_gemini_compression_offload.py tests/test_tokenizers tests/test_proxy_handlers_batch.py -q 50 passed $ ruff check . # No issues found $ ruff format --check . # 1043 files already formatted $ mypy headroom --ignore-missing-imports # 0 errors ``` ## Real Behavior Proof - Environment: Windows 11 Pro (10.0.26200), Python 3.13, local checkout of this branch with the Rust core built. - Exact command / steps: `python -m pytest tests/test_tokenizer_count_offload.py -q` — includes `test_count_tokens_offloaded_keeps_loop_responsive`, which reproduces the issue's mechanism: a tokenizer whose `count_messages` blocks (stand-in for the unbounded `AutoTokenizer.from_pretrained` network load) while an asyncio ticker measures event-loop liveness. Also `python -m pytest tests/test_huggingface_tokenizer_timeout.py -q` with a `from_pretrained` stub that sleeps 60s and `HEADROOM_HF_TOKENIZER_LOAD_TIMEOUT_SECS=0.2`. - Observed result: with the fix, the slow count runs on a `headroom-compress` worker thread and the loop keeps ticking (`ticks >= 5`; inline it yields ~0 — the zombie). The 60s-hung HF load unblocks at the 0.2s timeout, falls back to estimation, and the second call returns instantly (failure cached, no re-probe). All 10 new tests pass. - Not tested: live reproduction against `api.deepseek.com` from a network where HF hub downloads stall (the reporter's exact environment); actual HF vocab download timing on a healthy network. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |