mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-26 04:26:14 +08:00
feat/https-compose-caddy
2
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ca6ba3486c |
fix(ccr): stream the buffered CCR upstream request so idle-killing networks cannot cut it (#4206)
## Description The buffered CCR path flips a streaming Claude Code turn to `stream: false` upstream so the proxy holds the whole reply before serving `headroom_retrieve`. With `stream: false`, Anthropic sends no byte until the generation is complete. A middlebox that drops HTTP connections idle for ~60s (TLS-inspecting antivirus, VPN, corporate proxy; TCP keepalive does not reset an HTTP-layer idle timer) closes the connection first: each attempt fails at ~60s with `Server disconnected without sending a response`, the client gets a 502 after ~186s, and Claude Code resends the same body forever. The CCR continuation that serves the retrieval (`anthropic_ccr_continuation`, its own `http_client.post`) is a second `stream: false` call and is cut the same way. Without Headroom the client streams and the same turns complete. This PR keeps the buffered design and makes only its upstream leg stream. The buffered request and every continuation built from it (CCR, memory, turn hook) go to first-party Anthropic as `stream: true`, and the event stream is folded back into the Message JSON the buffered path already reads, so retrieval, memory, turn hooks, usage accounting and SSE resynthesis see exactly what they saw before. Bytes (deltas and pings) now flow for the whole generation, so an idle timer never fires. The fold reuses `AnthropicSSEEnvelope`, the reconstruction #3130 and #3266 already use on this path. Closes #4205 ## 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/handlers/anthropic.py`: new `_send_buffered_as_stream(send, headers, body, *, url, request_id)`. It sends `{**body, "stream": true}` with `Accept: text/event-stream` (one Accept value, any casing replaced) and folds the reply: - not a 200 event stream (an HTTP error, or an upstream that answered JSON anyway): returned unchanged; - a whole stream: a 200 JSON response holding the folded Message; - an in-band `error` event: the event as the body, with its own HTTP status (529 `overloaded_error`, 429 `rate_limit_error`, other documented types to their status, else 500); - a stream that ended before `message_stop` or with a block open: the existing strict 502 `upstream_protocol_error` of `_adapt_event_stream_to_json` (#3266); - a complete stream holding a known event the fold cannot read (an unknown delta type): logged, and the original `stream: false` body is sent instead. One more generation, but never a 502 the client would resend forever. A connection dropped mid-stream raises inside `send`, exactly as for a `stream: false` reply. An in-band error arrives after upstream already answered 200, so `_retry_request` does not retry it; the client gets the status and retries as it would on a direct stream. - It is used at the four places Headroom sends a body it made non-streaming: the buffered CCR request (only when `buffered_stream_ccr`; a client's own `stream: false` request still goes through `_retry_request` with its original bytes), the CCR continuation (the `prepare_outbound_body_bytes` + `log_outbound_request` + `http_client.post` sequence moved into a local `_post_continuation`, unchanged otherwise, so a fallback attempt logs its own outbound line), the memory continuation and the turn-hook continuation. - Gates: the body is not already streaming, the upstream is first-party Anthropic (`is_custom_anthropic_base_url(url)` is false; the host-equality check tool-search gating already uses), and the kill switch `HEADROOM_BUFFERED_UPSTREAM_STREAM` is not `0`/`false`/`no`/`off`. Copilot and other gateways keep the `stream: false` request: the fold is checked against Anthropic's own stream, and a gateway dialect it cannot read would cost every turn a second generation. - `headroom/proxy/runtime_env.py`: `HEADROOM_BUFFERED_UPSTREAM_STREAM` is a registered knob in `RUNTIME_ENV_KNOBS`, read per request through `runtime_env.getenv`, so a reusing `headroom wrap` pushes it to the running proxy and `POST /admin/runtime-env` sets it with no restart. Listed in the `security-model.mdx` allowlist. - `headroom/proxy/anthropic_wire.py`: `fold_anthropic_stream(raw)` parses with `AnthropicSSEEnvelope.parse` and trims each block to the non-streaming Message shape: a null member leaves every block, `thinking` keeps `type`/`thinking`/`signature`, `redacted_thinking` keeps `type`/`data`. Claude Opus 5.5 streams a thinking `content_block_start` with `estimated_tokens: null`; the CCR continuation resends the folded turn as history, and Anthropic answers any block carrying that member with 400 `Extra inputs are not permitted`. - `headroom/proxy/anthropic_wire.py` `_response_from_events`: `message_delta.usage` is merged only where non-null, as the Anthropic SDK's `MessageStream` does. Before, a null count there overwrote the real `message_start` count (input and cache tokens) in the reconstructed message. - `headroom/proxy/buffered_ccr_response.py`: the status-to-error-type table moves out of `_anthropic_error_type` into `ANTHROPIC_ERROR_TYPES` so the handler can invert it; `_anthropic_error_type` returns the same values. - Unchanged on purpose: `body["stream"] = False` and its mutation reason `ccr_streaming_retrieve_buffered_non_stream` stay the buffered path's internal representation (every later step, the response-cache guard and the #3587 log counts key on them), and the `using buffered stream:false upstream request` log line keeps its text. - Tests: new `tests/test_buffered_ccr_upstream_stream.py` (16 tests): the fold equals the Anthropic Python SDK's `accumulate_event` result on a stream with thinking, signature, redacted thinking, text, citations, split `input_json_delta`, pings and a null usage count; stream-only members are dropped; truncated, in-band error and unknown-delta outcomes; the send helper's gates (kill switch, gateway URL, already streaming), passthrough of non-stream replies, 529 for an in-band overload, 502 for a truncated stream, the `stream: false` fallback; and through the handler, the buffered turn and its CCR continuation both go upstream `stream: true` with `Accept: text/event-stream` and the continuation's resent thinking block carries only its schema, while a client's own `stream: false` request goes out `stream: false` with `Accept: application/json` and its original bytes. - Existing tests that pinned `stream: false` on the wire for a buffered turn now pin `stream: true` (`test_anthropic_streaming_ccr_retrieve.py`, `test_ccr_buffered_stream_signed_thinking.py`, `test_proxy_response_cache_replay.py`, `test_no_ccr_disables_response_handling.py`). `test_anthropic_buffered_ccr_usage.py` now answers the buffered turn with an event stream, so usage booking is checked through the fold. `test_buffered_ccr_accept_header.py` (#3078) pins the `stream: false` leg it is about with the kill switch; custom upstreams such as Copilot always take that leg. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - ran on the 3 changed source files only, see below - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ pytest tests/test_buffered_ccr_upstream_stream.py -q 16 passed, 1 warning in 2.89s # every test file that touches the buffered CCR path, the CCR continuation or SSE reconstruction $ pytest tests/test_buffered_ccr_upstream_stream.py tests/test_sse_safeguards_passthrough.py \ tests/test_buffered_ccr_salvage.py tests/test_anthropic_buffered_ccr_usage.py \ tests/test_buffered_ccr_grace_window.py tests/test_anthropic_buffered_sse.py \ tests/test_ccr_buffered_stream_signed_thinking.py tests/test_toin_feedback.py \ tests/test_proxy_response_cache_replay.py tests/test_proxy/test_anthropic_buffered_timeout.py \ tests/test_anthropic_auto_mode_passthrough.py tests/test_proxy/test_openai_responses_ccr.py \ tests/test_sse_thinking_blocks.py tests/test_streaming_sse_malformed_events.py \ tests/test_route_advice.py tests/test_memory_tool_stream.py \ tests/test_proxy/test_anthropic_streaming_ccr_retrieve.py tests/test_proxy_byte_faithful_forwarding.py \ tests/test_buffered_ccr_accept_header.py tests/test_anthropic_buffered_memory_continuation.py \ tests/test_anthropic_ccr_workspace_unbound.py tests/test_no_ccr_disables_response_handling.py \ tests/test_proxy_ccr.py tests/test_ccr_inline_resolve_handlers.py \ tests/test_proxy/test_anthropic_ccr_raise.py tests/test_proxy/test_anthropic_ccr_deferred_injection.py \ tests/test_nonstream_sse_policy.py tests/test_ccr_response_handler_extra.py \ tests/test_compress_route_tokenizer_by_model.py -q 855 passed, 6 warnings in 57.94s # the updated assertions fail on main's source (they pin stream:true on the wire) $ git checkout upstream/main -- headroom/ && pytest tests/test_anthropic_buffered_ccr_usage.py \ tests/test_proxy/test_anthropic_streaming_ccr_retrieve.py tests/test_ccr_buffered_stream_signed_thinking.py \ tests/test_no_ccr_disables_response_handling.py tests/test_proxy_response_cache_replay.py -q --tb=no 12 failed, 33 passed, 1 warning in 13.64s # whole suite $ pytest tests -q 18 failed, 16435 passed, 583 skipped, 119 warnings in 1226.31s (0:20:26) # 16 of the 18 fail the same way on unmodified main in the same environment # (tests/test_proxy_uds.py x11, tests/test_cli/test_wrap_persistent.py x4, # tests/test_pricing_from_litellm.py groq/llama-guard-3-8b x1); the other 2 # (test_offline_egress_chokepoint.py::TestUpdateCheckOffline::test_explicit_update_check_never_constructs_request, # test_stateless_no_disk.py::test_cli_stateless_flag_exports_env_for_children) pass when run alone on this branch. $ ruff check . All checks passed! $ ruff format --check . 1790 files already formatted $ mypy headroom/proxy/anthropic_wire.py headroom/proxy/buffered_ccr_response.py headroom/proxy/handlers/anthropic.py Success: no issues found in 3 source files ``` ## Real Behavior Proof - Environment: macOS 27.0.1 arm64, Python 3.11.13. Upstream `main` |
||
|
|
139c7cbdde |
fix(ccr): send Accept: application/json on a buffered stream:false turn (#3102)
## Description Server-side CCR retrieval flips a `stream: true` turn to `stream: false` so the whole upstream reply is in hand before answering. The **body** was rewritten; the client's `Accept: text/event-stream` was **not**. The request that went on the wire therefore contradicted itself — *"answer as JSON"* in the body, *"I only accept SSE"* in the headers. Anthropic's first-party API tolerates that, which is why this never surfaced against it. GitHub Copilot's Anthropic-compatible gateway does not, and answers with a generic `api_error`. That is the reported shape exactly. An OpenCode session's **first** call succeeds — no marker exists yet, so nothing is buffered. The **second** call is the first to carry a redeemable `<<ccr:…>>` marker, so it is the first to be flipped to buffered, and it fails. The reporter's own logs show the correlation: every failed request carries `mutation_reasons=…,ccr_streaming_retrieve_buffered_non_stream`. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - `headroom/proxy/handlers/anthropic.py`: when the buffered CCR path flips `stream` to `false`, the outgoing `Accept` header is set to `application/json` to match. The lookup is case-insensitive and **replaces** the existing header rather than appending, so exactly one `Accept` goes upstream. - `headroom/proxy/handlers/openai.py`: the **same fix on the `/v1/responses` buffered path**, which has an identical `stream: false` flip with no matching `Accept`. This handler is a GitHub Copilot path — it calls `apply_copilot_api_auth` — so leaving it would have left the reported bug live on a route the reporter can hit. Found during self-review, not in the original diff. - Same treatment for the Anthropic CCR continuation request, which is non-streaming for the same reason and previously fixed only `Content-Type`. Its header strip is now case-insensitive for `Content-Type` as well, removing a latent duplicate-header path. - `tests/test_buffered_ccr_accept_header.py`: 6 tests — the buffered turn asks for JSON, exactly one `Accept` survives, mixed-case `Accept` is replaced, a client sending no `Accept` still gets one, a non-buffered streaming turn keeps `text/event-stream` untouched, and the OpenAI `/v1/responses` buffered turn asks for JSON too. ## Testing - [x] Unit tests pass (`pytest`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text tests/test_buffered_ccr_accept_header.py ...... [100%] 6 passed CCR-adjacent suites on this branch: tests/test_buffered_ccr_accept_header.py, test_buffered_ccr_salvage.py, test_buffered_ccr_grace_window.py, test_anthropic_streaming_ccr_retrieve.py, test_ccr_buffered_stream_signed_thinking.py 41 passed Full suite on this branch: 3 failed, 11216 passed, 581 skipped in 414.81s ``` The 3 failures are pre-existing and environmental, identical to a plain-`main` baseline run on the same machine: no `cargo` installed (`test_no_native_tls_in_wheel_build_tree`), no `codex` CLI (`test_learn/test_integration.py`), and `test_run_server_installs_cancelled_error_filter`, which fails under full-suite ordering on `main` too. ## Real Behavior Proof - Environment: macOS (darwin 25.4.0), Python 3.12.13, worktree off `main` @ `7ef736fb`, `HEADROOM_SKIP_UPSTREAM_CHECK=1` - Exact command / steps: Drove one streaming `/v1/messages` turn through `create_app()` carrying a redeemable `<<ccr:…>>` marker and `headroom_retrieve` in `tools` (so the buffered path engages), with the client sending `Accept: text/event-stream`, and captured the exact headers and body handed to the upstream call. - Observed result: Before — `body.stream=False` sent together with `accept: text/event-stream`, the self-contradicting request. After — `body.stream=False` with `accept: application/json`, and a turn that is not flipped still sends `accept: text/event-stream` unchanged. Reverting only `headroom/proxy/handlers/anthropic.py` fails 3 of the new tests; reverting the OpenAI hunk alone fails the `/v1/responses` test with `['text/event-stream'] != ['application/json']`. Restoring both passes all 6. - Not tested: No live GitHub Copilot gateway call — I have no Copilot credentials here, so the claim that Copilot rejects the contradictory request is inferred from the reporter's logs plus the header mismatch, not observed against their upstream. Confirmation from @mars-peng-lb on a real OpenCode + Copilot session is still wanted before treating #3078 as fully closed. Separately noted while reviewing, **not fixed here**: `_should_buffer_openai_responses_stream_ccr` has no redeemable-marker requirement, so the `/v1/responses` path still buffers on mere tool presence — the #3071/#3092 narrowing was never mirrored from the Anthropic handler. Worth its own issue. ## Runtime Rollout Safety - Rollout-managed feature(s): None — no rollout channel gates this. - Minimum rollout channel: n/a - Stable/default behavior changed: Only on the buffered CCR path, and only the `Accept` header, which is made consistent with the `stream: false` body already being sent. Non-buffered turns are byte-identical, pinned by a test. - Kill switch / disable path: `--no-ccr` / `HEADROOM_NO_CCR` disables the buffered path entirely (see #3082), as does `ccr_handle_responses=False`. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert this commit; the buffered path returns to forwarding the client's `Accept` unchanged. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review Closes #3078 Co-authored-by: Tejas Chopra <tejas@Tejass-MacBook-Pro.local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> |