mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-25 12:11:49 +08:00
feat/https-compose-caddy
17
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
956b8855a6 |
fix(proxy): say a forwarded streaming error came from the provider (#4629)
## Description An Extra Headroom user found this line in their proxy log and could not tell whether Headroom or the provider made the 429: `Forwarding upstream streaming error status=429 url=https://chatgpt.com/backend-api/codex/responses` The proxy only passes the provider's error on. The new wording says so. The `status=` and `url=` fields and their order are unchanged, so greps on them still match. ## 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/streaming.py`: the >=400 streaming log line now reads `[%s] Upstream provider returned an error; forwarding it to the client status=%s url=%s`. - `tests/test_proxy_streaming_ratelimit_headers.py`: the assertion on that line follows the new text. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ uv run --frozen --extra dev pytest tests/test_proxy_streaming_ratelimit_headers.py -q 22 passed in 3.60s $ uvx ruff check headroom/proxy/handlers/streaming.py tests/test_proxy_streaming_ratelimit_headers.py All checks passed! $ uvx ruff format --check headroom/proxy/handlers/streaming.py tests/test_proxy_streaming_ratelimit_headers.py 2 files already formatted ``` ## Real Behavior Proof - Environment: macOS 27.2, Python 3.12 via uv, this branch at |
||
|
|
66023a0187 |
fix(proxy): forward Copilot accounting headers on streaming path (#4431)
## Description The streaming path only forwards upstream headers on a short list (`*ratelimit*`, `x-codex*`, `x-litellm-key-*`, request-id family). GitHub Copilot uses `x-github-*` / `*copilot*` headers for AI-credit accounting, and those are not on the list, so they get dropped. When they're missing, the Copilot CLI stamps streamed usage records `aiCreditsStatus: "unavailable"`, leaves out `serviceRequestId`/`providerCallId` and the `copilotUsage` block (which carries `totalNanoAiu`), and stops advancing `session.usage_checkpoint.totalNanoAiu`. Token counts arrive in the SSE body and look correct, so nothing errors. Credits are just silently under-reported by about 4–5x. The buffered path already forwards every upstream header. Real coding agents stream, so the streaming path is the one that matters for Copilot. In a 9-task agentic A/B on `claude-opus-4.8` (one arm direct, one through Headroom): | | direct | via Headroom | |---|---|---| | `aiCreditsStatus: complete` | 990 (100%) | 247 (34.9%) | | `aiCreditsStatus: unavailable` | 0 | 460 (65.1%) | | reported AI credits | 8,015.9 | 1,471.8 (−82%) | | actual cacheRead tokens | 98.5M | 68.8M (−30%) | A −82% drop in credits against a −30% drop in tokens is a measurement gap, not a saving. Closes # ## 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/streaming.py`: forward headers that start with `x-github` or contain `copilot`, and update the comment to explain why. - `tests/test_proxy_streaming_ratelimit_headers.py`: add `test_copilot_accounting_headers_forwarded_in_streaming`, which checks that `x-github-request-id` and `x-copilot-usage` are forwarded on a streamed response and an unrelated header (`cf-ray`) is still dropped. ## 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 -q tests/test_proxy_streaming_ratelimit_headers.py 22 passed in 30.59s # The new test without the fix: $ pytest -q tests/test_proxy_streaming_ratelimit_headers.py -k copilot FAILED ...::test_copilot_accounting_headers_forwarded_in_streaming 1 failed, 21 deselected $ ruff check headroom/proxy/handlers/streaming.py tests/test_proxy_streaming_ratelimit_headers.py All checks passed! $ ruff format --check <same files> 2 files already formatted ``` ## Real Behavior Proof ## Real Behavior Proof - Environment: - macOS 26.6.2 (arm64) - Python 3.12.12 - headroom-ai 0.40.0 from PyPI in a venv (`~/.venvs/headroom-040`), with this PR's two-line change applied to `headroom/proxy/handlers/streaming.py` in site-packages (same diff as this branch) - GitHub Copilot CLI 1.0.103, model `claude-opus-4.8`, reasoning effort `medium` - Upstream: `https://api.githubcopilot.com` - Exact command / steps: 1. Start the proxy, with telemetry off and routed to Copilot: ```bash HEADROOM_COMPRESS_WORKERS=8 HEADROOM_COMPRESSION_DEADLINE_MS=60000 \ ANTHROPIC_TARGET_API_URL=https://api.githubcopilot.com \ OPENAI_TARGET_API_URL=https://api.githubcopilot.com \ GITHUB_COPILOT_API_URL=https://api.githubcopilot.com \ headroom proxy --port 8787 > /tmp/hr-proxy-hdrfix.log 2>&1 ``` 2. Send one streamed Copilot CLI request through it: ```bash cd /tmp && COPILOT_API_URL=http://127.0.0.1:8787 \ copilot --no-experimental --model claude-opus-4.8 --allow-all-tools \ -p "Reply with exactly: OK" ``` 3. Confirm the streaming path was used: ```bash grep "forwarder=streaming" /tmp/hr-proxy-hdrfix.log ``` 4. Check the CLI session transcript (`~/.copilot/session-state/<session-id>/events.jsonl`): ```bash grep -o '"aiCreditsStatus":"[a-z]*"' events.jsonl | sort | uniq -c grep -o '"serviceRequestId":"[^"]*"' events.jsonl | head -1 grep -o '"totalNanoAiu":[0-9]*' events.jsonl | tail -1 ``` - Observed result: Verified end-to-end. The proxy log shows `forwarder=streaming` (`keeping the streaming path (#3071)`). In the resulting transcript, all 9 records are `aiCreditsStatus: complete` and `serviceRequestId` is present. The last checkpoint is `totalNanoAiu = 30,213,500,000` → 30.21 AIC, exactly matching the CLI's displayed `AI Credits 30.21`. - Before the patch: in the A/B eval through unpatched 0.40.0 with the same proxy settings, streamed records were stamped `aiCreditsStatus: "unavailable"` with no `serviceRequestId` and no `copilotUsage`. For example, one task had 70 of 113 records unavailable, and the checkpoint covered only 22% of cacheRead tokens. - Not tested: a live run built from this branch (the identical patch was verified on the 0.40.0 wheel instead); non-Copilot providers end-to-end (unit tests only); `mypy`. ## Runtime Rollout Safety - Rollout-managed feature(s): None - Minimum rollout channel: N/A - Stable/default behavior changed: Yes. The streaming path now also forwards `x-github*` and `*copilot*` response headers, which the buffered path already forwards. - Kill switch / disable path: None; revert the commit. - Unsafe override required: No - Qualification impact: None. Both are response metadata headers, never hop-by-hop. - 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 - [ ] 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 <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4431" 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: dmanepal <dmanepal@linkedin.com> Co-authored-by: JD Davis <mxjerrett@gmail.com> |
||
|
|
33ade5b0e1 |
fix(proxy): forward x-litellm-key-* headers on streaming path (#2532)
## Description
The streaming SSE path rebuilds downstream headers from an allowlist
that forwards `*ratelimit*`, `x-codex-*`, and the `request-id` family —
but drops `x-litellm-key-*`, while the buffered (non-streaming) path
forwards every upstream header. LiteLLM virtual keys report a per-key
spend/budget envelope on every response (`x-litellm-key-spend`,
`x-litellm-key-budget-remaining`, …); these are silently lost for
streaming clients.
This adds `k.lower().startswith("x-litellm-key-")` to the streaming
allowlist — the same one-line widening applied for `*ratelimit*` (#57),
`x-codex-*` (#794), and `request-id` (#1100) — keeping the two paths
symmetric.
Closes #2531
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- `headroom/proxy/handlers/streaming.py`: added `or
k.lower().startswith("x-litellm-key-")` to the `forwarded_headers`
allowlist in `_stream_response`, and expanded the existing comment to
explain the new clause.
- `tests/test_proxy_streaming_ratelimit_headers.py`: added
`test_litellm_key_headers_forwarded_in_streaming`, mirroring the
existing `test_request_id_headers_forwarded_in_streaming` (#1100). It
asserts `x-litellm-key-spend` / `x-litellm-key-budget-remaining` are
forwarded and that a non-allowlisted header (`cf-ray`) is still dropped.
## Testing
- [x] Linting passes (`ruff check .`)
- [x] New tests added for new functionality
### Test Output
```text
$ ruff check headroom/proxy/handlers/streaming.py tests/test_proxy_streaming_ratelimit_headers.py --config pyproject.toml
[]
$ ruff format --check headroom/proxy/handlers/streaming.py tests/test_proxy_streaming_ratelimit_headers.py --config pyproject.toml
2 files already formatted
```
## Real Behavior Proof
- Environment: Arch Linux, kernel 7.1.4, Python 3.14.6. Upstream LiteLLM
proxy as the upstream provider; Headroom built locally from the 0.32.1
source with the streaming allowlist patched for this change, running as
`headroom proxy`.
- Exact command / steps: A streaming POST through the patched Headroom
proxy (with a LiteLLM upstream) returns `x-litellm-key-spend` in the
response headers, where the unpatched build dropped it. A status widget
reading `x-litellm-key-*` from the streaming response resumes updating
after the patch.
- Observed result: `x-litellm-key-spend` (and sibling `x-litellm-key-*`)
present in the streaming response headers with the patch; absent without
it. The buffered path carried them in both cases.
- Not tested: The full `pytest` suite was not run locally. The
backend/compression streaming paths (`_stream_*_via_backend`) forward no
response headers at all and would need a separate change, as noted in
#1100 — out of scope here.
## 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 changes
- [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] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/2532"
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: Bartosz Oudekerk <bartosz.oudekerk@bloomreach.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
|
||
|
|
a961a6fea0 |
fix(proxy): don't retry a 429/529 that cannot succeed within the backoff cap (#3992)
## Description
The streaming and non-streaming forwarders retry every 429/529, sleeping
`Retry-After` capped at `retry_max_delay_ms` (30 s). When upstream's
`Retry-After` is longer than the cap, the retry is re-sent before the
reset and can only fail again. An exhausted subscription window resets
hours ahead. The client waits `attempts × cap` (≈ 61 s by default) for
the same 429, and every proxy chained in front multiplies that wait.
Observed on Claude OAuth traffic (Anthropic `rate_limit_error: This
request would exceed your account's rate limit`):
```text
Upstream 429 (attempt 1/3), retrying in 30000ms
Upstream 429 (attempt 2/3), retrying in 30000ms
Forwarding upstream streaming error status=429
event=proxy_inbound_response status=429 duration_ms=61746.83
```
With one more headroom → proxy → headroom hop in front, a single request
took 744 s to return its 429.
```diff
if status in RETRYABLE_OVERLOAD_STATUSES and retry_enabled and attempts left
+ and not overload_retry_is_futile(response, retry_max_delay_ms, retries_left)
sleep(retry_after_ms(...) or jitter)
retry
+overload_retry_is_futile(response, max_ms, retries_left)
+ x-should-retry: false → True
+ uncapped Retry-After > retries_left × max_ms → True (reset beyond every remaining wait)
+ otherwise → False (no hint / reachable reset: retry as before)
```
`retry_after_ms` now reads `Retry-After` through `_retry_after_seconds`,
which returns the uncapped value. The headers forwarded on the final 429
are unchanged.
Closes #
## 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/helpers.py`: `overload_retry_is_futile(response,
max_ms, retries_left)`; `_retry_after_seconds()` shared with
`retry_after_ms()`. The budget is all remaining retries, not one wait:
with 3 attempts and a 30 s cap, `Retry-After: 31` still retries (30 s,
then the next 429 says 1 s) and recovers.
- `headroom/proxy/handlers/streaming.py`, `headroom/proxy/server.py`
(`_retry_request`): skip the overload retry when it is futile.
- Tests: `tests/test_overload_retry_futile.py` (helper, non-streaming
path, decreasing-Retry-After recovery sequence) and streaming cases in
`tests/test_proxy_streaming_ratelimit_headers.py` (futile hints
forwarded at once; reachable reset recovers on the 3rd attempt).
## Testing
- [x] Unit tests pass (`pytest`): retry/streaming/overload suites listed
below
- [x] Linting passes (`ruff check .`): on the touched files
- [ ] Type checking passes (`mypy headroom`): not run
- [x] New tests added for new functionality
- [ ] Manual testing performed
### Test Output
```text
# before the fix: the new tests fail on origin/main
# streaming 429, retry-after: 3600 → send.await_count 3, want 1 FAILED
# streaming 429, x-should-retry: false → send.await_count 3, want 1 FAILED
# first revision of this PR (single-wait budget): reachable-reset sequences fail
# 429 RA 0.031s → 429 RA 0.001s → 200, cap 20 ms → got 429 after 1 call, want 200 after 3 FAILED (both forwarders)
$ pytest -q tests/test_overload_retry_futile.py tests/test_proxy_streaming_ratelimit_headers.py \
tests/test_retry_preserve_upstream_status.py tests/test_5xx_accounting_all_providers.py \
tests/test_h2_stream_reset_retry.py tests/test_proxy_handler_helpers.py tests/test_proxy
505 passed in 38.40s
$ ruff check headroom/proxy <touched tests> → All checks passed!
$ ruff format --check <touched files> → 5 files already formatted
```
## Real Behavior Proof
- Environment: macOS 27, Python 3.11. `headroom proxy` started from a
source checkout of `origin/main` (before) and of this branch (after),
with `--retry-max-delay-ms 2000` (default 3 attempts),
`--anthropic-api-url` pointing at a local stub upstream, and an isolated
`HOME`. The checkouts have no compiled `headroom._core`, so both ran
with `HEADROOM_REQUIRE_RUST_CORE=false` (Python-only mode; the retry
path is pure Python).
- Exact command / steps: `POST /v1/messages` (non-streaming) through the
proxy against two stub scenarios:
- **exhausted**: every call → `429`, `Retry-After: 3600`
- **reachable**: `429 Retry-After: 3` → `429 Retry-After: 1` → `200`
- Observed result: exhausted 429 is forwarded after 1 upstream call in
0.25 s (was 3 calls, 4.29 s); a reachable reset still recovers to 200 in
3 calls (~3.3 s, unchanged):
```text
before exhausted -> status 429, upstream calls 3, 4.29s
after exhausted -> status 429, upstream calls 1, 0.25s
before reachable -> status 200, upstream calls 3, 3.28s
after reachable -> status 200, upstream calls 3, 3.27s
```
The exhausted case is forwarded at once. The reachable case keeps
recovering: `Retry-After: 3` is over one 2 s wait but inside the 2 × 2 s
budget.
- Not tested: live Anthropic traffic through the patched build, and the
streaming path end to end (covered by the streaming unit tests above).
## Runtime Rollout Safety
- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: yes, narrowly. A 429/529 with
`x-should-retry: false` or a `Retry-After` above `retry_max_delay_ms` is
forwarded after 1 attempt instead of `retry_max_attempts`.
- Kill switch / disable path: raise `--retry-max-delay-ms` above the
upstream hint to restore retrying.
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert the 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 (no doc
covers the retry policy beyond the CLI help)
- [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`
## Additional Notes
Merge danger: two-way door. The blast radius is limited to the overload
retry path, and 5xx and transport retries are untouched. A 429 inside
the cap, such as a short per-minute limit with `Retry-After: 5`, still
retries.
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3992"
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: JerrettDavis <mxjerrett@gmail.com>
|
||
|
|
861e94d8c1 |
fix(proxy): keep exception text and the proxy token out of client output (#3851)
## Why
Two leaks of internal detail to clients and logs (findings 01-F4 and
10-F4).
- When an upstream connection failed, several response paths returned
`str(e)` from `httpx`, `ssl` or the OS in 500/502/503 bodies and SSE
`error` events. That text names the resolved upstream host, its address
and the failing library. A client that can steer the upstream
(`x-headroom-base-url`) could learn internal hostnames one error at a
time.
- `extract_tags` copied every `x-headroom-*` header into
`RequestOutcome.tags`, including `x-headroom-proxy-token`, which
gateways send on every turn. The token then appeared in the request log
(`--log-file`), dashboard facets and any export that carries tags.
## What changes
- New module `headroom/proxy/public_errors.py`. `classify_exception()`
maps transport and OS failures to fixed codes: `upstream_unreachable`,
`upstream_timeout`, `upstream_tls_error`, `upstream_protocol_error`;
anything else is `internal_error`. Every client- or model-visible path
fails closed: unrecognised exception text (`RuntimeError`, `ValueError`,
parser, database or library errors) never leaves the proxy. Provider
error text is forwarded only when the exception carries a provider HTTP
error response (`openai.APIStatusError`, which LiteLLM's provider errors
subclass, or `anthropic.APIStatusError`). Helpers build the existing
wire shapes with the same `error.type`, plus `code` and `request_id`.
The full exception stays in the server log under that request id.
- Every site that built a client-visible message from an exception now
uses it: `handlers/streaming.py` (direct, Bedrock and OpenAI-via-backend
SSE), `handlers/openai.py` (backend 500, `/v1/compress` 503, both
passthrough connect paths), `handlers/anthropic.py` (Bedrock backend
500), `handlers/bedrock.py` (connect 502), the memory tool handlers
(tool results returned to the model), and the `litellm` / `anyllm`
backends. The existing corporate-TLS hint is kept.
- `internal_header_policy.py` gains `is_credential_header()` and
`is_credential_tag_key()`. They match whole name components (`token`,
`secret`, `password`, `authorization`, `cookie`, `apikey`, `key`, and
similar), so `X-Headroom-Key` and `X-Headroom-Api-Key` are covered, so
numeric tags such as `tool-search-deferred-tokens` are not caught.
- `extract_tags` skips credential headers.
`savings_attribution.public_tags`, the last step before the request log,
also drops credential-shaped keys.
## Behaviour change
- Transport-layer and internal failures now return a fixed sentence plus
`code` and `request_id`. Clients that parsed the old free-text messages
should read `error.code`. Provider HTTP error responses (and their
status codes) are unchanged. In the LiteLLM / any-llm backends, an
exception that is not a provider response now returns `The proxy could
not complete the request.`; the HTTP status mapping is unchanged.
- Memory tool results for any failure return `{"status": "error",
"error": "<code>", "message": ...}` instead of the exception text.
- `x-headroom-*` headers whose name contains a credential component are
no longer recorded as tags. A benign label that happens to use such a
name should be renamed.
## Tests
- `tests/test_public_errors.py`: classification of transport exceptions
(including TLS wrapped in a connect error), non-transport exceptions
left alone, wire shapes carry `code` and `request_id`; the passthrough,
direct-streaming and `/v1/compress` error paths contain no upstream
detail; memory tool results hide transport and internal text;
`client_message` / `tool_result_error` / the LiteLLM backend return
`internal_error` for `RuntimeError`, `ValueError`, `KeyError` and
`JSONDecodeError` carrying a path, host and token (10 tests in this file
fail without the fail-closed change), while an
`openai.AuthenticationError` keeps its text; `extract_tags` and
`public_tags` never carry credentials. Six of these fail on `main`.
- Existing tests that asserted the old exception text in client output
now assert the new contract: the client gets the fixed `code` and
`request_id`, the exception text is absent, and the `headroom.proxy` log
has the full text under the same `request_id`
(`test_litellm_transport_errors.py`, `test_openai_backend_path.py`,
`test_proxy_compress_endpoint.py`,
`test_proxy_streaming_ratelimit_headers.py`).
- Manual run with every upstream connect failing: streaming
`/v1/messages`, streaming `/v1/chat/completions` and passthrough
`/v1/models` return `code: upstream_unreachable` with no address. A
request with `x-headroom-proxy-token` and `x-headroom-license-token`
leaves neither value in the `--log-file` output.
Not tested live: the Bedrock and LiteLLM / any-llm backend paths (unit
tests only) and OTEL/Langfuse export (tags are filtered before they
reach it).
## Open review points
- Resolved: unclassified exception text (JerrettDavis, 2026-09-29) now
fails closed in `client_message` and `tool_result_error`.
- Resolved: `X-Headroom-Key` is matched (`key` is a credential
component; the `api`+`key` pair rule is gone). No internal or test tag
key has a `key` component.
- `is_credential_header` special-cases `authorization`, `cookie`,
`api-key` and `x-api-key`, but its only caller passes only
`x-headroom-*` names, so those branches never run.
- `_is_tls_failure` also matches on message text. Provider HTTP error
responses are now checked first in the backends, so this only affects
non-provider exceptions.
- any-llm: only provider errors raised as `openai`/`anthropic`
`APIStatusError` keep their text; any other any-llm exception type
returns `internal_error`.
Revised 2026-10-01 after review: unrecognised exceptions now return a
fixed `internal_error` message and only provider HTTP error responses
keep their text.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
|
||
|
|
2c4dc44627 |
fix(proxy): stamp x-headroom-* compression metrics on streaming responses (#3769)
## Description The buffered (non-streaming) path stamps `x-headroom-tokens-before`, `-after`, `-saved`, `-model` and `-transforms` on its response. The streaming path does not: `_stream_response_inner` forwards only the upstream rate-limit and request-id headers. Coding agents stream, so every Claude Code and Codex turn comes back without the compression metrics, and a client or a metering layer in front of the proxy cannot tell what a request saved without scraping `/stats` or the logs. Every value is already a `_stream_response` argument, known before the first byte, so this adds them to `forwarded_headers`, the same way the buffered path does. Related: #2531 / #2532 forward LiteLLM spend headers on the same streaming block. That is a different header set, and the two changes don't depend on each other. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - `headroom/proxy/handlers/streaming.py`: add `x-headroom-tokens-before/-after/-saved` and `x-headroom-model` to the streaming response headers, plus `x-headroom-transforms` (via `header_safe_transforms`, as on the buffered path) when anything was applied. - `tests/test_proxy_streaming_ratelimit_headers.py`: two tests, one for the full set including comma-safe transform tags alongside the forwarded upstream headers, and one for a no-op request (counts present, no empty transforms header). ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality ### Test Output ```text $ uv run --frozen --extra dev pytest tests/test_proxy_streaming_ratelimit_headers.py -q 16 passed in 1.77s # Same two new tests against upstream/main's streaming.py (fix reverted): 2 failed, 14 passed in 2.21s $ uv run --frozen --extra dev pytest tests -q -k "stream or header or x_headroom" 887 passed, 29 skipped, 12593 deselected in 125.81s $ uvx ruff check <changed files> -> All checks passed! $ uvx ruff format --check <changed files> -> 2 files already formatted $ uv run --frozen --extra dev mypy headroom/proxy/handlers/streaming.py -> Success: no issues found in 1 source file ``` ## Real Behavior Proof - Environment: macOS 15 (arm64), headroom-ai 0.38.0 behind Headroom Desktop, real Claude Code 2.1.28x traffic (terminal and VS Code) to api.anthropic.com. The same header stamping ran there as a local patch wrapping `_stream_response` from 2026-09-23 on. - Exact command / steps: Used Claude Code normally through the proxy. A client in front of the proxy read `x-headroom-tokens-saved` from each streaming `/v1/messages` response head and summed it per `x-claude-code-session-id`. - Observed result: Streaming responses carried the headers, and the per-request savings the client recorded matched the proxy log's `tok_saved` for the same turns (e.g. `tok_saved=2865` in the log, +2865 recorded), across 64 conversations in about a day. Without the patch the 0.38.0 streaming handler sets none of these headers (read from source), so the client had nothing to record. - Not tested: This exact branch end to end against a live provider (the evidence above is the equivalent patch on 0.38.0; this branch is covered by the unit tests), and the Bedrock and Gemini streaming handlers, which build their own responses and are unchanged. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: Stable. - Stable/default behavior changed: Yes, additively: streaming responses gain five `x-headroom-*` headers the buffered path already sends. The body and all existing headers are unchanged. - Kill switch / disable path: None needed; clients ignore unknown response headers. Reverting the commit removes them. - Unsafe override required: No. - Qualification impact: None. - Rollback path: 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) Not applicable. ## Additional Notes Documentation: no doc lists the streaming response headers today, so nothing to update. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
85fac8c3a9 |
fix(stats): stop rejected upstream turns from feeding the savings funnel (#3615)
## Description Carries #3010 by @nangsontay across the line. That PR moves the `emit_request_outcome` funnel short-circuit from `status_code >= 500` to `>= 400`, so a turn the provider rejected cannot reach `metrics.record_request`, `cost_tracker.record_tokens`, the `RequestLog` feed, or the PERF line. It was approved on 2026-09-13 and then blocked on one test seam (`test_codex_rate_limit_captured_on_streaming_429` awaits a `MagicMock`); no push since. This PR keeps the original commit verbatim (author preserved) and adds one commit that fixes that seam and updates the PR's new buffered-CCR test for #3092, which landed on main afterwards and gates the buffered path on a redeemable marker rather than the resident tool alone. Second real-world case, independent of the 429 fast-mode one in #3010: a Claude Code session on 2026-09-16 grew past the 1M window and entered a compaction loop. Every compaction request came back `400 invalid_request_error: prompt is too long: 2183557 tokens > 1000000 maximum`. Anthropic processed and billed none of them (the subscription window stayed at 2% / 4%), yet the proxy ran the full success funnel on each. 13 rejected turns of 1.6M to 1.9M tokens added 23.7M "input tokens" and $242 of "input cost" to the session display; 96% of that session's reported usage was turns the provider never served. Supersedes #3010. ## 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/outcome.py` (from #3010, unchanged): funnel short-circuit at `status_code >= 400`; 429 books via `record_rate_limited`, every other 4xx/5xx via `record_failed`. Neither counter feeds savings. - `tests/test_outcome_records_5xx_as_failed.py` (from #3010): 429 rate-limited case, parametrized 400/401/403/404/413/422 sweep, and a 200 control that still reaches the funnel with `tokens_saved` intact. - `tests/test_anthropic_buffered_ccr_usage.py` (from #3010, adapted): the two buffered-CCR cases now plant an owned `<<ccr:...>>` marker via the same fixture `tests/test_ccr_buffered_stream_signed_thinking.py` uses, because #3092 no longer buffers on the resident tool alone. Without that the assertion `upstream saw stream:false` fails on current main. - `tests/test_proxy_streaming_ratelimit_headers.py`: the mock proxy's `metrics.record_rate_limited` is an `AsyncMock`, matching `record_request` / `record_failed` on the same mock. This is the seam the #3010 review flagged. ## 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 ### Test Output ```text $ uv run --frozen --extra dev pytest tests/test_proxy_streaming_ratelimit_headers.py tests/test_outcome_records_5xx_as_failed.py tests/test_anthropic_buffered_ccr_usage.py tests/test_ccr_buffered_stream_signed_thinking.py -q 39 passed, 1 warning in 10.02s $ uv run --frozen --extra dev pytest tests -q -x -k "outcome or ratelimit or rate_limit or 429 or 4xx or upstream_error or record_failed or savings_tracker or persistent_metrics or buffered" 320 passed, 10 skipped, 12765 deselected, 2 warnings in 77.61s $ uv run --frozen --extra dev pytest tests -q -x 12172 passed, 7 failed, 593 skipped in 810s. The 7 (tests/test_proxy_health.py readyz-kompress cases and tests/test_read_maturation_handler_nobust.py) pass when run as their own files on this branch (22 passed) and on unmodified upstream/main; they are order-dependent and untouched by this change. $ uvx ruff check headroom/proxy/outcome.py tests/test_proxy_streaming_ratelimit_headers.py tests/test_outcome_records_5xx_as_failed.py tests/test_anthropic_buffered_ccr_usage.py All checks passed! $ uv run --frozen --extra dev mypy headroom/proxy/outcome.py Success: no issues found in 1 source file ``` ## Real Behavior Proof - Environment: macOS 15.6 (Darwin 24.6.0), Python 3.11, this branch at its head, against a `create_app(ProxyConfig(optimize=False, ...))` proxy with the real `PrometheusMetrics`. - Exact command / steps: Replayed the live loop through `proxy._record_request_outcome`: 13 outcomes with `status_code=400`, `original_tokens=1640331`, `optimized_tokens=1638180`, `tokens_saved=2151` (the PERF values of request `hr_1789579601_001966` from the 2026-09-16 session), then one identical outcome with `status_code=200` as control. Printed `metrics.tokens_input_total`, `requests_failed`, `requests_total` after each phase. Then swapped in `upstream/main`'s `outcome.py` and re-ran. - Observed result: This branch: `tokens_input_total: start=0 after 13x400=0 after 1x200=1638180`, `requests_failed=13 requests_total=1`. `upstream/main`: the 13 rejected turns raised `tokens_input_total` to 21,296,340 before the control ran (assertion `400s still feed input totals` fired). - Not tested: A live upstream 400 through the whole HTTP handler on this branch; the handler sites already pass `status_code=response.status_code` (added in #1571 / #2682), so the funnel is the only place the status is consulted. Not re-measured on Windows. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: Stable. - Stable/default behavior changed: Yes, accounting only. A 4xx upstream response no longer increments `requests_total`, `tokens_input_total`, the savings/cost ledgers, or the request log; it increments `requests_failed` (or `requests_rate_limited` for 429). The response returned to the client is unchanged. - Kill switch / disable path: None. Revert the commit. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert the squash commit; no persisted state changes shape. ## 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 Documentation: N/A, no user-facing surface changes beyond the counters already documented. Credit for the fix and its analysis belongs to @nangsontay in #3010; happy for maintainers to land whichever of the two is more convenient and close the other. --------- Co-authored-by: nangsontay <github@nangsontay.com> |
||
|
|
4949cd5594 |
fix(proxy): record streaming upstream 5xx as failed instead of success (#2682)
## Description A streaming request that fails upstream is currently recorded as a success. `RequestOutcome.from_stream` takes no `status_code`, so every outcome built through it keeps the dataclass default of 200. The `>= 500` guard in `emit_request_outcome` can never fire on a streaming request, and an exhausted 529 lands in the savings and cost stats as a request the proxy served. That inflates the save-rate. `streaming.py` contains zero `record_failed` calls today. The error path is not a dead end that skips accounting. The `>= 400` branch does not early-return. It calls `_finalize_stream_response` and then returns the error response to the client. That finalizer has no `return` statement anywhere in its body and no reference to a status, so the failure books through the full success funnel exactly like a 200. This is the streaming half of #1568. The non-streaming half landed in |
||
|
|
0951663562 |
fix(proxy): close the upstream stream when a streaming body is never consumed
Close unconsumed upstream streaming bodies. |
||
|
|
3d59df7be8 |
fix(proxy): forward request-id headers on the streaming path (#1100) (#1258)
## Description On the streaming (SSE) path the proxy rebuilt response headers from a deny-by-default allowlist that only kept rate-limit and Codex headers, so Anthropic's `request-id` was dropped. Claude Code needs that header to write `requestId` into transcripts; without it, usage/cost tools that dedup on `messageId` + `requestId` over-count tokens. This widens the streaming allowlist to also forward the `request-id` family, matching the non-streaming path. Closes #1100 ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - `headroom/proxy/handlers/streaming.py`: widened the streaming response-header allowlist to also forward `request-id`, `anthropic-request-id`, and `x-request-id`. - `tests/test_proxy_streaming_ratelimit_headers.py`: flipped two assertions that expected `x-request-id` to be dropped, and added `test_request_id_headers_forwarded_in_streaming`. ## Testing - [x] Unit tests pass (`pytest`) ### Test Output ```text $ pytest tests/test_proxy_streaming_ratelimit_headers.py -q 11 passed $ pytest tests/ -k "header or stream" -q 75 passed ``` ## Real Behavior Proof - Environment: Windows 11, Python 3.12, pytest-asyncio 1.4.0 (asyncio_mode=auto) - Exact command / steps: Ran the streaming rate-limit header suite plus adjacent header/stream tests after widening the allowlist. - Observed result: All 11 tests in the targeted file pass including the new request-id forwarding test; 75 adjacent header/stream tests stay green. - Not tested: Did not run a live end-to-end `claude -p` round-trip through the proxy to inspect transcript `requestId`. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
0ce68dedd7 |
fix(proxy): restore Codex usage headers on WS and streaming SSE transports (#577) (#794)
## Description Codex's subscription/rate-limit window (the `x-codex-*` headers) was being **stripped on every transport Codex actually uses**, so session/weekly usage never reached the Codex CLI's own `/status` display, Headroom `/stats`/dashboard, or any consumer that sniffs the client-facing handshake. This PR restores it on **both** the WebSocket and streaming-SSE paths — the two halves of #577 — in one place. Fixes #577 **Supersedes #582 and #590.** This PR incorporates #582's SSE fix (carried verbatim with a `Co-authored-by` trailer) and additionally forwards the window onto the client `101` on the WS path, which #582/#590's capture-only WS code cannot do. Both can be closed as superseded once this merges — GitHub closing keywords only auto-close issues (hence `Fixes #577` above), not PRs, so #582/#590 need a manual close. ### WebSocket (`gpt-5.4+`) OpenAI delivers `x-codex-*` **only** on the upstream WS handshake response, never in data frames. `handle_openai_responses_ws` accepted the client WS *before* it connected upstream and never read `upstream.response.headers`, so the window was dropped. This reorders the handler to **connect upstream first**, extract the `x-codex-*` subset, then **accept the client WS with those headers attached** to the `101`, and refresh the Python state for `/stats` parity. ### Streaming SSE (incorporated from #582, @m16khb) Codex CLI almost always streams. `streaming.py` neither captured `x-codex-*` into `CodexRateLimitState` nor forwarded it — the forwarded-header filter matched only the substring `"ratelimit"`, which `x-codex-*` does not contain. This calls `update_from_headers()` **before** the `>=400` early-return (so a streaming 429/5xx still refreshes the window, matching the non-streaming handlers) and widens the forward filter to pass `x-codex-*`. > Credit: the SSE fix is @m16khb's work from #582, carried here verbatim with a > `Co-authored-by` trailer so the maintainer gets a single PR covering both > transports. This supersedes #582/#590's **WS** capture (which only writes > `/stats`); the connect-before-accept reorder additionally forwards the window to > the client `101`, which capture-only cannot do. #590's optional snapshot > persistence is intentionally left out (separable; hot-path sync write; doesn't > help the `101`-sniff consumers). ## 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 - `openai.py`: add `_extract_codex_handshake_headers()` (strictly `x-codex-*`, via `raw_items()` to avoid `MultipleValuesError`; never `set-cookie`/`authorization`). - `openai.py`: reorder `handle_openai_responses_ws` — connect-only retry loop runs before `accept()`; `accept(headers=...)` carries the forwarded window; first client frame read afterward. HTTP fallback preserved; it now also refreshes `/stats` from the HTTP response headers. - `streaming.py`: capture `x-codex-*` on all statuses + widen the forwarded-header filter (from #582). ### Diff-size note The bulk of the `openai.py` line count is **whitespace-only relocation**: the relay block dedents one level out of the old per-attempt `async with`. Logical change is ~290 lines. **Review with `?w=1`.** In API-key mode the handshake carries no `x-codex-*`, so the accept-header list is empty and the path behaves exactly as before — the fix only activates for ChatGPT-subscription auth. ## 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 - WS: `test_ws_connect_happens_before_accept`, `test_ws_forwards_codex_headers_to_client_accept` (only `x-codex-*` forwarded; `set-cookie`/`authorization` excluded; `/stats` refreshed), `test_ws_connect_failure_falls_back_to_http`, `test_ws_first_frame_timeout_after_connect_closes_upstream`. - Fallback: `test_fallback_refreshes_codex_rate_limit_state`. - SSE: `test_codex_rate_limit_headers_captured_and_forwarded_in_streaming`, `test_codex_rate_limit_captured_on_streaming_429` (from #582). - Wire-level e2e: `tests/e2e_ws_codex_usage_headers.py` boots the real proxy + fake upstream + real `websockets` client and reads the client `101` — closes the gap the unit tests stub (that uvicorn/starlette actually write `accept(headers=...)`). ## Test Output ``` $ uv run pytest tests/test_proxy_streaming_ratelimit_headers.py \ tests/test_ws_http_fallback.py \ tests/test_openai_codex_ws_lifecycle.py \ tests/test_openai_codex_ws_timings.py \ tests/test_codex_rate_limits.py -q 63 passed in 0.83s $ .venv/bin/python tests/e2e_ws_codex_usage_headers.py [codex-hdr-e2e] client 101 headers: x-codex-primary-used-percent: 42 x-codex-primary-window-minutes: 300 x-codex-secondary-used-percent: 7 x-codex-secondary-window-minutes: 10080 [codex-hdr-e2e] /stats reflects codex window (primary-used=42) === CODEX-HDR E2E ALL GREEN === $ uv run ruff check . && uv run ruff format --check <touched files> All checks passed! ``` ## 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 - [ ] I have updated the CHANGELOG.md if applicable ## Additional Notes - **Why connect-before-accept (not capture-only).** Once `accept()` sends the `101`, headers can no longer be added; the `x-codex-*` window only exists after we connect upstream. Capturing into Python state (as #582/#590's WS code does) fixes `/stats` but not the Codex CLI's native display or any `101`-sniffing consumer — those need the headers *on the client handshake*, which requires the reorder. - **Security.** Forwarding is filtered strictly to `x-codex-*`; `set-cookie`, `authorization`, and all other upstream headers are never forwarded to the client (asserted by both the unit test and the e2e). 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Contract Schemas Per maintainer request: a JSON Schema (draft 2020-12) artifact enshrining the OpenAI interaction expectations this changeset relies on, so drift is detectable later. Committed following the repo's parity convention: - schema: `tests/parity/fixtures/codex_openai_contracts/codex-openai-interaction.schema.json` - test: `tests/test_codex_openai_contract_parity.py` binds the schema to the **live code** in both directions, so drift fails CI rather than living only in this description - every declared `x-codex-*` header must be consumed by `parse_codex_rate_limits`, and `_extract_codex_handshake_headers` must forward exactly the declared subset and never `set-cookie`/`authorization`. No new dependency (does not pull in `jsonschema`). It covers, as `$defs`: - `WSUpstreamHandshakeResponse` / `StreamingUpstreamResponseHeaders` - the upstream `x-codex-*` header family (full superset, with per-header wire pattern + the parsed semantic type) the WS and SSE captures read. Source of truth: `parse_codex_rate_limits`. - `ClientForwardedHandshakeHeaders` - the WS-101 **allow/deny** contract: only `x-codex-*` may be forwarded; `set-cookie`/`authorization` are explicitly forbidden (`propertyNames` + `not`). - `ClientForwardedStreamingHeaders` - the wider SSE forward set (`*ratelimit*` OR `x-codex*`). - `WSClientRequestFrame` / `WSRelayEvent` / `HTTPFallbackRequestBody` - the WS frame envelopes and the unwrapped HTTP-fallback POST body. - `CodexRateLimitStatsOutput` - the headroom `/stats` shape the parity tests assert. Validated with `jsonschema` (Draft202012 `check_schema` passes; positive instances from the e2e validate; negative instances - a leaked `set-cookie`, a fallback body still carrying a top-level `type` - are correctly rejected). <details> <summary><code>codex-openai-interaction.schema.json</code> (draft 2020-12)</summary> ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/chopratejas/headroom/contracts/codex-openai-interaction.schema.json", "title": "Codex <-> OpenAI interaction contracts (PR #794)", "description": "Enshrines the OpenAI interaction expectations this changeset depends on, so drift is detectable. Header values are transported as strings on the wire; the `x-headroom-parsed-type` annotation on each records the semantic type the parser (headroom/subscription/codex_rate_limits.py) coerces them to. Sources: codex_rate_limits.parse_codex_rate_limits (header family + gating), openai._extract_codex_handshake_headers (WS-101 forward filter), streaming.py (SSE forward filter).", "$defs": { "OpenAICodexWindowHeaders": { "title": "x-codex-*-{primary,secondary} window headers", "description": "A rolling rate-limit/subscription window. A window is materialized iff its `*-used-percent` header is present and numeric; `*-window-minutes` and `*-reset-at` are optional. `primary` and `secondary` are independent and either may be absent.", "type": "object", "properties": { "x-codex-primary-used-percent": { "type": "string", "pattern": "^\\d+(?:\\.\\d+)?$", "x-headroom-parsed-type": "float (0-100, NaN-guarded)", "description": "Percent of the primary window consumed. Gates creation of the primary window." }, "x-codex-primary-window-minutes": { "type": "string", "pattern": "^\\d+$", "x-headroom-parsed-type": "int", "description": "Primary window size in minutes." }, "x-codex-primary-reset-at": { "type": "string", "pattern": "^\\d+$", "x-headroom-parsed-type": "int (Unix epoch seconds)", "description": "Absolute reset time of the primary window." }, "x-codex-secondary-used-percent": { "type": "string", "pattern": "^\\d+(?:\\.\\d+)?$", "x-headroom-parsed-type": "float (0-100, NaN-guarded)", "description": "Percent of the secondary window consumed. Gates creation of the secondary window." }, "x-codex-secondary-window-minutes": { "type": "string", "pattern": "^\\d+$", "x-headroom-parsed-type": "int" }, "x-codex-secondary-reset-at": { "type": "string", "pattern": "^\\d+$", "x-headroom-parsed-type": "int (Unix epoch seconds)" } }, "additionalProperties": true }, "OpenAICodexCreditsHeaders": { "title": "x-codex-credits-* headers", "description": "OpenAI credits balance. A credits snapshot is materialized iff `x-codex-credits-has-credits` is present; `unlimited` defaults to false; `balance` is optional.", "type": "object", "properties": { "x-codex-credits-has-credits": { "type": "string", "pattern": "^(?:[Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]|[01])$", "x-headroom-parsed-type": "bool (true|false|1|0, case-insensitive)", "description": "Gates creation of the credits snapshot." }, "x-codex-credits-unlimited": { "type": "string", "pattern": "^(?:[Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]|[01])$", "x-headroom-parsed-type": "bool (defaults false when absent/unparseable)" }, "x-codex-credits-balance": { "type": "string", "x-headroom-parsed-type": "str (empty -> null)", "description": "Free-form server string, e.g. \"$5.00\"." } }, "additionalProperties": true }, "OpenAICodexMetaHeaders": { "title": "x-codex meta headers", "type": "object", "properties": { "x-codex-limit-name": { "type": "string", "x-headroom-parsed-type": "str (empty -> null)", "description": "Active limit/model label, e.g. \"gpt-5.2-codex-sonic\"." }, "x-codex-promo-message": { "type": "string", "x-headroom-parsed-type": "str (empty -> null)", "description": "Server announcement. Also gates snapshot creation when present." } }, "additionalProperties": true }, "OpenAICodexRateLimitHeaders": { "title": "Full x-codex-* header family OpenAI may emit", "description": "Superset of every x-codex-* header headroom reads. parse_codex_rate_limits returns a snapshot iff at least one of: a primary window, a secondary window, a credits snapshot, or a non-empty promo message is present; otherwise null (treated as a non-Codex response). All members are individually optional.", "type": "object", "allOf": [ { "$ref": "#/$defs/OpenAICodexWindowHeaders" }, { "$ref": "#/$defs/OpenAICodexCreditsHeaders" }, { "$ref": "#/$defs/OpenAICodexMetaHeaders" } ], "additionalProperties": true }, "WSUpstreamHandshakeResponse": { "title": "OpenAI WS handshake (101) response headers consumed by the WS fix", "description": "On the Codex WebSocket transport the x-codex-* window is delivered ONLY on the upstream handshake response (never in data frames). handle_openai_responses_ws reads upstream.response.headers here. This is the contract the connect-before-accept reorder depends on: if OpenAI ever moves these headers off the handshake (e.g. into a frame), the WS half of the fix goes stale.", "$ref": "#/$defs/OpenAICodexRateLimitHeaders" }, "StreamingUpstreamResponseHeaders": { "title": "OpenAI streaming/HTTP response headers consumed by the SSE fix", "description": "On the streaming SSE/HTTP transport the same x-codex-* headers ride the HTTP response. streaming.py captures them on ALL statuses (including >=400) via update_from_headers, and forwards a wider set to the client (see ClientForwardedStreamingHeaders).", "$ref": "#/$defs/OpenAICodexRateLimitHeaders" }, "ClientForwardedHandshakeHeaders": { "title": "Headers forwarded onto the CLIENT-facing WS 101 (allow/deny contract)", "description": "_extract_codex_handshake_headers forwards ONLY headers whose (lowercased) name starts with `x-codex-`. Every other upstream handshake header - notably set-cookie and authorization - MUST NOT appear on the client 101. Enforced by propertyNames below and asserted by the unit tests + tests/e2e_ws_codex_usage_headers.py.", "type": "object", "propertyNames": { "pattern": "^[Xx]-[Cc][Oo][Dd][Ee][Xx]-" }, "not": { "anyOf": [ { "required": ["set-cookie"] }, { "required": ["Set-Cookie"] }, { "required": ["authorization"] }, { "required": ["Authorization"] } ] }, "additionalProperties": { "type": "string" } }, "ClientForwardedStreamingHeaders": { "title": "Headers forwarded to the client on the streaming SSE path", "description": "streaming.py forwards a header iff `\"ratelimit\" in name.lower()` OR `name.lower().startswith(\"x-codex\")`. This is a SUPERSET of the WS allow-list: it additionally passes generic *ratelimit* headers (e.g. the Anthropic streaming path) which do not contain the x-codex prefix.", "type": "object", "propertyNames": { "pattern": "(?:[Rr][Aa][Tt][Ee][Ll][Ii][Mm][Ii][Tt])|^[Xx]-[Cc][Oo][Dd][Ee][Xx]" }, "additionalProperties": { "type": "string" } }, "WSClientRequestFrame": { "title": "Client -> proxy WS data frame (Responses API over WS)", "description": "Codex sends the request as a response.create envelope. The HTTP fallback unwraps `.response` for the POST body, forces stream=true, and strips any top-level `type`. A flattened variant (no envelope, fields at top level) is also tolerated by the fallback.", "type": "object", "properties": { "type": { "const": "response.create" }, "response": { "type": "object", "properties": { "model": { "type": "string", "description": "e.g. gpt-5.4" }, "input": { "description": "String prompt or Responses-API structured input array.", "type": ["string", "array"] }, "stream": { "type": "boolean" } }, "required": ["model"], "additionalProperties": true } }, "required": ["type", "response"], "additionalProperties": true }, "WSRelayEvent": { "title": "proxy -> client WS data frame (relayed Responses API event)", "description": "SSE `data:` payloads relayed verbatim as WS text frames. `[DONE]` sentinels are dropped (not relayed). Every relayed event is a JSON object carrying a `type`. response.completed additionally carries usage under `response.usage`. anyOf (not oneOf): an error event also satisfies the looser lifecycle shape, which is fine.", "anyOf": [ { "title": "lifecycle event", "type": "object", "properties": { "type": { "type": "string", "examples": [ "response.created", "response.output_item.added", "response.completed" ] }, "response": { "type": "object", "additionalProperties": true } }, "required": ["type"], "additionalProperties": true }, { "title": "error event", "type": "object", "properties": { "type": { "const": "error" }, "error": { "type": "object", "properties": { "message": { "type": "string" } }, "required": ["message"], "additionalProperties": true } }, "required": ["type", "error"], "additionalProperties": true } ] }, "HTTPFallbackRequestBody": { "title": "proxy -> OpenAI HTTP POST body on WS->HTTP fallback", "description": "Derived from WSClientRequestFrame: the inner `.response` object, with `stream` forced to true and any top-level `type` removed.", "type": "object", "properties": { "model": { "type": "string" }, "stream": { "const": true }, "input": { "type": ["string", "array"] } }, "required": ["model", "stream"], "not": { "required": ["type"] }, "additionalProperties": true }, "CodexRateLimitStatsOutput": { "title": "headroom /stats output for the codex tracker (CodexRateLimitSnapshot.to_dict)", "description": "Internal (headroom-emitted) shape produced from the headers above; the WS and SSE update_from_headers parity tests assert this is refreshed. Included so drift in our own surface is also caught.", "type": "object", "properties": { "limit_id": { "const": "codex" }, "limit_name": { "type": ["string", "null"] }, "primary": { "$ref": "#/$defs/CodexWindowDict" }, "secondary": { "$ref": "#/$defs/CodexWindowDict" }, "credits": { "oneOf": [ { "type": "null" }, { "type": "object", "properties": { "has_credits": { "type": "boolean" }, "unlimited": { "type": "boolean" }, "balance": { "type": ["string", "null"] } }, "required": ["has_credits", "unlimited", "balance"], "additionalProperties": false } ] }, "promo_message": { "type": ["string", "null"] }, "captured_at": { "type": "number", "description": "Unix epoch seconds (float)." } }, "required": ["limit_id", "limit_name", "primary", "secondary", "credits", "promo_message", "captured_at"], "additionalProperties": false }, "CodexWindowDict": { "oneOf": [ { "type": "null" }, { "type": "object", "properties": { "used_percent": { "type": "number" }, "window_minutes": { "type": ["integer", "null"] }, "window_label": { "type": "string", "description": "e.g. \"5h\", \"7d\"-style label; \"unknown\" when window_minutes is null." }, "resets_at": { "type": ["integer", "null"], "description": "Unix epoch seconds." }, "seconds_until_reset": { "type": ["integer", "null"] } }, "required": ["used_percent", "window_minutes", "window_label", "resets_at", "seconds_until_reset"], "additionalProperties": false } ] } } } ``` </details> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: m16khb <m16khb@gmail.com> |
||
|
|
c788b7d6c9 |
style: align proxy tests with current ruff formatter
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> |
||
|
|
6690740218 | chore(merge): resolve upstream main conflicts for pi codex branch | ||
|
|
b0422cd27a | fix(proxy): retry responses transport without bypassing compression | ||
|
|
9f0a813004 | fix: address PR review feedback | ||
|
|
4bdc1482af |
feat: add Pi/Codex and Cloud Code Assist compatibility routes
- Adds /v1/codex/responses aliases for OpenAI Codex clients configured with /v1 base URLs - Uses JWT-derived account routing for /v1/responses/* subpaths (compact, cancel, etc) - Adds /v1internal:streamGenerateContent aliases for Cloud Code Assist / Antigravity - Preserves upstream HTTP error status/body in StreamingResponse (fixes empty SSE drops) |
||
|
|
83c60407e7 |
test: verify ratelimit headers are forwarded in streaming responses
Tests cover: - Ratelimit headers from upstream are present in StreamingResponse - Non-ratelimit headers are NOT forwarded (only ratelimit filtered) - Missing ratelimit headers don't break streaming - Connection errors return proper SSE error events Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> |