Commit Graph
3 Commits
Author SHA1 Message Date
35ca9b8356 fix(proxy): reconcile Chat content-block cache markers after prefix replay (#4333)
## Description

OpenCode V2 talking to Claude through an OpenAI-compatible gateway
(LiteLLM → Bedrock) marks
Chat **content blocks**: two system text blocks, the newest user or tool
text block, plus one tool
definition. After the Chat prefix replay (`_restore_frozen_prefix` /
`finalize_turn`), last turn's
block marker is forwarded again next to the client's moved one. The
client sends four markers, the
proxy forwards five, and the provider rejects the turn:

```text
A maximum of 4 blocks with cache_control may be provided. Found 5.
```

#3895 fixed the same accumulation for message-dict and `tool_calls`
markers, and its helper
explicitly left block markers alone. This PR extends
`mirror_client_message_cache_control` to
content blocks, so all three Chat marker holders follow the client's
current request.

Related: #3894 (same symptom, message-level variant), #4332 (separate
token-mode lost breakpoint).

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `mirror_client_message_cache_control` now also reconciles
`content[].cache_control`:
- The client marks a block → copy the client's own value (`ttl` kept per
position).
- The client marks no block in that message → drop replayed block
markers.
This also covers OpenCode resending an older turn as a **string** while
the replay restores
    the block form it forwarded when that turn was newest.
- The client marks blocks but the block count no longer aligns → leave
the message unchanged.
    No index guessing.
- Only `cache_control` keys change; never creates a marker and never
moves one to another block.
- Why not reuse `normalize_message_cache_control`: in Chat the system
prompt lives in `messages`.
Its legacy fallback strips every block marker and re-places one, which
would also drop the
  client's system breakpoints.
- Why not rely on `enforce_cache_breakpoint_budget`: it only runs for
`provider == "anthropic"`.
  This traffic is OpenAI Chat to a gateway, so it never runs here.
- The insertion point is unchanged. The existing mirror call already
runs after both Chat replays
and before forwarding and the tracker snapshot, so cache and token mode
and streaming and
  buffered forwarding are all covered.
- Docstring and comment no longer claim OpenAI-compatible OpenCode never
marks blocks.

## Testing

- [x] Unit tests pass (`pytest`): see below
- [x] Linting passes (`ruff check .`, `ruff format --check`)
- [x] Type checking passes (`mypy headroom/cache/prefix_tracker.py`)
- [x] New tests added for new functionality
- [x] Manual testing performed

New: `tests/test_openai_block_cache_control_replay.py` (20 tests).
Without the fix, 17 fail.

- Helper cases:
  - moved user → tool breakpoint
  - byte-identical replayed content
  - mid-message positions with `ttl: 1h` and `5m`
  - client with no block markers (none created)
  - client with no markers at all
  - mixed block, message and `tool_calls` markers
  - block-count mismatch (left unchanged)
  - string client content vs replayed blocks
- literal `cache_control` inside tool text and arguments stays user data
  - idempotence
- Handler cases capture the real forwarded body through
`/v1/chat/completions`:
  - cache and token mode (token with frozen floor 2)
  - streaming and buffered
  - block-form and string-form older user turn
- the tracker snapshot records the reconciled layout, and turn 3 stays
bounded

### Test Output

```text
$ pytest tests/test_openai_block_cache_control_replay.py tests/test_openai_message_level_cache_control.py
29 passed in 5.19s

# same new file with the fix reverted
17 failed, 3 passed

# related cache / prefix / OpenAI / proxy / LiteLLM / compression-cache suites
1217 passed, 33 skipped

# full suite, before vs after: identical failure set except three tests that
# fail intermittently under -n 8 on both builds and pass in isolation on both.
# All remaining failures are local-environment only (no Rust toolchain,
# sandboxed network, missing optional extras).
41 failed, 16305 passed, 860 skipped, 14 errors

$ ruff check . && ruff format --check headroom tests     # clean
$ mypy headroom/cache/prefix_tracker.py                  # Success: no issues found
```

## Real Behavior Proof

- Environment: macOS arm64, Python 3.13, OpenCode 2.1.2 with the bundled
Headroom plugin → `headroom proxy --mode cache|token` → LiteLLM gateway
→ Bedrock Claude Haiku; synthetic data only.
- Exact command / steps: Ran the same OpenCode agent task (one tool
returning 120 synthetic JSON records, called 3 times in sequence)
through the proxy, once on installed 0.41.0 and once importing this
branch's Python source via `PYTHONPATH` (Rust crates unchanged since
0.41.0); an `httpx` hook in the proxy recorded only the `cache_control`
paths of each outbound body.
- Observed result: 0.41.0 forwards 5 markers on the second request and
the gateway returns 400 "Found 5"; with this branch, cache and token
mode forward at most 4 markers on every request and the agent returns
the exact expected answer after 3 tool calls.
- Not tested: Windows; Anthropic `/v1/messages` (unchanged path);
Responses API; clients other than OpenCode V2; live sessions longer than
4 requests; compression of cache-protected Chat text blocks.

### Details

| Build | Mode | Inbound markers per request | Outbound markers per
request | Result |
| --- | --- | --- | --- | --- |
| 0.41.0 | cache | 4, 4 | 4, **5** | 400 "Found 5", turn aborted |
| this PR | cache | 4, 4, 4, 4 | 4, 4, 4, 4 | exact answer after 3 tool
calls |
| this PR | token | 4, 4, 4, 4 | 4, 4, 4, 3 | exact answer after 3 tool
calls (see note) |

Loopback HTTP replay of the same shapes (4 steps, cache and token, with
and without a
provider-confirmed frozen floor):

- 0.41.0 forwards 4/5/6/7 markers.
- This branch forwards 4/4/4/4 in all four cases.

Paths and values match the client, and the non-marker message bytes are
unchanged.

The token-mode `3` also reproduces on unpatched 0.41.0 and is a separate
issue.
`CompressionCache._swap_tool_result_content` writes a cached compression
back as a string for
`role: "tool"`, which drops the client's block marker on the newest tool
result. That is a lost
breakpoint, not a 400. Not changed here; tracked in #4332.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: Chat Completions forwarding no longer
re-sends replayed
content-block `cache_control` markers the client did not send this turn.
- Kill switch / disable path: none (bug fix; output is the client's own
marker layout)
- 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

Co-authored-by: Thomas Bartik <22518863+tbartik@users.noreply.github.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-11-03 22:57:17 -06:00
Mansurshakh JaparovandJD Davis 9553d4292f fix(cache): retain prefix trackers for the provider cache lifetime (#4023)
## Description

Session cleanup currently drops prefix trackers after the default
600-second session lifetime even when Anthropic's request selects a
one-hour cache TTL. Losing the tracker also loses the frozen forwarded
prefix and causes the cache-preserving overlay to replay different
bytes.

Closes #4017.

## Type of Change

- [x] Bug fix
- [x] Documentation update

## Changes Made

- Resolve the request's existing Anthropic cache TTL before selecting
the prefix lineage and pass that TTL through tracker selection/creation.
- Retain each lineage for the greater of the configured session floor
and its observed/current provider TTL plus the existing 60-second safety
margin.
- Keep the lifetime per lineage rather than changing global
configuration: a five-minute session does not inherit another session's
one-hour lifetime.
- Preserve normal expiry beyond the provider lifetime and margin.
- Honor configured cache TTL before a confirmed cache write; discard
expired state before accepting a later request's longer TTL.
- Re-register the live lineage family after lookup/cleanup so recreated
sessions cannot share a tracker's frozen state across sibling
conversations or tool profiles.
- Update existing fake callbacks to the changed tracker contract,
preserve all consumer byte-stability assertions, and remove one
handler-to-store wiring-only test rather than re-pinning its internal
identity assertions.
- Document local tracker retention separately from provider cache
availability.

## Testing

- [x] Unit tests pass (`pytest`), including frozen-prefix byte stability
and independent TTL expiry.
- [x] Changed-file lint, configured pre-commit mypy and manual
production timestamp/overlay checks pass.

### Test Output

```text
Review correction: 273 passed, 2 dependency warnings in 83.79s
{"expires_beyond_provider_ttl_and_margin": true, "five_minute_session_evicted": true, "forwarded_prefix_byte_exact": true, "initial_frozen": 1, "one_hour_session_retained": true, "resolved_ttl_seconds": 3600, "resumed_frozen": 1, "same_tracker_after_660s": true}
```

The mandatory pre-push `make ci-precheck` passed: workspace Rust
fmt/clippy/tests, native extension build/import verification, the
complete configured Python gate, and Commitlint. The native gate
explicitly used the installed CPU `libonnxruntime.so.1.26.0` via
`ORT_DYLIB_PATH`, without skipping cached-model assertions.

```text
[build_rust_extension] headroom._core build + install + verify: OK
================== 177 passed, 4 skipped, 1 warning in 12.87s ==================
✅ ci-precheck PASSED — safe to push.
```

```sh
python -m pytest -q tests/test_cache/test_prefix_tracker.py
python -m pytest -q tests/test_proxy_anthropic_cache_stability.py tests/test_cache_prefix_overlay.py tests/test_cache_ttl_preserved.py tests/test_cold_prefix.py
```

**74 passed** in tracker tests; **54 passed** in request/cache tests
(one existing Starlette TestClient deprecation warning). Two new
regressions fail on baseline because the request TTL is not accepted; a
separate production runtime comparison demonstrates the actual pre-fix
loss, not just the missing parameter.

After rebasing onto current main
`1ad92f0cbc3dea27676e253588100f64a2af6994`, ran those suites together
with `tests/test_prefix_tracker_client_rewrote_reply.py`,
`tests/test_cache_mode_delta_marker.py`, and
`tests/test_content_router_mcp_small_result.py`: **150 passed**. The
actual production timestamp/byte-retention smoke was repeated
successfully on the rebased code, covering compatibility with main's
newly merged client-reply normalization.

Review regression and affected HTTP-consumer suite: **273 passed**,
including tracker expiry, Anthropic/OpenAI cache stability,
byte-faithful forwarding, header isolation, buffered timeouts, CCR
injection, and immutable system prompts. All affected two-argument test
callbacks now accept the TTL contract. The obsolete walker-call-order
test was removed; wire-byte assertions remain. The new
configured-TTL/expiry cases fail against the published baseline; the
post-cleanup regression also verifies that an unrelated conversation
gets a different tracker after recreation.

Changed-file Ruff, formatting, installed pre-commit `mypy headroom`, and
Commitlint hooks passed. Full-tree Ruff is locally blocked by executable
filesystem permissions on five unchanged OAuth2 plugin files (tracked
100644). A separate full dev-environment mypy run found an unchanged
optional LangChain `truthy-function` error; the configured isolated
pre-commit hook passed. No unrelated source/permissions changed.

## Real Behavior Proof

- Environment: Linux x86_64, CPython 3.13.14; unchanged
`dea9092e19385f286b7f67a64f4d85de2708d756` and this branch; real
`SessionTrackerStore`, `PrefixCacheTracker`, request TTL parser, token
estimator and `overlay_cached_prefix`, no mocked store or mocked clock.
- Exact command / steps: parse `cache_control: {type: ephemeral, ttl:
1h}` for `claude-sonnet-4-5`; establish one real cache-write-confirmed
frozen message with different original/forwarded prefix bytes; age
`_last_activity` to `time.time()-660` and make periodic cleanup due;
resume the same lineage and compare the tracker, frozen count, and
forwarded-prefix bytes. Also age beyond 3901 seconds and compare
independent 300/3600-second sessions.
- Before: resolved TTL 3600; after 660 seconds, tracker identity
changes, frozen count drops **1→0**, and forwarded-prefix bytes differ.
- Observed result: after the fix, after 660 seconds the same tracker
remains, frozen count stays **1**, and forwarded-prefix bytes are
identical. The one-hour session survives independently, the five-minute
session expires, and the one-hour lineage still expires beyond TTL plus
margin.
- Review runtime proof against published head `e1a107df`: actual stores
and prefix overlays confirm configured TTL retention before the first
cache write, no resurrection of expired state by a later one-hour
request, eventual expiry, and separate trackers after the maintainer's
3901-second cleanup/recreation sequence. On that exact baseline the
unrelated lookup reuses the wrong tracker, although the overlay guard
preserves the particular unrelated input bytes; after the fix both
identity isolation and byte preservation hold. Identical messages under
different tool profiles also receive a cold, separate tracker after the
expired bare-key transition.
- Not tested: Anthropic cloud cache availability, billed savings, or an
actual one-hour wait. The local production state and byte invariants
were exercised by aging actual timestamps, not by a paid upstream
request. Preserving a tracker cannot guarantee that the provider retains
its cache.

## Runtime Rollout Safety

- Rollout-managed feature(s): none; repair of existing TTL-aware
cache-prefix behavior.
- Minimum rollout channel: stable; no rollout-managed feature is
enabled.
- Stable/default behavior changed: eligible local prefix trackers
survive for their provider cache lifetime. Short-TTL/default sessions
remain bounded by their own session floor.
- Kill switch / disable path: the existing prefix-freeze disable path
remains available; no new flag.
- Unsafe override required: no.
- Qualification impact: local Anthropic prefix lineage
selection/retention, not cache pricing or subscription quota policy.
- Rollback path: revert the commit to restore previous retention. No
persistent schema change.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] Existing cache TTL parser and safety margin reused; cache docs
updated.
- [x] Regressions cover frozen-byte retention, expiry, mixed lifetimes,
and existing request byte-stability behavior.
- [x] `CHANGELOG.md` not edited; Conventional Commit title supplied.

Remote CI results are not inferred from local verification.

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-10-07 17:46:21 -05:00
a6d6c14cf7 fix(proxy): keep cache_control outside content blocks where the Chat Completions client put it (#3895)
## Description

Chat Completions clients that reach Anthropic models through a gateway
(OpenCode via `@ai-sdk/openai-compatible`, then LiteLLM) do not mark
content blocks. They mark the message dict and the entries of an
assistant's `tool_calls`, and move those markers to the newest messages
on every call. `handle_openai_chat` replays earlier turns' forwarded
messages byte-identical: `finalize_turn` in every mode, plus
`_restore_frozen_prefix` in cache mode. The markers those messages
carried back then come along with them.

`normalize_message_cache_control` exists for exactly this accumulation,
but it only handles block-level markers, and this handler does not call
it after its replays. A client sending three markers per step (system,
newest tool call, newest tool result) gets four forwarded, then six, and
the gateway fails with `A maximum of 4 blocks with cache_control may be
provided. Found 6`, which breaks every tool turn of three or more steps.
`enforce_cache_breakpoint_budget` does not catch it either:
`count_cache_breakpoints` does not count `tool_calls` markers, so it
sees four.

This adds `mirror_client_message_cache_control`. It applies the rule the
block-level normalizer already applies (the client's current request
decides where markers go) to the two places it does not see:

- on each message, and on each entry of its `tool_calls`, drop the
marker unless the client put one there in this request;
- where the client did, copy the client's own value;
- leave content untouched, so the replayed bytes the provider cached
stay identical.

The handler applies it once, after both replays.

Closes #3894

## 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/cache/prefix_tracker.py`: new
`mirror_client_message_cache_control(messages, client_messages)` (and a
small `_mirror_marker` helper).
- It touches only markers on the message dict and on `tool_calls`
entries; block-level markers stay with
`normalize_message_cache_control`.
- It returns the input list unchanged when nothing moved. When the
message lists, or one message's `tool_calls`, are not index-aligned,
that part is left as-is: it does not guess.
- `headroom/proxy/handlers/openai.py`: call it in `handle_openai_chat`
after the cache-mode restore/replay block, before memory injection, with
`original_client_messages`.
- `tests/test_openai_message_level_cache_control.py`:
- 7 unit tests for the helper: stale message and `tool_calls` markers
dropped, the client's value (including `ttl`) copied verbatim, identity
when there is nothing to do, block markers ignored, misaligned messages
or `tool_calls` left unchanged;
- 1 handler test, parametrized over `cache` and `token`, that drives
`/v1/chat/completions` with the exact OpenCode shape (system, newest
tool call and newest tool result marked) and a tracker holding last
step's compressed forward.

## 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_openai_message_level_cache_control.py
9 passed

# the handler test on main, without the fix (both modes):
E   AssertionError: assert ['0', '2.0', '3', '4.0', '5'] == ['0', '4.0', '5']

$ pytest -q tests/test_proxy/*.py tests/test_*openai*.py tests/test_*prefix*.py tests/test_*cache*.py \
    --deselect tests/test_proxy/test_issue_3650_router_emits_visible_retrievable_sentinel.py
2 failed, 1455 passed, 5 skipped
# FAILED tests/test_proxy/test_cc_switch_reconciler.py::test_switching_provider_recaptures
# FAILED tests/test_proxy/test_cc_switch_reconciler.py::test_official_resets_a_captured_third_party_upstream
# Both fail identically on main without this change:
# `pytest tests/test_proxy/test_cc_switch_reconciler.py` → 2 failed, 14 passed.

$ ruff check <changed files> && ruff format --check <changed files>
All checks passed!
3 files already formatted
```

## Real Behavior Proof

- Environment: OpenCode 1.18.30 → `headroom proxy` 0.39.1 → LiteLLM
proxy → AWS Bedrock `bedrock-claude-sonnet-4.6`, in a Kubernetes pod,
with pass-through taps before and after the proxy counting every
`cache_control` (message dict, content blocks, `tool_calls`). This
change was applied to 0.39.1 (the two changed files dropped over the
installed package) and run as a second proxy in the same pod. Plus the
four requests captured from that session, replayed against a mock
upstream.
- Exact command / steps: a turn asking for `date`, `uname -r` and
`nproc` through the bash tool, one after the other: five requests, the
last three after a tool result.
- Observed result: stock 0.39.1 forwards 6 markers on the fourth request
where the client sent 3, and Bedrock answers 400; with this change it
forwards exactly the client's 3 and the whole turn completes, in both
cache and token mode. Details:

  | Build (live, Bedrock) | Request 4 forwarded (client sent 3) | Turn |
  |---|---|---|
  | stock 0.39.1, `cache` | 6 → 400 `Found 6` | fails |
| 0.39.1 + this change, `cache` | 3 (system, 4.tc0, tool#5) | all 5
requests 200, answer returned |
| 0.39.1 + this change, `token` | 3 | all 5 requests 200, answer
returned |

Replay of the captured requests, markers forwarded for requests 1 to 4:

  | Build | Forwarded (client sent 3 / 2 / 3 / 3) |
  |---|---|
  | 0.37.0 | 3 / 2 / 3 / 3 |
  | `main` (`0a2c80d5`) | 3 / 2 / **4** / **6** |
  | this branch | 3 / 2 / 3 / 3 |

- Not tested: this branch installed as a package (live runs used 0.39.1
with these two files patched in, because that is the version the
deployment ships); non-OpenCode Chat Completions clients.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a (stable)
- Stable/default behavior changed: yes, narrowly. On
`/v1/chat/completions`, `cache_control` on the message dict and on
`tool_calls` entries now matches the client's current request instead of
accumulating from replayed turns. Content and block-level markers are
unchanged.
- Kill switch / disable path: none new; revert the PR
- Unsafe override required: no
- Qualification impact: none expected. The provider keys its cache on
content, not on marker placement (the premise
`normalize_message_cache_control` already relies on), and the client's
own positions are the ones it would have sent without the proxy.
- Rollback path: revert this PR; no state, schema or config migration
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

- `mypy headroom` could not run in my environment: it stops in numpy's
stubs (`Type statement is only supported in Python 3.12`) before it
reaches this code.
- No documentation change: this restores the behaviour the existing
docstrings already describe for block-level markers.
- Follow-up, not in this PR: `count_cache_breakpoints` does not count
`tool_calls` markers, so the last-stop guard under-counts for these
clients (it saw four where six went out). Teaching it to count them also
means teaching the repair step to remove them, so I kept it separate.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-01 12:16:26 -05:00