Commit Graph
2 Commits
Author SHA1 Message Date
Mansurshakh JaparovandJD Davis 89545fbdf3 fix(ccr): recognize client-owned MCP retrieval aliases (#4165)
## Description

Fixes #4159.

OpenCode exposes `headroom_headroom_retrieve`, but the proxy only checks
the bare `headroom_retrieve` when deciding whether the client already
owns retrieval. It therefore adds a second, unavailable client tool.
Retrieval-only proxy turns can be intercepted internally; mixed
retrieval + Read turns are forwarded to the client, which cannot execute
the bare spelling.

## Type of Change

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

## Changes Made

- Share one ownership selector between session-sticky injection and the
per-request `CCRToolInjector` fallback. Accept the bare canonical name
and the three supported default-Headroom-server client spellings.
- Do not treat another MCP server's `headroom_retrieve` suffix as
ownership of Headroom's cache. Existing broader compression-exclusion
matching is unchanged.
- Optional system instructions use the executable registered retrieval
name in the legacy path and both Anthropic/OpenAI handlers.
- Preserve client-owned aliases and bare-only proxy interception; do not
alter mixed-tool response handling or add execution of client tools.
- Add namespace/provider regressions across cold, compressed and later
turns, plus real-store instruction and foreign-server boundaries.
- Delete the incidental tool-description-size assertion and
error-message wording pin, retaining real eager/lazy/cache-stability
validation.
- Document default-server ownership, alias-only forwarding and
mixed-call behavior explicitly.

## Testing

- [x] Relevant CCR/API tests pass: 161 cases across the seven suites
below
- [x] Changed Python source/test Ruff format and check pass
- [x] Failing-before/passing-after behavioral regressions added
- [x] Actual CLI/HTTP/native before-and-after smoke performed

### Test Output

All **6** initial alias/provider regressions fail against exact upstream
main `976aa714ef3e19174dc0cb586cee7b20d064e4ef` because unavailable bare
retrieval is injected. All **10** first review regressions and **2**
additional actual-API regressions fail against immutable first-PR commit
`7601252be7e8b02297e342e2775bb153927e2fe9`: instructions name an
unavailable tool, or a foreign MCP server displaces proxy retrieval.
Current fixed result: **161 passed, 1 existing Starlette TestClient
deprecation warning** across:

```text
tests/test_ccr_tool_injection_cache_stability.py
tests/test_ccr_tool_always_on.py
tests/test_ccr_tool_injection.py
tests/test_issue_728_empty_tools_injection.py
tests/test_corrupt_golden_bytes_recovery.py
tests/test_proxy_anthropic_cache_stability.py
tests/test_proxy_openai_cache_stability.py
```

Ruff format/check passed for the four changed Python sources and three
regression files. A genuine-module-preloaded, coverage-instrumented CCR
run passed all 110 cases (four warnings); an additional instrumented API
run passed both new API regressions and measured both changed handler
instruction calls as executed. Import-time coverage is incomplete in
those local runs, so they are not whole-package or CI patch-coverage
claims. Whole-repository pytest and whole-package mypy are not claimed
by these scoped results.

## Real Behavior Proof

- Environment: Linux x86_64, Python 3.13.14; genuine installed
development/proxy extras and editable Rust extension, actual ONNX
Runtime 1.26.0 via `ORT_DYLIB_PATH`. Independent baseline/fixed
worktrees. Beacon off, isolated settings, stateless proxy, no live
credentials. Provider is a controlled local Anthropic-shaped HTTP
upstream; request model string is `claude-sonnet-4-20250514`, not a live
model run.

- Exact command / steps: start `headroom proxy --port 18858` for
baseline and `--port 18859` for fixed source, each with
`--anthropic-api-url http://127.0.0.1:45111` and:

```text
--stateless --no-cache --no-rate-limit --no-subscription-tracking
--disable-kompress --disable-kompress-fallback --no-read-lifecycle --no-telemetry
```

Optimization and CCR remain enabled. Both genuine CLI startups report
`event=rust_core_loaded`. POST the same `/v1/messages` request to each
with model above, `max_tokens: 128`, `system: "Use the available
tools."`, user text `Retrieve the original compressed data and read the
related file.`, and these client tool schemas:

```json
[
  {"name":"headroom_headroom_retrieve","description":"Retrieve original Headroom content through the client MCP server","input_schema":{"type":"object","properties":{"hash":{"type":"string"}},"required":["hash"]}},
  {"name":"Read","description":"Read a local file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}},"required":["file_path"]}}
]
```

The controlled upstream observes the actual advertised tools, selects
bare retrieval if advertised (otherwise the available alias), and
returns a mixed retrieval + Read response.

**Observed before:** upstream tools are `Read`,
`headroom_headroom_retrieve`, **`headroom_retrieve`**. HTTP 200 forwards
mixed `headroom_retrieve` + `Read`, leaving one returned tool
unavailable in the client's registry.

- Observed result: after the fix, upstream tools are only `Read`,
`headroom_headroom_retrieve`. HTTP 200 forwards mixed
**`headroom_headroom_retrieve`** + `Read`; zero unavailable returned
names. No mixed-call suppression or response rewriting hides the
problem.

- Not tested: live Anthropic, installed OpenCode end-to-end, actual CCR
hash/payload recovery, Windows or native Gemini HTTP. Per-request
fallback is exercised directly by regressions. Controlled-upstream
behavior alone is not offered as proof: this ran the real baseline/fixed
proxy CLI, HTTP path and native extension.

### Additional review behavior proof

The first PR SHA and corrected source each ran the actual proxy app
through its full lifespan, with the genuine native extension loaded,
actual `CompressionStore` and real HTTP to a controlled upstream at
`127.0.0.1:45112`. Requests entered the genuine Anthropic and OpenAI
ASGI routes, not patched handlers; this additional check was not an
external CLI socket or live-provider run.

Construct `ProxyConfig` with `ccr_inject_system_instructions=True`,
`stateless=True`, no caching/rate limiting/subscription tracking/read
lifecycle/Kompress, Anthropic URL `http://127.0.0.1:45112`, and OpenAI
URL `http://127.0.0.1:45112/v1`. After startup, store
original/compressed content in the actual in-memory store and use its
returned hash in `<<ccr:HASH 1_rows_offloaded>>`. Send a valid assistant
tool call and matching tool result to each provider endpoint, once with
only `headroom_headroom_retrieve` registered and once with only
`mcp__other__headroom_retrieve` registered. Anthropic uses
tool-use/tool-result blocks and model `claude-sonnet-4-20250514`; OpenAI
uses function tool-calls/tool messages and model `gpt-4o`. The upstream
records advertised names and names invoked by the actual injected system
instructions, then returns a normal final text response.

All eight before/after requests returned HTTP 200. Before: both
providers instructed bare `headroom_retrieve` while neither registry
contained it. After: the Headroom alias is retained alone and
instructions invoke it; a foreign server's tool is retained alongside
proxy-owned bare retrieval and instructions invoke the bare tool. **Zero
unavailable instruction names** in all four corrected requests. The
upstream and both apps were stopped afterwards.

The permanent API regressions reuse the existing full-lifespan provider
`TestClient` fixtures and a real isolated in-memory store. Only the
upstream response boundary supplies fixed provider-shaped JSON; the CCR
injector, instruction generation and ownership selector are real. Both
tests fail on the first PR SHA because the instructions name unavailable
bare retrieval, then pass after the fix. They assert executable-name and
real-hash invariants, not that a helper received forwarded arguments.
Scoped coverage measured the previously untested instruction calls in
both handlers as executed.

## Runtime Rollout Safety

- Rollout-managed feature(s): existing CCR tool-injection paths and
opt-in retrieval instructions; tool ownership and instruction naming
only.
- Minimum rollout channel: unchanged; no feature is enabled by this
patch.
- Stable/default behavior changed: stop injecting a duplicate bare
schema when the client already owns a supported retrieval alias.
- Kill switch / disable path: existing controls unchanged; no new
switch.
- Unsafe override required: none.
- Qualification impact: alias/provider/cold-to-compressed regressions,
foreign-server and actual-store boundaries, CLI/native proof and
both-provider ASGI/native/HTTP proof above; no widened rollout.
- Rollback path: revert this Python bug fix.

## Review Readiness

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

## Checklist

- [x] One shared ownership selector, broader compression exclusions
unchanged, no new dependency
- [x] Documentation updated
- [x] Consumer-visible failing-before/passing-after regressions included
- [x] Relevant new and existing tests pass locally
- [x] Did not edit generated `CHANGELOG.md`

## Mandatory Local Push Gates

Normal `git push fork fix/issue-4159-client-retrieval-alias-20261011`
executed the installed pre-push hook and **`make ci-precheck` passed**:

- `cargo fmt --all -- --check`
- `cargo clippy --workspace -- -D warnings`
- `cargo test --workspace`
- Genuine editable Rust extension build, install and import verification
- Critical Python/native parity suite: **177 passed, 4 skipped, 1
warning**
- Conventional commit validation through commitlint

The warning is the existing no-client Anthropic tokenizer approximation
reported by `test_relevance_with_query_context`; it was not suppressed.
The earlier cold-build push timed out. Retrying with the real shared
Cargo
build cache and two build jobs completed all gates and pushed normally;
no bypass flag or skipped hook was used.

The review update `440fd96aaa11c0ea9263d9628ccc2b5f8b3865d4` also
passed every normal pre-push gate above, including 177 critical Python
tests. This run used `RUST_TEST_THREADS=2`: the preceding
default-parallel
attempt failed the unchanged native
`expired_get_does_not_wipe_concurrent_refresh` test's final-live
assertion
with a 20 ms TTL. Baseline/current native source hashes are identical.
No Rust fix is claimed; no tests or gates were filtered or bypassed.

The API regression update `c5c36ba0e7074cbd815498d00ee8f394bd7287bc`
again passed all normal local push gates above with the same bounded
test/build concurrency, genuine native rebuild/import and 177 critical
Python tests. The two additional API regressions and complete
seven-suite
161-test run are separate measured verification, not mocked CCR
plumbing.

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-10-24 08:45:20 -07:00
Tejas ChopraandClaude Opus 5 bb8c285714 fix(ccr): inject headroom_retrieve before the prefix is warm, not after (#3810)
## Description

Reported by a user on 0.38.0: a full cache miss (`reason=prefix_change`)
immediately after `inject_first_time`, in almost every session.

```
req 001611  tool_injection_decision=skip               cache_read=53,420
req 001613  tool_injection_decision=inject_first_time  (headroom_retrieve added)
            CACHE-BUST expected_cached=84,416 actual_read=0
            cache_read=0  cache_write=85,611
req 001629  tool_injection_decision=inject_sticky_replay  cache_read=85,611
```

They were right, and it is not a config mistake.

`tools` is the **head** of Anthropic's cache key — the prefix is ordered
tools → system → messages — so any change to the array invalidates every
cached token behind it. `apply_session_sticky_ccr_tool` gated the first
injection on `has_compressed_content_this_turn`, so the tool enters the
array **at the first compression**: typically many turns in, against a
fully warm prefix. The idle time and the subagent hand-off in their logs
are coincidental; they just correlate with when the first compression
happens.

### The trade is not close

Their session: 113,888 tokens of cache write to save 2,205 tokens of
content. Pricing the classes against each other (read 0.1×, 5m write
1.25×):

| | |
|---|---|
| one-time bust | **130,971** base-token-equivalents |
| benefit per later turn | 220 |
| **payback** | **~594 turns of the same session** |

At Sonnet list that is **$0.393 spent to save $0.00066/turn**, and more
on Opus. PR-B7's sticky tracker already turned this from a per-turn flap
into a once-per-session event; this fixes the one that remained.

### The fix is timing, not mechanism

The definition is **~119 tokens**. Injecting it on the session's first
request folds that cost into the cache write the session was always
going to pay, and the tools array never changes again. Eager:
**$0.00045, once**. Lazy: **$0.393**.

## Type of Change

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

## Changes Made

- `headroom/proxy/helpers.py`: `apply_session_sticky_ccr_tool` gains
`allow_eager`; both branches now arm on `allow_eager and bool(tools_out)
and get_ccr_tool_injection_mode() == "eager"` instead of waiting for
`has_compressed_content_this_turn`.
- New `HEADROOM_CCR_TOOL_INJECTION` (`eager` | `lazy`, default `eager`)
with `resolve_ccr_tool_injection_mode` / `get_ccr_tool_injection_mode`,
following the `HEADROOM_TOOL_INJECTION_STICKY` precedent. An unknown
value raises rather than silently defaulting.
- New `inject_eager` member of the `ToolInjectionDecision` literal, so
the existing `event=tool_injection_decision` line distinguishes "entered
the array cold" from "entered against a warm prefix".
- Call sites pass `allow_eager` from what the request can actually do:
`not preserve_tool_order` (anthropic), `bool(self.config.optimize) and
not _bypass` (openai) — a request that will never compress is not
pre-armed.
- `tests/test_ccr_tool_injection_cache_stability.py`: new, 13 tests (10
functions, three parametrized over both providers / both empty-tools
spellings).

### Scope: only when the client already sends tools

My first cut injected eagerly always, and it broke 8 existing tests.
Rather than flip them I looked at why — one was asserting that a request
arriving with **no** tools must not gain a `tools` key. That is a real
invariant: it would let the model emit `tool_use` blocks the client
never expected (#728), and such a client has no tool results to
compress, so no warm tools segment to protect either. Narrowing eager
injection to "the client already sent tools" made **all 8 failures
disappear on their own**. The existing tests were right; the first
design was wrong.

### Safety

- A spurious call is **not an error path**: an unknown hash resolves to
a structured `{"status": "missing"}` tool result via
`CCRResponseHandler._execute_retrieval`, not an exception or a 400.
- `has_done_ccr` / `record_ccr_done` have no consumers outside the
injection path, so pinning the golden bytes early cannot mislead
anything else.

## 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
$ pytest tests/test_ccr_tool_injection_cache_stability.py -q
13 passed in 0.46s

# same file with the default flipped back to the pre-fix timing
# (CCR_TOOL_INJECTION_DEFAULT = "lazy"), i.e. the gate this PR replaces:
6 failed, 7 passed
FAILED test_tools_array_is_byte_stable_across_the_first_compression[anthropic]
FAILED test_tools_array_is_byte_stable_across_the_first_compression[openai]
FAILED test_the_tool_is_present_from_the_very_first_request[anthropic]
FAILED test_the_tool_is_present_from_the_very_first_request[openai]
FAILED test_sticky_replay_is_byte_identical_to_the_eager_injection
FAILED test_the_sessionless_path_is_also_stable
# and the diff is the bug itself - one turn's array carries
# {"name": "headroom_retrieve", ...} and the other's does not

$ pytest -k "ccr or injection or sticky or cache"
2,079 passed   (clean origin/main: 2,067 passed)
# same single failure on both: test_verbatim_read_never_cache_written_before_maturation
# pre-existing, passes in isolation; its own docstring names the cause
# (~/.headroom/ccr_store.db is shared across processes)

$ ruff check . && ruff format --check .
All checks passed!
1659 files already formatted

$ mypy headroom --ignore-missing-imports
Success: no issues found in 543 source files
```

CI on `f5b24f1d`: green.

## Real Behavior Proof

- Environment: live Anthropic API, real `create_ccr_tool_definition()`
output, 6 client tools, nothing else changed between turns.
- Exact command / steps: three turns against a warm prefix — turn 1
cold, turn 2 identical tools array, turn 3 with `headroom_retrieve`
appended and nothing else altered.
- Observed result: `turn 1 read=0 write=4,335` (cold) → `turn 2
read=4,335 write=0` (warm) → `turn 3 read=0 write=4,458`. One 478-byte
tool, entire prefix gone. This is the customer's `reason=prefix_change`
reproduced from first principles.
- Not tested: no live-API run of the *fixed* path end to end — the
post-fix evidence is the byte-identity assertion over the tools array
plus the suite, not a second live capture. My first verification sweep
also used a `-k "ccr or injection or sticky or cache"` filter that
matched nothing in `test_anthropic_stage_timings.py`, which is why CI
caught the `--no-optimize` flaw and I did not; the filter was the hole,
not the coverage.

## Runtime Rollout Safety

- Rollout-managed feature(s): CCR retrieval-tool injection timing, via
the new `HEADROOM_CCR_TOOL_INJECTION` env var.
- Minimum rollout channel: Stable.
- Stable/default behavior changed: Yes — the default changes from `lazy`
(inject at first compression) to `eager` (inject on the session's first
request, only when the client already sent tools). Deliberate: the old
default is the bug. The tool's *contents* and the sticky golden-bytes
replay are unchanged, so only the timing of the first injection moves.
- Kill switch / disable path: `HEADROOM_CCR_TOOL_INJECTION=lazy`
restores the historical gate exactly. `--no-ccr` (env `HEADROOM_NO_CCR`)
still disables CCR injection entirely.
- Unsafe override required: No.
- Qualification impact: Requests that already send tools now carry
`headroom_retrieve` from turn 1, so any fixture or assertion pinning the
turn-1 tools array for a tools-bearing request will see one extra entry.
No-tools requests, `--no-optimize`, and bypassed requests are unaffected
by construction and covered by tests.
- Rollback path: Set `HEADROOM_CCR_TOOL_INJECTION=lazy` for an immediate
revert with no deploy, or revert the commit. Nothing is persisted and
the session tracker is in-memory, so a rollback takes effect on the next
session with no migration.

## 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
- [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`

Documentation: the new env var is self-documenting in the resolver and
carries its rationale in comments; say the word if you want it in the
proxy env-var reference and I will add it here.

## Additional Notes

Known, not fixed here: on the OpenAI **chat-streaming** path
`can_inject_ccr_tool` is False, which also skips sticky replay — so a
session mixing streaming and non-streaming turns toggles the tool
repeatedly, busting the tools segment each way. Worse than the bug fixed
here because it recurs, but resolving it properly needs buffered-CCR
work rather than a timing change. Tracked as #3815; #3816 is its first
step and is independent of this PR (zero file overlap, either merge
order is fine).

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-28 16:46:44 -07:00