Commit Graph
3 Commits
Author SHA1 Message Date
94a99ed20f feat(proxy): give turn hooks one conversation id per client conversation (#4496)
## Description

Plugins that pin wording per conversation (headroom-condense, and
through it skill-search and tool-search) cannot see a real conversation
id. Today:

- **Claude:** they hash the first typed prompt, so two sessions that
open with the same words share a key.
- **Codex:** they get no key at all, so every new skill or MCP
description waits out the one-hour hold.

This PR adds an optional `TurnContext.conversation` that core fills from
the client's own conversation id, so hooks can pin per real
conversation. It is item #4 of the compression-gaps plan; the plugin
work for #3, #6, #8 and #9 needs it to stay cache-safe.

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

- **New field:** `TurnContext.conversation: str | None = None`. It is an
opaque key that stays the same for every turn and retry of one client
conversation, or `None` when the client names none. Hooks get a digest,
never the raw id.

  | Path | Source |
  | --- | --- |
| `/v1/messages` | sha256 of `X-Claude-Code-Session-Id` (Claude Code
sends it on every request), falling back to `X-Headroom-Session-Id`;
each source has its own namespace |
| `/v1/responses` (HTTP and WebSocket) | the new
`turn_conversation_key`, computed from the body before compression and
passed through `_compress_openai_responses_payload_in_executor` |
  | `/v1/chat/completions` | `X-Headroom-Session-Id` only |
| `/v1/compress` (gateway) | the gateway session id; `None` without one
|

- **Responses key.** `turn_conversation_key` uses the same identity and
digest as `savings_conversation_key` (`thread_id` before `session_id`,
then `client_metadata.*`, then the session header). Unlike the savings
key, it also applies on `previous_response_id` turns and on bodies that
name a server-side `conversation` (a string, or an object with an `id`),
so the key does not drop out after the first WebSocket frame.
`savings_conversation_key` keeps its existing exclusions.
- **Gateway seam.** `CompressTurn.prepare()` is a third-party seam, so
its signature is unchanged. Instead, the handler sets an optional
writable `conversation` attribute on the turn before calling `prepare`.
This is documented in `compress_turn.py`.
- **No new ids.** Nothing is generated. The per-connection WebSocket
uuid is not used, because a reconnect would change it.
- **One path left out.** The catch-all passthrough Responses route still
passes `None`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`): 3 errors, all in files
this PR does not touch (embedders, model_metadata, langchain)
- [x] New tests added for new functionality
- [x] Manual testing performed

- **New tests:**
  - `tests/test_turn_context_conversation.py`:
- Anthropic: the same session gives one key, a different session with
the same prompt gives a different key, the fallback header gets its own
key, and no header gives `None`.
- Responses HTTP: the same thread gives one key, including on a
`previous_response_id` turn, and a different thread gives a different
key.
- Responses server-side `conversation`: string and object forms give one
key across turns; a different conversation gives a different key; the
savings key stays `None`.
- Responses WebSocket: first and later frames share one key; a different
thread gets a different key.
    - Chat Completions: covered the same way.
- `tests/gateway/test_contract_request_half.py`: per-session gateway
keys, and `None` without a session.
  - Every new test fails on `main`.
- **Updated test:** `tests/test_proxy_openai.py` now pins
`conversation=None` for a body with no ids.

### Test Output

```text
pytest (turn hooks, gateway, Codex WS lifecycle, proxy openai, conversation savings, passthrough, hook usage): 411 passed, 5 skipped
after the server-side conversation fix, on the synced head: 101 passed (conversation, gateway, Responses suites)
ruff@0.17.0 check / format --check: clean
mypy headroom --ignore-missing-imports: 3 errors, none in changed files
```

`tests/test_turn_hook_usage.py` needs
`LITELLM_LOCAL_MODEL_COST_MAP=True` in a fresh venv; that is an existing
litellm price-map fetch, and it fails the same way on `main`.

## Real Behavior Proof

- Environment:
  - macOS 27.0.1 (Darwin 27.0.0, arm64), Python 3.12.13.
- The proxy ran from this branch in a fresh `uv` venv (`uv venv -p 3.12
&& uv pip install -e ".[dev]"`) on 127.0.0.1:9100, with default
`ProxyConfig` (optimize on).
- Upstream was the real Anthropic API, with my own API key passed by
environment variable.
- Client was Claude Code 2.1.311 (`claude --version`) with `--model
claude-haiku-5-5`.
- Exact command / steps:
1. Start the proxy with a scratch-only launcher (not committed). It
calls `register_turn_hook()` with a hook whose `on_request` appends
`ctx.provider`, `ctx.model`, `ctx.conversation` and `len(ctx.messages)`
to a JSONL file, then calls `run_server(ProxyConfig(host="127.0.0.1",
port=9100))`. Run it with `PYTHONSAFEPATH=1 HEADROOM_TELEMETRY=off
LITELLM_LOCAL_MODEL_COST_MAP=True python run_proxy.py hooks.jsonl`, from
a directory outside the repo.
2. Point Claude Code at the proxy: `export
ANTHROPIC_BASE_URL=http://127.0.0.1:9100 CLAUDE_CONFIG_DIR=<fresh empty
dir>`.
3. Start two sessions with the same prompt: `claude -p "say hi" --model
claude-haiku-5-5 --output-format json`, run twice. Note each
`session_id`.
4. Add two more turns to session 1: `claude -p "now say bye" --resume
<session 1 id> --model claude-haiku-5-5`, then `claude -p "one more word
please" --resume <session 1 id> --model claude-haiku-5-5`.
5. Read `hooks.jsonl`, and compare each key with sha256(`claude-code\0`
+ session_id).
- Observed result (from `hooks.jsonl`, keys truncated):

  | Session | Turn | Messages | `ctx.conversation` |
  | --- | --- | --- | --- |
  | `305d64a9…` | first | 2 | `306306eeb9bc164b…` |
  | `4e50609f…` (same prompt) | first | 2 | `4a9e51bc7f8005f2…` |
  | `305d64a9…` | first `--resume` | 4 | `306306eeb9bc164b…` |
  | `305d64a9…` | second `--resume` | 6 | `306306eeb9bc164b…` |

Each key equals sha256(`claude-code\0<session id>`) of the session id
that Claude Code reported. All three runs answered normally, and the
proxy log had no errors.
- Not tested:
- Codex over Responses HTTP or WebSocket (unit and handler tests cover
these).
  - Chat Completions with `X-Headroom-Session-Id`.
  - The `/v1/compress` gateway path.
- The server-side `conversation` body form, live (covered by the handler
test).
  - The `X-Headroom-Session-Id` fallback on `/v1/messages`.
  - Claude Code `/compact` and subagents.
  - Bedrock and Vertex upstreams.
  - Linux and Windows.
- A real plugin consuming the key. That is wired in
headroomlabs-ai/headroom-condense#7; skill-search and tool-search
adoption comes next.

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: stable.
- Stable/default behavior changed: no request or response bytes change.
Registered turn hooks receive one new optional field; hooks that do not
read it behave as before.
- Kill switch / disable path: none needed; a hook that should not use
the key ignores it (headroom-condense falls back to its previous key
when the field is `None` or absent).
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this PR. Plugins read the field with `getattr`,
so they keep working on cores without it.

Cache note: compare keys only within one endpoint, since the same header
gives different keys on `/v1/messages` and `/v1/responses`. Each key
comes from a client id that stays the same for the whole conversation
(Claude Code session ids survive retries, `--resume` and `/compact`;
Codex `thread_id` wins over `session_id`, so guardian and subagent
requests do not collide), and the Responses key is taken before
compression rewrites the body, so a pinning hook keeps the same pin on
every turn.

## 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] I have made corresponding changes to the documentation
- [ ] 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 (proxy-side change).

## Additional Notes

- "No new warnings" is unchecked because the run was not compared
warning by warning against `main`.
- Follow-ups: skill-search and tool-search switch to
`conversation_for(ctx)` once headroom-condense#7 is released.

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


## Maintainer post-merge qualification
Published `819f82117a4737de621528e9c49aee6aeeb4a793` includes upstream
main `e4a60ed72f6ef5b28569f8bfbe2163cfda32c948`. 28
conversation/Responses/per-frame-memory/disconnect tests pass;
Ruff/format/diff pass. Clean main merge; hook conversation policy
unchanged, no new code finding. Author explicitly reserves unchecked
self-review/readiness attestations; existing hold remains. Contributor
correctness logic was not rewritten. Existing Changes Requested decision
retained without duplicate findings. Scoped Windows validation uses the
existing development native extension, not a fresh build. Hosted
qualification is handled by maintainers; nothing merged.


### Maintainer current-main requalification

Exact head `965ff21ffbea9b446e5e39269812bb0d8c43c108`, upstream main
`ecbaf86d78cf52d185fbffa306157b9a4cc1b906`.

Mechanically updated from upstream/main
ecbaf86d78 with no conflicts and no
contributor conversation/ownership policy changes. Re-reviewed current
discussion and the integration delta. All 38 focused
conversation-context, Responses, per-frame WebSocket memory, disconnect
and Gemini tests pass; Ruff0.17.3 lint/format and whitespace checks
pass. Existing runtime evidence remains scoped; local tests use the
existing native extension, not a fresh build.

No new source blocker was found. The existing readiness action remains:
the author has explicitly reserved and still not checked the self-review
and ready-for-human-review attestations. They are not asserted on the
author's behalf. Preserve the existing Changes Requested readiness hold
until the author completes that action. Maintainers handle exact-head
hosted checks; no contributor CI action requested. Nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `db69aa725d085d75b0881f0b2e1f2237480ee0c6`, upstream main
`8d3e9e5ca7cd645eb73084b848edbea5fc796e1a`.

Clean mechanical sync with upstream
main8d3e9e5ca7cd645eb73084b848edbea5fc796e1a. Re-reviewed
conversation-context integration and fresh author/Devin discussion
without changing contributor identity/ownership
policy.38conversation/Responses/per-frame-WebSocket/disconnect/Gemini
tests pass;10changed Python files pass Ruff0.17.3check/format and
whitespace checks. Existing runtime evidence remains scoped; copied
extension supports Python startup, not a fresh native build.

No new source blocker found. The current body still leaves author
self-review and ready-for-human-review attestations unchecked and
reserves those actions for the author. Preserve that existing readiness
hold; no boxes were ticked or attested on their behalf. This is not an
inherited-main CI defect. Maintainers handle exact-head hosted checks;
nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `7411de5607beabfcbbd63b134795b0053da0e681`, upstream main
`7592e681459f14a2041eb5f524a658cb6ad1dd92`.

Clean current-main
sync7592e681459f14a2041eb5f524a658cb6ad1dd92,including
latestmemoryfixes. Conversationidentity/ownership
policyunchanged.46conversation/Responses/perframeWS/disconnect/memory-regression/Gemini
tests pass;whitespace passes. PriorRuff0.17.3check/format applies to
unchangedPRfiles.
Freshbodystillreservesuncheckedself-review/ready-for-humanreviewboxesfortheauthor.

No
newsourceblockerfound;retainexistingauthor-readinessholdwithouttickingboxesonbehalf.
Existingruntimeevidence scoped,no freshnativebuildclaim.
Maintainershandlechecks;nothingmerged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `cdf48ae9561dd2075625a4085594ac429a421231`, upstream main
`2d3ee51846435ef5b320eea4806af14e602b0d8c`.

Clean integration with upstream/main
2d3ee51846 after the external 0.43.1
release merge. Exact headroom/crates/tests comparison against previously
reviewed 7411de560 shows no changes. Re-reviewed generated metadata; 78
release/version/MCP tests pass on this tree and whitespace passes.
Earlier 46 conversation/Responses/WebSocket/disconnect/memory/Gemini
passes remain scoped to unchanged inputs.

No new source blocker found in reviewed scope. Existing author-owned
readiness declaration remains the hold; fresh body must be checked
before publication without checking author attestations on their behalf.
No contributor identity/ownership policy rewritten, no fresh
native-build/provider claim. Maintainers handle checks; nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `d343c187f73b6a9005f0268e280ec657f435f1df`, upstream main
`ea59ac3eef3a3dc02076e9fe4bb30d572ca9c1a9`.

Clean integration with upstream/main
ea59ac3eef after the Click/macOS setup
merge. Re-reviewed the OpenAI response replay transport-header overlap;
conversation and existing tool-name map parameters remain additive.14
conversation/context-compaction tests and3 targeted route/gateway cases
pass (71 unrelated cases deselected); Ruff and whitespace pass. No new
source blocker found. Fresh body still leaves author-owned
self-review/readiness attestations unchecked; preserve the existing hold
without attesting on their behalf. Existing wider runtime evidence
remains scoped; no fresh native-build or live-provider claim.
Maintainers handle hosted checks; nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `741582654b9d0817ca8318af6aaf2dd000d1ec81`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Final post-Dependabot requalification against upstream/main
c01cf07d94. All six Dependabot updates are
now merged. Relative to this branch's freshly tested prepared tree, the
final main sync changes only the three intended Cargo.lock records;
Python/source/test inputs are unchanged. Re-reviewed the integration and
confirmed complete native source/lock/toolchain objects match the tested
combined build and exact fresh native DLL used for this branch's local
tests.

Focused fresh-native qualification: 18 passed, 70 deselected, 1 warning
in 20.19s. Selected real dependency overlays and native DLL paths are
recorded in final4496-fresh-native-tests.log; the DLL provenance/input
hashes are in final-native-artifact-proof.json. No redundant rerun is
implied after this Cargo-only merge. Whitespace passes. Prior source
review and scoped real-behavior evidence remain applicable to unchanged
contributor inputs.

No new source blocker found. Fresh body still leaves author self-review
and ready-for-human-review attestations unchecked. Retain the
author-owned readiness hold without checking those boxes on their
behalf.

Maintainers handle hosted checks; no external-provider claim,
contributor semantic rewrite or non-Dependabot merge.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `cb5c34b6221880a811dd94d21c5e3f3e874ee565`, upstream main
`da6d9736cd82074988c7d0a2360b49d9d8b6c0a0`.

Current-main requalification against
da6d9736cd. All69 integration patches
exactly equal c01cf07-to-current-main delta after diff-location
normalization; conversation identity/ownership policy unchanged.88
conversation,Responses context-compaction,OpenAI route,gateway
request-contract tests pass;1 deprecation warning. Post-suite PyTorch
cache-stat logging reports closed-stream logging errors during process
exit; pytest exit0 and test results are retained without claiming full
runtime qualification.31 changed Python files pass Ruff lint/format;
offline lock and whitespace pass. Existing pr3982 native DLL verified
full input hashes/artifact checksum, no fresh build claimed.
Author/Devin discussion considered; previous substantive Devin findings
resolved. No new source blocker found. Author explicitly reserves
self-review/ready-for-human-review attestations and both remain
unchecked; retain existing readiness hold without attesting on their
behalf. Maintainers handle hosted checks; no contributor logic rewrite
or merge.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `951bdf5853aaf8757ba46253763c91b6601b5c6d`, upstream main
`0ddaa56c21cdc01c4774391fdcc69e987ecc4e5c`.

Clean integration with upstream/main
0ddaa56c21. All 19 integration patches
exactly match the prior-reviewed-main da6d9736 to current-main delta
after diff-location normalization; conversation identity/ownership
policy is unchanged. Fresh conversation/turn-hook/Responses/gateway
request-contract, doctor and incoming Vertex/backend/CLI suite: 367
passed, 11 skipped, 1 warning. Fourteen changed Python files pass Ruff
lint/format; offline lock and whitespace checks pass.

Author discussion and Devin findings read: both historical Devin items
are marked resolved, including server-side conversation IDs. No new
source blocker found. Existing author-reserved
self-review/ready-for-human-review attestations remain a hold; this
maintainer does not attest on the author's behalf. Static source/test
scope and security inspection found no new workflow/dependency/setup
path; the inherited flagged workflow-validation job is excluded by this
exact PR's unchanged workflow paths. Conversation digests are not an
authentication boundary. Verified recorded native input-set/hashes and
artifact checksum before DLL reuse; no fresh build or new live-client
qualification claimed. Maintainers handle exact-head hosted checks; no
PR merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-11-09 14:56:34 -06:00
33f067a243 feat(proxy): add lossless /v1/compress mode and detect provider by wire shape (#4617)
## Description

Two gaps stop a gateway from using `/v1/compress` well. Both showed up
while fixing LiteLLM's `headroom` guardrail, which is the follow-up PR
that needs this one.

1. **No mode compresses messages losslessly without markers.** A gateway
with no retrieval loop can't resolve a marker or call
`headroom_retrieve`, so it needs a mode with nothing to retrieve. The
existing marker-free modes still run lossy compressors.
2. **Hooks guess the provider from the model name.** A gateway can send
any client's shape to any model. Claude Code's Anthropic body routed to
Gemini looked like OpenAI, so skill condensing found nothing to change.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)

## Changes Made

**`config.mode="lossless"`**
- Runs format-native folds only, with no markers and no CCR store
writes. A registered lossless provider still applies.
- Turns off stale-Read pointers, which drop the file body and need the
retrieval tool.
- Turns off cross-turn dedup pointers, which a client that never numbers
its messages can't resolve.
- Scope: the guarantee covers message compression (lossless codecs, no
CCR). On a gateway turn, tool schema compaction and registered turn
hooks still run as configured, as in every other mode; description
truncation only happens when an operator sets
`HEADROOM_TOOL_DESC_MAX_CHARS`.

**`provider_for_body`**
- Hooks and the session tracker now use the body's wire shape, and fall
back to the model name when the shape proves nothing, such as plain text
with no system prompt or tools.
- Anthropic's own tool types (server tools such as
`web_search_20250305`, client tools such as `bash_20250124`) end in an
eight-digit date and count as the Anthropic shape, so a first-turn body
whose only tool is a server tool is read correctly.
- `route.provider` still follows the model.
- The cache breakpoint budget runs when either the shape or the model is
Anthropic, and never on a Responses body.
- `gateway_response_fields` loses its unused `provider` parameter, and
`RESPONSE_RECEIVED` keeps reporting the model's provider.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`, `ruff format --check .`, on the
pinned 0.17.0)
- [ ] Type checking passes (`mypy headroom`): one error, in
`headroom/integrations/langchain/chat_model.py`, which this PR doesn't
touch (local mypy 1.19.1)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
pytest tests/test_proxy_compress_endpoint.py tests/gateway tests/test_gateway_turn_unit.py tests/test_compress_route_tokenizer_by_model.py
425 passed, 4 skipped

Regression tests with the fixes removed: 8 failed, 7 passed
```

## Real Behavior Proof

- **Environment:** LiteLLM main with the follow-up guardrail change,
this branch as the sidecar, and a fake upstream that simulates prompt
caching. No real provider API was called.
- **Exact command / steps:** replayed a scripted 17-call agent session
with exact-duplicate outputs removed, once direct to the fake upstream
and once through LiteLLM and `/v1/compress`.
- **Observed result:** 0 errors, 0 rewrites of already-sent results,
`Read` and `Edit` results unchanged, about 1.3s added in total.

| Client | Prompt cost vs direct |
|---|---|
| Anthropic Messages, Claude Code cache markers | −3.9% |
| Chat Completions | −3.8% |
| Responses | −4.1% |

The script's outputs are synthetic, so treat these as a comparison
between setups, not a forecast for real traffic.

## Known limits

- The default mode and `lossy_inline` can still return a stale-Read
`Retrieve original: hash=` marker, although the docs call them
marker-free. This predates the PR and needs a separate fix. Proxy
`--lossless` has no read-lifecycle guard either, from reading the code.
- With no `ContentRouter`, `_derived_compress_pipeline` falls back to
the default pipeline, so `lossless` wouldn't hold. Production always has
a router, so only test stubs reach this.

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

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4617"
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 -->

## Maintainer post-merge revisit: main e9331b6b
Published head `e50b001bd05c9bc85405accca49cbef0e7786e51` incorporates
upstream main `e9331b6b963b5b6554f45943abed2366aaa25ea6` after #4142,
#4637 and #4641 merged. 164 endpoint/gateway/tokenizer/admission tests
pass; one json_minifier strategy assertion fails identically on actual
main e9331b6b. Ruff/format/diff pass. Import-only conflict resolved by
retaining both provider_for_body and RequestBodyTooLarge. Both existing
holds reconfirmed: lossless HTTP output removes unique description
suffix via tool_desc_compaction; Anthropic server tool with Gemini model
is classified OpenAI.

Contributor correctness logic was not rewritten. The existing Changes
Requested decision remains applicable; unchanged findings are not
reposted as duplicate reviews. Scoped Windows qualification uses the
existing development native extension, not a fresh build. Hosted checks
must finish independently; no contributor CI action requested and
nothing merged by this review.


## Maintainer post-merge revisit: main cc1eb540
Published `38b871120e318f6eaa1cb2ce16f96d4f6cc2b1e8` includes upstream
main `cc1eb5402aade58204b96b6b4b4d280cdd5456d2`. 90 gateway/tokenizer
tests pass; both existing HTTP/provider counterexamples reconfirmed.
Clean merge; Ruff/format/diff pass. Contributor correctness logic was
not rewritten. The existing Changes Requested decision remains
applicable; unchanged findings are not reposted. Scoped Windows
qualification uses the existing development native extension, not a
fresh build. Hosted checks must finish independently; nothing merged by
this review.


### Maintainer current-main requalification

Exact head `33395b5cdd7ee9facce9f97f2a3250f5e6e49cb2`, upstream main
`ecbaf86d78cf52d185fbffa306157b9a4cc1b906`.

Mechanically merged upstream/main
ecbaf86d78 without changing contributor
policy logic. Re-reviewed the combined gateway/provider delta and
existing comments. All 90 focused gateway/tokenizer tests and ten
inherited Gemini fixture cases pass; Ruff0.17.3 lint/format and
whitespace checks pass. The shared Gemini repair was already present, so
no duplicate fixture commit was added.

Both existing correctness findings independently remain on this combined
tree. An HTTP200 /v1/compress request with config.mode=lossless still
drops UNIQUE_REQUIREMENT_AT_END from a long tool description, reporting
tool_desc_compaction. An Anthropic web_search_20250305 tool body with a
Gemini-named model still returns provider openai. Existing requested
semantic fixes/regressions remain necessary; maintainers are handling CI
and no contributor CI execution is requested. No contributor logic was
rewritten and nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `4c40adb53a68f382e32f00620adcfaf1cff477f5`, upstream main
`8d3e9e5ca7cd645eb73084b848edbea5fc796e1a`.

Clean mechanical sync with upstream
main8d3e9e5ca7cd645eb73084b848edbea5fc796e1a including intervening
release/runtime/cache/CCR/SSE/HTTP1.1 merges. No contributor
gateway/provider policy rewritten. Fresh author/Devin discussion
considered.100focused gateway-contract/tokenizer/Gemini tests
pass;7changed Python files pass Ruff0.17.3check/format and whitespace
checks pass. Last main delta after test start changes only
Rust/OpenClaw, leaving tested Python inputs unchanged.

Both existing blockers remain freshly reproduced from this worktree
(source import path verified): real app POST/v1/compress lossless
returns200 but drops UNIQUE_REQUIREMENT_AT_END from tool description via
tool_desc_compaction; Anthropic server-tool wire shape with Gemini model
returns provider openai. Preserve promised lossless content and classify
server-tool wire forms correctly, with regressions. No external provider
session/nativebuild claimed. Copied extension supports Python startup;
maintainers handle hosted checks. Nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `8b7b2b0d02daf1a031828ecb13095ab315431f7e`, upstream main
`917edc62230c3c4a8a415e2053da68dab1f003dd`.

Current-main integration against917edc62230c3c4a8a415e2053da68dab1f003dd
is clean. Compared entire headroom/crates/Python manifests+lock/tests
inputs to prior qualified4c40adb53: byte-identical. Intervening changes
are reviewed npm maintenance and release-envelope recovery workflow; no
contributor gateway policy changed.75new-base
release-workflow/normalizer tests pass,whitespace passes.
Prior100gateway/tokenizer/Gemini results remain scoped to those
identical inputs rather than relabeled fresh.

Both gateway blockers freshly rechecked from worktree: Anthropic
server-tool+Gemini body classifiesopenai; actual lossless/v1/compress
returns200 but drops unique description suffix via tool_desc_compaction.
Retain existing losslessness/classification corrections. No fresh
nativebuild/provider claim. Maintainers handle exactheadCI;nothing
merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `490ff6defdebddda9106e9e143d42d1e463b6324`, upstream main
`7592e681459f14a2041eb5f524a658cb6ad1dd92`.

Clean integration with upstream/main
7592e68145. Reviewed both intervening
memory fixes and fresh PR discussion. Gateway/runtime/Rust inputs are
unchanged from the previously reviewed head; only the two main memory
fixes and their regressions enter this merge. Nine memory/Gemini
regression tests pass; main-relative whitespace passes.

Fresh actual-app probes retain both existing blockers: Anthropic
server-tool content with a Gemini model classifies as OpenAI; lossless
/v1/compress removes the unique tool-description suffix through
tool_desc_compaction. No contributor policy was rewritten. Existing
native extension used for Python startup, not a fresh native-build
claim. Maintainers handle hosted checks; nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `d3cb3a02af03991a696461160ee0db322dd8bf48`, upstream main
`2d3ee51846435ef5b320eea4806af14e602b0d8c`.

Clean integration with upstream/main
2d3ee51846 after the external 0.43.1
release merge. Exact headroom/crates/tests comparison against prior
reviewed 490ff6def shows no changes. Re-reviewed generated release
metadata; 78 release/version/MCP tests pass on this composed tree, and
whitespace passes. Previous nine memory/Gemini regressions and fresh
gateway probes remain scoped to identical runtime inputs.

Both established blockers remain: lossless /v1/compress drops the unique
tool-description suffix, and Anthropic server-tool content with a Gemini
model classifies as OpenAI. Runtime probes were not relabeled as rerun
after this metadata-only merge. No contributor policy rewritten; no
fresh native-build claim. Maintainers handle exact-head checks; nothing
merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `e0c873630e9ffc7bc0d0d2fdd22c483b731e49a3`, upstream main
`910588e6b15ab54c4099d03703e5fa20c8abb757`.

Clean mechanical synchronization with upstream
main910588e6b15ab54c4099d03703e5fa20c8abb757, including the externally
merged runtime fixes, docs dependency update and tree-sitter lock
repair. No contributor gateway/provider policy rewritten. Current
author/Devin discussion considered. All90 gateway
contract/tokenizer-by-model tests pass on the preceding composed runtime
tree; the final dependency-only merge changes only pyproject/uv.lock,
leaving those gateway/tokenizer sources unchanged. No redundant rerun on
the final merge is claimed. Changed Python Ruff lint/format and
main-relative whitespace pass.

Both existing blockers freshly reproduce on the composed runtime paths:
lossless /v1/compress returns200 but drops UNIQUE_REQUIREMENT_AT_END
from the tool description and reports tool_desc_compaction; Anthropic
server-tool content with a Gemini model is classified as OpenAI.
Preserve the lossless original payload and classify the full request
protocol consistently, with endpoint regressions for these inputs. The
main fixes do not close either defect.

Tests use the existing native core for startup, not a fresh native
build; no live provider traffic was made. Maintainers handle hosted
checks; no inherited-main pipeline failure attributed and nothing
merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `507433606f698249e546e1418928caee99d0c901`, upstream main
`7877241d84c93b3ec487e07324245838ddae85cc`.

Clean mechanical integration with
upstream/main7877241d84c93b3ec487e07324245838ddae85cc. Gateway
production/contracts remain byte-identical to the preceding reviewed
head; re-reviewed the new CLI/Hermes integration.127 gateway
request/response contract and model-tokenizer tests pass; whitespace
passes. Both existing holds freshly reproduce on this exact tree:
lossless /v1/compress returns200 while dropping
UNIQUE_REQUIREMENT_AT_END and reporting tool_desc_compaction; Anthropic
server-tool content with a Gemini model is classified as OpenAI.
Preserve the lossless original payload and classify the full request
protocol consistently, with endpoint regressions. No contributor
gateway/provider policy rewritten. Existing native core used for
startup; no fresh native build or live provider claim. Maintainers
handle hosted checks; nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `b0daece6b10f623a6e7b0dc3eb01c73e05fa3209`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Final post-Dependabot requalification against upstream/main
c01cf07d94. All six Dependabot updates are
now merged. Relative to this branch's freshly tested prepared tree, the
final main sync changes only the three intended Cargo.lock records;
Python/source/test inputs are unchanged. Re-reviewed the integration and
confirmed complete native source/lock/toolchain objects match the tested
combined build and exact fresh native DLL used for this branch's local
tests.

Focused fresh-native qualification: 127 passed, 3 warnings in 104.78s
(0:01:44). Selected real dependency overlays and native DLL paths are
recorded in final4617-fresh-native-tests.log; the DLL provenance/input
hashes are in final-native-artifact-proof.json. No redundant rerun is
implied after this Cargo-only merge. Whitespace passes. Prior source
review and scoped real-behavior evidence remain applicable to unchanged
contributor inputs.

Both existing blockers freshly reproduce using the combined native DLL:
lossless /v1/compress returns200 but removes UNIQUE_REQUIREMENT_AT_END
and reports tool_desc_compaction; Anthropic server-tool content with a
Gemini model is classified as OpenAI. Preserve the original lossless
payload and classify the complete wire protocol, with endpoint
regressions.

Maintainers handle hosted checks; no external-provider claim,
contributor semantic rewrite or non-Dependabot merge.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `ec6abc0228a93c5eab1881938041dfee344b1e3a`, upstream main
`2973ca593d2fe65c3259941fdff8009175eff456`.

Requalified after human merges #4667/#4669/#4670 against upstream main
ce42754912. All 11 integration patches
exactly match the prior-main-to-current-main delta after ignoring diff
locations; no contributor gateway/provider policy changed. Fresh gateway
request/response contracts, model-tokenizer, gateway unit,
Kompress-disable and must-keep suites: 207 passed, 3 warnings. Six
changed Python files pass Ruff lint/format; offline lock validation and
whitespace pass. Existing matching-core DLL used; native
source/lock/toolchain unchanged by these main merges, with no fresh
native build or live-provider claim. Both existing blockers freshly
reproduce: lossless /v1/compress returns 200 while removing
UNIQUE_REQUIREMENT_AT_END and reporting tool_desc_compaction; Anthropic
server-tool content with a Gemini model is classified as OpenAI.
Preserve original lossless payload and recognize complete wire protocol
with endpoint regressions. Author and Devin discussions checked;
existing findings remain actionable. Maintainers handle hosted checks;
nothing merged.
Subsequent human merge #4671 advanced main to
2973ca593d before publication; guard
stopped the old candidate. Cleanly integrated the new workflow-only
delta and re-reviewed action pinning with 62 workflow/release tests
passing. Runtime/native sources are byte-identical to the immediately
preceding 207-test and real-behavior qualification; those results apply
to unchanged inputs. All prior-main hosted results are historical for
readiness.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `9f857218486fa451ecacc675863a64bc95f45bb0`, upstream main
`2b0315b2d4b0d54947050bbdad2de9e89df06378`.

Current-main requalification
against2b0315b2d4b0d54947050bbdad2de9e89df06378 after later human
merges. All37 integration patches exactly match2973ca59-to-current-main
delta after diff-location normalization; contributor gateway/provider
policy unchanged.393gateway request/response
contracts,model-tokenizer,gateway
unit,Kompress-disable,must-keep,doctor,search tests
pass;3warnings.27changedPythonfiles pass Ruff lint/format;offline
lock/whitespacepass. Existing pr3982 native DLL verified every tracked
native-input hash/artifactchecksum;no fresh build claimed. Author/Devin
discussion checked. Both correctness blockers freshly reproduce:lossless
/v1/compress returns200while droppingUNIQUE_REQUIREMENT_AT_END and
reportingtool_desc_compaction;Anthropicserver-toolcontent
withGeminimodel classifiedOpenAI. Preserve original lossless payload and
classify full request wire protocol consistently,with endpoint
regressions. No live provider qualification,contributor logic rewrite,or
inherited-main CI fault attributed. Maintainers handle hosted
checks;nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `41b2145418db7f5980cd52e6235ab330fcd31ac0`, upstream main
`0ddaa56c21cdc01c4774391fdcc69e987ecc4e5c`.

Clean integration with upstream/main
0ddaa56c21. All 17 integration patches
exactly match the prior-reviewed-main to current-main delta after
diff-location normalization; contributor gateway/provider policy is
unchanged. Fresh gateway/tokenizer/search/doctor and incoming
Vertex/backend/CLI qualification: 455 passed, 11 skipped, 3 warnings.
Additional gateway request/response contracts and compress-endpoint
suite: 158 passed, 1 warning. Twelve changed Python files pass Ruff
lint/format; offline lock and whitespace checks pass.

Author discussion and outstanding Devin findings read. Both existing
correctness findings freshly reproduce on this exact tree: lossless
/v1/compress returns 200 but drops UNIQUE_REQUIREMENT_AT_END through
tool_desc_compaction; Anthropic server-tool content with a Gemini model
classifies as OpenAI. Existing requested corrections remain; no new
duplicate finding. Local app probes are not live provider proof. Native
DLL reused only after verifying the complete tracked input set, every
recorded input SHA256 and artifact checksum against
pr3982-c01-native-proof.json; no fresh build claimed. Maintainers handle
exact-head hosted checks. No PR merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-11-07 20:36:11 -06:00
Tejas ChopraandClaude Fable 5.1 d9757dcc6b fix(proxy): gateway turn contract for /v1/compress behind a compress-turn seam (#3605)
## Description

Adds a gateway turn contract to `POST /v1/compress`, allowing an API
gateway to submit a complete provider request and later report the
provider response. Requests without a top-level `gateway` object remain
unchanged.

## Type of Change

- [x] 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)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Adds the request half to `/v1/compress` and the response half at
`/v1/compress/response`, including bounded pending turns, idempotent
rounds, usage relay, and redrive obligations.
- Adds a reusable six-stage compress-turn extension seam and turn-hook
priority/provider-header support.
- Keeps native tool-schema deferral in the licensed extension while
sharing protocol-shape helpers with core.
- Accepts Anthropic, OpenAI chat, OpenAI Responses, and Kong-shaped
usage payloads.
- Documents the gateway contract in `docs/content/docs/proxy.mdx` and
`wiki/proxy.md`.

## 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
tests/gateway + gateway unit + turn-hook seam + test_issue_746_tool_search:
358 passed

ruff 0.16.3 lint/format and mypy on touched modules:
clean

Kong 3.9 Docker e2e (HEADROOM_KONG_E2E=1):
4 passed
```

## Real Behavior Proof

- Environment: Kong 3.9 Docker e2e and real-provider Claude Code through
Kong on SWE-bench-mini.
- Exact command / steps: `HEADROOM_KONG_E2E=1` gateway e2e;
real-provider traffic through the gateway contract with usage relay and
licensed native deferral.
- Observed result: four Kong e2e tests passed; prefix cache remained
intact with zero busts; relayed usage matched Anthropic token-for-token;
licensed tool-search deferral reduced cache-read tokens per turn by
27–30%.
- Not tested: production rollout at scale.

## Runtime Rollout Safety

- Rollout-managed feature(s): gateway contract and in-process
pending-turn registry.
- Minimum rollout channel: controlled gateway deployment before broader
enablement.
- Stable/default behavior changed: only requests containing a top-level
`gateway` object enter the new contract; ordinary `/v1/compress` bodies
are unchanged.
- Kill switch / disable path: set `HEADROOM_GATEWAY_CONTRACT=0`.
- Unsafe override required: no.
- Qualification impact: gateway callers must redeem advertised `redrive`
and `relay_usage` obligations.
- Rollback path: disable the contract with `HEADROOM_GATEWAY_CONTRACT=0`
or revert the feature 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
- [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] 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; this is an API contract change.

## Additional Notes

Pending turns are process-local and bounded by
`HEADROOM_GATEWAY_TURN_TTL_SECONDS`,
`HEADROOM_GATEWAY_MAX_PENDING_TURNS`, and
`HEADROOM_GATEWAY_MAX_REDRIVES`.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-15 16:56:07 -07:00