mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-12-03 02:16:29 +08:00
## Description On `--backend bedrock`, the OpenAI-compatible route (`send_openai_message` / `stream_openai_message`) forwards the client's `messages` verbatim. A client that never sends `cache_control` — OpenAI-compat gateways such as Bifrost strip it — therefore never gets a Bedrock `cachePoint`, and `cache_read_input_tokens` never appears in usage even for models litellm reports as caching-capable. Note on the issue's stated root cause: there is no `litellm.get_supported_openai_params` gate anywhere in headroom (checked `main` and the v0.37.0 commit the reporter pinned), and litellm's Converse transform honours `cache_control` unconditionally. The caching half of #3554 is a missing behaviour, not a wrong API call, so this PR adds it **opt-in** rather than changing the default. The `max_completion_tokens` half is #3558. Design: - New rollout feature `bedrock_openai_prompt_caching` (stable channel, **not** default-enabled): a breakpoint bills the system prompt at the cache-write rate until it is read back, so a one-shot caller who did not ask for it would pay more. `HEADROOM_FEATURES=bedrock_openai_prompt_caching` turns it on; flipping the default later is a one-line `default_enabled_in` change if you want it. - When enabled and `litellm.utils.supports_prompt_caching()` is true for the **mapped** litellm model (`bedrock/us.anthropic.claude-sonnet-5-v1:0`, not the client alias — `claude-sonnet-5` alone is answered from litellm's Anthropic-direct registry entry, not the Bedrock one), the first system message gets `cache_control: {"type": "ephemeral"}`; litellm turns it into a Converse `cachePoint` covering tools + system prefix. First (not last) so volatile trailing system messages cannot turn every turn into a cache write. - Untouched: requests that already carry client-placed markers anywhere (the client owns placement, as on the Anthropic route), models without prompt caching (incl. ARN-mapped inference profiles, which litellm cannot look up), non-Bedrock providers. The caller's `body["messages"]` is never mutated (the proxy re-reads it for `POST_SEND`). Refs #3554 (the `max_completion_tokens` half is #3558) ## Type of Change - [ ] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - `headroom/rollout.py`: register `bedrock_openai_prompt_caching` (available in `stable`, opt-in, no legacy env alias). - `headroom/backends/litellm.py`: import `litellm.utils.supports_prompt_caching` alongside `acompletion`; add pure helper `_place_system_cache_control()`; resolve the rollout decision once in `LiteLLMBackend.__init__` (Bedrock only); gate both OpenAI call sites on the decision + capability lookup (~20 µs/call, no memoisation needed). - `tests/test_backends/test_litellm_bedrock_prompt_caching.py`: 26 tests — helper edge cases (empty/none/wrong-type content, list vs string content, non-dict entries, first-of-several, client-placed markers anywhere, input never mutated), gate off by default (identity), on for buffered + streaming, skips non-caching models, non-Bedrock no-op (lookup not even called), uses the mapped id, kill switch, and litellm's real Converse transform emitting `cachePoint` from the produced messages. - `tests/test_rollout.py`: one assertion pinned a positional index into the alphabetically sorted feature list; made it name-based so adding a feature does not shift it. ## 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 $ python -m pytest tests/test_backends/test_litellm_bedrock_prompt_caching.py -q 26 passed in 4.11s # same file on unpatched main (helper does not exist): E ImportError: cannot import name '_place_system_cache_control' from 'headroom.backends.litellm' $ python -m pytest tests/test_backends tests/test_litellm_openai_passthrough.py tests/test_litellm_caller_key.py \ tests/test_litellm_nonstream_cache_usage.py tests/test_litellm_optional.py tests/test_litellm_upstream_timeout.py \ tests/test_rollout.py tests/test_bedrock_region.py tests/test_bedrock_streaming_input_tokens.py \ tests/test_bedrock_tool_result_cache_and_streaming_stats.py tests/test_bedrock_prefix_tracker_wiring.py \ tests/test_proxy/test_openai_backend_path.py tests/test_proxy/test_bedrock_passthrough.py -q 189 passed (after the test_rollout.py assertion fix; 188 passed, 1 failed before it) $ ruff check headroom/backends/litellm.py headroom/rollout.py tests/test_backends/test_litellm_bedrock_prompt_caching.py tests/test_rollout.py All checks passed! $ ruff format --check headroom/backends/litellm.py headroom/rollout.py tests/test_backends/test_litellm_bedrock_prompt_caching.py tests/test_rollout.py 4 files already formatted $ mypy headroom/backends/litellm.py headroom/rollout.py Success: no issues found in 2 source files # Full local suite (12,650 collected; Windows, borrowed 0.35.0 headroom._core, known Windows-only # CLI tests deselected) was still running when this PR was opened; result will be added below. ``` ## Real Behavior Proof - Environment: Windows 11, Python 3.11.9, litellm 1.97.0 (issue reports 1.96.2; same `supports_prompt_caching` / Converse behaviour), boto3 1.43.93, headroom source checkout at this branch, `LiteLLMBackend(provider="bedrock", region="us-east-1")`, model `global.anthropic.claude-sonnet-5`. No live AWS account available to me, so the request was driven through litellm's real pipeline (message validation, Converse transformation, SigV4 signing) and the outgoing `AsyncHTTPHandler.post` was intercepted to capture the exact wire body and return a canned Bedrock response. - Exact command / steps: `HEADROOM_FEATURES=bedrock_openai_prompt_caching python wire_proof.py` (script in the PR discussion) calling `backend.send_openai_message({"model": "global.anthropic.claude-sonnet-5", "max_tokens": 64, "messages": [{"role": "system", "content": <~1800 tokens>}, {"role": "user", "content": "hi"}]}, {})`; then the same command without the env var. - Observed result: with the feature on, the captured POST to `https://bedrock-runtime.us-east-1.amazonaws.com/model/global.anthropic.claude-sonnet-5/converse` carries `"system": [{"text": ...}, {"cachePoint": {"type": "default"}}]`, SigV4 `Authorization` header present, and the client's `body["messages"]` still contains no `cache_control`. Without the env var (default) the same request carries `"system": [{"text": ...}]` only — byte-identical to today's behaviour. `headroom rollout status` lists `bedrock_openai_prompt_caching: enabled=false decision=not_requested` by default. - Not tested: a live Bedrock round trip (no AWS credentials here), so the returned `cache_creation_input_tokens` / `cache_read_input_tokens` were not observed from Bedrock itself; Bifrost/Cline in front of the proxy; Nova models (litellm reports `supports_prompt_caching=True` for them, so they would be marked too); the Anthropic-format route is untouched by this change. ## Runtime Rollout Safety - Rollout-managed feature(s): `bedrock_openai_prompt_caching` (new entry in `headroom/rollout.py` FEATURES). - Minimum rollout channel: stable (explicit request required in every channel; no `default_enabled_in`). - Stable/default behavior changed: no. Without `HEADROOM_FEATURES=bedrock_openai_prompt_caching` the backend forwards the client's `messages` object untouched (pinned by an identity assertion for buffered and streaming). Only `--backend bedrock` can ever be affected. - Kill switch / disable path: unset `HEADROOM_FEATURES`, or `HEADROOM_DISABLE_FEATURES=bedrock_openai_prompt_caching` (explicit disable wins over an explicit request; tested). - Unsafe override required: no. - Qualification impact: none; the feature is `not_requested` in the default snapshot, so the snapshot digest of an unconfigured deployment only changes by the registry digest (as for any new feature). - Rollback path: revert the commit; no persisted state, schema, or config format involved. ## 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: not changed on purpose — there is no catalogue of rollout features in `docs/`; the `FeatureSpec.description` is what `headroom rollout status` prints. Happy to add a line to `docs/content/docs/runtime-rollouts.mdx` if you want one. - Open questions for the maintainer: (1) default-on for Bedrock instead of opt-in? One-line change (`default_enabled_in=RolloutChannel.STABLE`), but it changes billing for one-shot callers. (2) Prefer the *last* system message (max cache coverage) over the first (robust to volatile trailing system messages)? (3) ARN-mapped application inference profiles (`HEADROOM_BEDROCK_MODEL_MAP`) get nothing because litellm cannot look them up — acceptable, or gate on the underlying model family instead? - Alternatives considered: default-on with no flag (rejected: silent cost change, no kill switch); reusing `AnthropicCacheOptimizer._insert_breakpoints` (Anthropic-format only, mutates in place); doing it in the OpenAI handler (provider-agnostic, lacks the mapped model id). - Verification for someone with Bedrock access: run the proxy with `--backend bedrock` and `HEADROOM_FEATURES=bedrock_openai_prompt_caching`, send two identical OpenAI chat completions with a >1024-token system prompt within 5 minutes; the second response's `usage` should carry non-zero `cache_read_input_tokens` / `prompt_tokens_details.cached_tokens`. Co-authored-by: JD Davis <mxjerrett@gmail.com>