Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(proxy): gateway turn contract for /v1/compress behind a compress-turn seam (#3605)

Tejas Choprad9757dcc6b69
diff --git a/docs/content/docs/proxy.mdx b/docs/content/docs/proxy.mdx
index 0c5db144e..d077a6ce8 100644
--- a/docs/content/docs/proxy.mdx
+++ b/docs/content/docs/proxy.mdx
@@ -457,14 +457,15 @@ So an Anthropic-native caller does not need to convert to OpenAI format first. B
| `model` | string | yes | Model name. Drives tokenizer + context-limit resolution. `400` if missing. |
| `token_budget` | integer | no | Overrides the model's context limit. Used by callers that need to fit a tighter budget. |
| `config` | object | no | Compression options, below. A non-object value is ignored rather than rejected. |
+| `gateway` | object | no | Switches on [gateway mode](#gateway-mode-two-half-turn-contract). May be `{}`. Fields below. |
-<Callout type="warning" title="system and tools are ignored">
-Only the four fields above are read. Anthropic sends `system` and `tools` **out of band**, alongside `messages` — this endpoint accepts them without complaint (you get a `200`, no warning) and returns neither, so neither is compressed.
+<Callout type="warning" title="system and tools are ignored outside gateway mode">
+Without a `gateway` block, only the four fields above are read. Anthropic sends `system` and `tools` **out of band**, alongside `messages` — this endpoint accepts them without complaint (you get a `200`, no warning) and returns neither, so neither is compressed.
Keep carrying both yourself and send them upstream unchanged. Two consequences worth knowing:
- An Anthropic system prompt is not compressed here, even though it is resent on every request.
-- Tool-schema compaction and tool-search deferral are not reachable through this endpoint — on tool-heavy traffic those can be the largest share of available savings. Run Headroom as the proxy (rather than calling `/v1/compress`) if you need them.
+- Tool-schema compaction, tool-search deferral and output steering are not reachable this way — on tool-heavy traffic those can be the largest share of available savings. [Gateway mode](#gateway-mode-two-half-turn-contract) passes `tools` and `system` through and applies all three.
</Callout>
`config` fields:
@@ -473,6 +474,7 @@ Keep carrying both yourself and send them upstream unchanged. Two consequences w
| --- | --- | --- | --- |
| `mode` | string | unset | `ccr`, `lossy_inline`, or `lossless_then_lossy`. Unset selects the default marker-free pipeline. Any other value is a `400`. |
| `frozen_message_count` | integer | unset | Pin a prefix: the first N messages are returned byte-for-byte unchanged while staying visible to cross-message transforms like dedup. Set it to the number of messages the provider has already cached so compression cannot rewrite the prefix and bust that cache. Must be a non-negative integer; anything else is a `400`. |
+| `session_id` | string | unset | Opt into [session mode](#session-mode): Headroom keeps this conversation's replay state itself, so you can resend the raw conversation every turn and get a byte-identical prefix back. Non-empty, at most 256 characters; anything else is a `400`. Cannot be combined with `compress_user_messages` (`400`). |
| `compress_user_messages` | boolean | `false` | Also compress user-role messages. |
| `target_ratio` | number | unset | Target compression ratio. |
| `protect_recent` | integer | unset | Leave the last N messages uncompressed. |
@@ -496,6 +498,7 @@ Keep carrying both yourself and send them upstream unchanged. Two consequences w
| `transforms_applied` | array | Transform labels that ran. |
| `transforms_summary` | object | Per-transform counts. |
| `ccr_hashes` | array | Retrieval hashes for markers inserted (empty unless `mode: "ccr"`). |
+| `session` | object | [Session mode](#session-mode) only: `{ "id", "frozen_message_count", "cached_prefix_replayed" }`. |
```json
{
@@ -518,12 +521,13 @@ Keep carrying both yourself and send them upstream unchanged. Two consequences w
| Status | Body | When |
| --- | --- | --- |
-| `400` | `error.type = "invalid_request"` | Missing `messages` or `model`, malformed JSON, invalid `config.mode`, or invalid `config.frozen_message_count`. |
+| `400` | `error.type = "invalid_request"` | Missing `messages` or `model`, malformed JSON, invalid `config.mode`, `config.frozen_message_count` or `config.session_id`, `session_id` combined with `compress_user_messages`, or a malformed `gateway` block. |
| `401` | — | `HEADROOM_PROXY_TOKEN` is set and the bearer token is missing or wrong. |
| `404` | — | Non-loopback caller without `HEADROOM_COMPRESS_ALLOW_REMOTE=1`. |
| `503` | `error.type = "compression_error"` | Compression failed unexpectedly. |
+| `503` | `error.type = "compression_timeout"` | Session mode only: the turn timed out or the session's lock was busy. Retry the turn. |
-Compression **fails open on timeout**: you get `200` with your original messages, zeroed metrics, plus `compression_skipped: true` and `skip_reason: "compression_timeout"`. Always check `compression_skipped` if you need to know whether compression actually ran.
+Without a session, compression **fails open on timeout**: you get `200` with your original messages, zeroed metrics, plus `compression_skipped: true` and `skip_reason: "compression_timeout"`. Always check `compression_skipped` if you need to know whether compression actually ran. In session mode the same timeout is a `503` instead — see below for why.
Requests are recorded under `provider="compress"` in `/stats` and `/metrics`.
@@ -531,7 +535,7 @@ Requests are recorded under `provider="compress"` in `/stats` and `/metrics`.
This is the single most important thing to get right, and the default is not safe for an agent loop.
-When Headroom proxies a request itself it watches the provider's cache hit rate turn over turn and freezes the already-cached prefix. `/v1/compress` **cannot do that — it is stateless.** It sees one isolated call and has no idea what the provider already cached.
+When Headroom proxies a request itself it watches the provider's cache hit rate turn over turn and freezes the already-cached prefix. Without `config.session_id`, `/v1/compress` cannot do that: it sees one isolated call and has no idea what the provider already cached. You have two options — let Headroom keep the state ([session mode](#session-mode), below) or keep it yourself with `frozen_message_count`, which the rest of this section covers.
The provider caches the bytes you **forwarded**. Compression changed those bytes, so your original messages and the ones the provider cached are no longer the same thing — and it is the forwarded version you have to keep reproducing. Send the pristine originals again next turn and the provider sees a different prefix and re-reads it from scratch. On Anthropic a cache read is ~90% cheaper than fresh input, so that can easily cost more than the compression saves.
@@ -568,6 +572,174 @@ Also for multi-turn callers:
- **Send the real model name** so the tokenizer and context limit resolve correctly — including gateway-prefixed forms.
- **`protect_recent` is not a substitute.** It guards the newest messages; `frozen_message_count` guards the oldest, which is the cached end.
+#### Session mode
+
+Pass `config.session_id` and Headroom keeps the conversation's replay state itself — the same per-session compression cache and prefix tracker the proxy path uses — so a gateway that owns routing can resend the **raw** conversation every turn and still get a byte-identical prefix back. Whatever this endpoint previously returned for the session is treated as the provider's cache contract: every already-returned message comes back unchanged, even where recompressing it would do better, and only the new tail is compressed. An explicit `config.frozen_message_count` still wins when it is larger.
+
+```json
+{
+ "messages": [{ "role": "user", "content": "..." }],
+ "model": "claude-sonnet-4-6",
+ "config": { "session_id": "conv-8f1c" }
+}
+```
+
+The response gains a `session` object:
+
+```json
+"session": { "id": "conv-8f1c", "frozen_message_count": 12, "cached_prefix_replayed": true }
+```
+
+What differs from the stateless contract:
+
+- **Forward the returned messages verbatim.** They are what the next turn replays.
+- **`compress_user_messages` is refused** (`400`). User-message rewrites are not byte-replayable across turns, so they would bust the prefix later.
+- **Timeouts and busy sessions are a `503`, never fail-open.** Handing back originals would leave the caller forwarding bytes the replay state does not know about, so a compression timeout answers `503` with `error.type = "compression_timeout"`; retry the turn and it lands on consistent state. Turns for one session are serialized under a per-session lock, and a concurrent turn for the same session that waits more than 10 seconds gets the same `503`.
+- **State is in-process.** The replay cache lives for `HEADROOM_COMPRESSION_CACHE_TTL_SECONDS` of idle time (3900 by default, floor 600); the tracker's usage state expires after 10 idle minutes. Multi-process deployments (gunicorn workers, replicas) must pin a session to one process — hash the upstream on the session id — or replay silently misses.
+- `HEADROOM_COMPRESS_SESSION_FROM_HEADER=1` lets the `x-headroom-session-id` header stand in for `config.session_id`. Off by default: gateways commonly stamp that header on all traffic, and a value shared across conversations (Claude Code subagents do this) would blend them into one replay state.
+
+**Relaying provider usage: `POST /v1/usage`.** Session mode never sees the provider's response, so cache-hit attribution and savings accounting for the session come from this optional relay (same exposure rules as `/v1/compress`). Post the provider's `usage` block under the session id:
+
+```json
+{
+ "session_id": "conv-8f1c",
+ "usage": { "cache_read_input_tokens": 11800, "cache_creation_input_tokens": 400 }
+}
+```
+
+OpenAI-shaped usage is accepted too: `prompt_tokens_details.cached_tokens` or a flat `cached_tokens` is read as the cache-read count (OpenAI reports no write counter). A block carrying none of these fields is a `400` — it has no cache signal, and reading it as zeros would wipe the tracker's cached-prefix state.
+
+The reply is `{ "session_id": "conv-8f1c", "frozen_message_count": 12, "applied": true }`. `applied: false` with `reason: "no_cache_signal"` means the only present field was `0` (a fully cold turn can only be asserted with both fields present). `404` with `error.type = "unknown_session"` means the tracker's state for that session has expired — replay may still be active; only this telemetry landed nowhere. `503` with `error.type = "session_busy"` means a compress turn for the session is in flight; retry.
+
+The relay is telemetry only. It never raises the frozen count, because a provider-confirmed count could freeze a message whose cache entry has since been evicted. Skipping it costs attribution, never correctness.
+
+#### Gateway mode (two-half turn contract)
+
+An API gateway that owns routing (Kong, LiteLLM, a custom sidecar) never lets Headroom see the provider's response, which rules out every transform whose reload step needs it. Gateway mode splits one model turn into two HTTP calls: the **request half** (`POST /v1/compress` with a top-level `gateway` object) returns the complete provider body plus the *obligations* the gateway must redeem, and the **response half** (`POST /v1/compress/response`) takes the provider's answer and either finishes the turn or asks the gateway to call the provider again.
+
+The rule behind it is the proxy's own **no shrink without reload**, moved to the API boundary: a transform whose reload step needs the response only runs when the gateway has said it can re-drive. A body without a `gateway` key never touches any of this — stateless and session behaviour are unchanged.
+
+**The `gateway` block.** Presence is the switch: `"gateway": {}` is gateway mode with every default. Unknown keys are ignored (a newer plugin can talk to an older Headroom); a non-object block or a non-boolean field is a `400`.
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `can_redrive` | boolean | `false` | The gateway can call the provider again with a request Headroom hands it and post the result back. Unlocks re-driving turn hooks and, with `config.mode: "ccr"`, in-band CCR retrieval. Send `false` for streaming requests. |
+| `can_relay_response` | boolean | `false` | The gateway will post the provider's status and usage to `/v1/compress/response` after every turn. |
+| `session_affinity` | boolean | `true` | The gateway pins this session to one Headroom replica. Pending turns are in-process state, so `false` disables re-driving for the turn even when `can_redrive` is set. |
+| `plugin_version` | string | unset | Diagnostics only. |
+| `request_headers` | object | `{}` | The client's request headers the gateway is willing to hand over, as lowercase name → string value. Only `anthropic-beta` is read today: when a turn hook asks for an `anthropic-beta` token, the client's tokens go first in the returned `headers`; every other name is ignored, so a gateway may pass its whole header map. A non-object block or a non-string value is a `400`. Never forwarded anywhere by Headroom. |
+
+**What changes on the request half.** Every top-level field other than `messages`, `model`, `token_budget`, `config` and `gateway` passes through into the returned `body`: `system`, `tools`, `temperature`, `stream`, `metadata`, anything the provider accepts. `tools` is compacted deterministically (`tool_schema_compaction` in `transforms_applied`, plus `tool_desc_compaction` when `HEADROOM_TOOL_DESC_MAX_CHARS` is set), so identical tools come back byte-identical every turn. Two more request-only, streaming-safe levers run here exactly as they do on the proxy path:
+
+- **Tool-search deferral (Anthropic) is an extension's job on this path.** OSS core does not mark tools `defer_loading` on `/v1/compress`; the [headroom-tool-search](https://github.com/headroomlabs-ai/headroom-tool-search) extension's native tier does, through the turn-hook contract, when it is installed, enabled (`HEADROOM_PROXY_EXTENSIONS=tool_search`) and licensed. It applies the same primitives as the proxy path (12 or more Anthropic-shaped tools on a first-party Claude model, the same resident set, the same client-already-searching check, `HEADROOM_TOOL_SEARCH=0` as the kill switch), is a pure function of the input tools so the tools prefix keeps prompt-caching turn over turn, and is named `tool_search:native_deferral:<n>tools:<n>tok` in `transforms_applied` and credited as `tool_schema_tokens_saved` in `/stats`. Without the extension the tools pass through compacted and `headers` is `{}`. Tool-search history repair stays in core regardless: once a transcript carries Anthropic's tool-search blocks, a later request whose tools cannot support them (a side request with a smaller tools array) has those blocks replaced in place by an inert placeholder text block, as on the proxy path (`router:tool_search_repair:<n>blocks`).
+- **Output steering.** When the output shaper is on (`HEADROOM_OUTPUT_SHAPER=1` or the `proxy_output_shaper` rollout; off in `mode="cache"` for steering), the byte-stable verbosity block is appended to the tail of `system` (Anthropic) or the last system/developer message (OpenAI chat), the conversation-stable `HEADROOM_OUTPUT_HOLDOUT` arm is honoured, and the `output_shaper:stratum:…` / `output_shaper:control:…` label rides `transforms_applied` — it is what turns the response half's relayed `output_tokens` into output savings in `/stats`. The block is identical every turn, so the prefix still caches; it is applied to the returned `body` only, never to the session snapshot, so it is re-appended once per turn rather than accumulating.
+
+Both fail open: any error leaves the body as built and `headers` empty.
+
+Turn hooks registered by proxy extensions run here as they do on the proxy path. Request hooks run stream-safe-only unless `can_redrive` and `session_affinity` are both `true` — a hook that must see the response is skipped when the gateway cannot come back with one. Hook savings show up as `turn_hook` and `turn_hook:tools:<n>tok`. In session mode hooks run after the replay overlay and before the snapshot, so a hook that is not a pure function of its input busts the prefix exactly as it would on the proxy.
+
+The response keeps every field above and adds six:
+
+```json
+{
+ "messages": [{ "role": "user", "content": "..." }],
+ "tokens_before": 15000,
+ "tokens_after": 3500,
+ "body": {
+ "model": "gpt-4o",
+ "messages": [{ "role": "user", "content": "..." }],
+ "tools": [{ "type": "function", "function": { "name": "search", "parameters": {} } }],
+ "temperature": 0.2
+ },
+ "turn_id": "3d2f6c0e0b0a4e1a9c1b2f3d4e5f6a7b",
+ "route": { "model": "gpt-4o", "provider": "openai", "service_tier": null, "reason": "" },
+ "obligations": ["relay_usage"],
+ "gateway": { "can_redrive": false, "can_relay_response": true, "session_affinity": true },
+ "headers": {}
+}
+```
+
+| Field | Description |
+| --- | --- |
+| `body` | The complete provider request: every pass-through field, final `messages` (the same list as top-level `messages`) and final `tools`. Never contains `config`, `gateway` or `token_budget`. Forward it as-is. |
+| `headers` | Request headers the gateway must **set** on the provider request (name → value), on the original forward and on every `redrive`. `{}` when nothing is needed. Produced by turn hooks through `TurnContext.provider_headers`: only allow-listed names are honoured (today `anthropic-beta`), and `anthropic-beta` is merged behind the client's value from `gateway.request_headers` (deduplicated, client tokens first — the same merge the proxy path uses for every Headroom-required beta). The tool-search extension's native tier uses it for `advanced-tool-use-2025-11-20`. Fail-open answers always carry `{}`. |
+| `turn_id` | Handle for the response half. Always present, but a turn is only *registered* — and worth posting back — when `obligations` is non-empty. |
+| `route` | Advisory. `provider` is inferred from the model name (`anthropic` for names containing `claude` or `anthropic`, else `openai`) unless a routing extension published advice; when it did, its model is also written into `body.model`, so `route.model` and `body.model` never disagree. `service_tier` echoes the request. Headroom never switches the upstream itself. |
+| `obligations` | `redrive` — a transform ran whose reload step needs the response; post `response` to `/v1/compress/response` and honour `redrive` answers. `relay_usage` — you offered `can_relay_response`; post status and usage when the provider answers. |
+| `gateway` | Echo of the capabilities Headroom honoured. |
+
+Fail-open answers (bypass header, empty `messages`, stateless timeout) carry the same six keys with your original body, `obligations: []` and `headers: {}`.
+
+When `relay_usage` is owed, the turn's `/stats` record is deferred until the response half arrives with billed input and output, cache counts, provider status and latency; a turn that never comes back is recorded as-is when it expires. Pending turns live `HEADROOM_GATEWAY_TURN_TTL_SECONDS` (default `120`, refreshed on every `redrive`), at most `HEADROOM_GATEWAY_MAX_PENDING_TURNS` at a time (default `10000`, oldest evicted first), and a turn may re-drive at most `HEADROOM_GATEWAY_MAX_REDRIVES` times (default `8`).
+
+**`config.mode: "ccr"` on this contract.** When markers were inserted and re-driving is allowed, Headroom injects the `headroom_retrieve` tool into `body.tools` (`ccr_tool_injected` in `transforms_applied`), adds the `redrive` obligation, and the response half answers the model's retrieval calls itself — the gateway just keeps re-driving. Without `can_redrive`, `ccr` mode behaves as it does today: the markers are yours to resolve.
+
+#### `POST /v1/compress/response`
+
+The response half. Same exposure rules as `/v1/compress`: loopback-only unless `HEADROOM_COMPRESS_ALLOW_REMOTE=1`, and `HEADROOM_PROXY_TOKEN` applies.
+
+| Field | Type | Required | Description |
+| --- | --- | --- | --- |
+| `turn_id` | string | yes | From the request half. |
+| `status` | integer | no | Provider HTTP status, `100`–`599`. Default `200`. Hooks only start on a `200`. |
+| `latency_ms` | number | no | Gateway-measured provider latency, added to the turn's recorded latency. Must be non-negative. |
+| `round` | integer | no | Which provider call this response answers: `0` for the original forward, `n` for the `n`-th re-drive (the `round` this endpoint returned). Makes the call idempotent: a retried relay for a round already answered gets the same `redrive` answer again instead of being fed to the hook, and its usage is not billed twice. A round ahead of the turn is a `400`. |
+| `usage` | object | no | The provider's usage block, in any accepted shape (below). |
+| `response` | object | no | The full provider response JSON. **Required** when the turn carries `redrive`. |
+| `model` | string | no | Provider-reported model. Accepted, not read today. |
+
+Accepted `usage` shapes — the whole provider response body works too, since a nested `usage` key is descended into once:
+
+- Anthropic: `input_tokens`, `output_tokens`, `cache_read_input_tokens`, `cache_creation_input_tokens`
+- OpenAI chat: `prompt_tokens`, `completion_tokens`, `prompt_tokens_details.cached_tokens`
+- OpenAI Responses: `input_tokens`, `output_tokens`, `input_tokens_details.cached_tokens`
+- Kong's flattened `ai.proxy` log shape: `prompt_tokens`, `completion_tokens`, top-level `cached_tokens`
+
+Booleans and negative counts are a `400`. Usage with no cache field is accepted but not applied to the session tracker; the apply rule is `/v1/usage`'s (a positive count, or both cache fields present at `0`). Across re-drive rounds the billed counters are summed and the cache fields come from the latest round that carried them.
+
+There are two answers. `done` ends the turn:
+
+```json
+{
+ "action": "done",
+ "turn_id": "3d2f6c0e0b0a4e1a9c1b2f3d4e5f6a7b",
+ "response": null,
+ "frozen_message_count": 12,
+ "usage_applied": true,
+ "rounds": 0
+}
+```
+
+`response` is a replacement to send to the client when a hook produced one; otherwise it is `null` and you forward the provider response you already hold. `frozen_message_count` is the session's count after the usage was applied (`null` for a stateless turn). `usage_applied` is `false` when the usage carried no cache signal, the session had expired, or its lock was busy — never an error, since the turn is finishing and there is nothing to retry with. After `done` the turn is gone.
+
+`redrive` asks for another provider call:
+
+```json
+{
+ "action": "redrive",
+ "turn_id": "3d2f6c0e0b0a4e1a9c1b2f3d4e5f6a7b",
+ "request": { "model": "gpt-4o", "messages": [], "tools": [] },
+ "round": 1
+}
+```
+
+Send `request` to the provider exactly as given — it is the provider body with the hook's messages and possibly reloaded tools — and post the provider's JSON back under the same `turn_id`. Past `HEADROOM_GATEWAY_MAX_REDRIVES` the turn ends with `done` and `response: null`. Hook failures never fail the turn either: the answer is `done` with `response: null` and the gateway forwards what it holds.
+
+| Status | Body | When |
+| --- | --- | --- |
+| `400` | `error.type = "invalid_request"` | Malformed JSON, missing or invalid `turn_id`, `status` not an HTTP status code, negative `latency_ms`, non-object `usage` or `response`, boolean or negative usage counts. |
+| `400` | `error.type = "missing_response"` | The turn carries `redrive` and `response` is absent. |
+| `404` | `error.type = "unknown_turn"` | Never registered (the request half returned no obligations), already finished, or expired. |
+| `409` | `error.type = "turn_busy"` | A response-half call for this turn is already being driven. |
+| `400` | `error.type = "round_out_of_sequence"` | `round` is ahead of the round the turn is waiting for. |
+| `409` | `error.type = "round_already_answered"` | `round` names a round that was already answered with `done`. |
+
+#### Kong plugin
+
+[kong-plugin-headroom](https://github.com/headroomlabs-ai/kong-plugin-headroom) is a Kong Gateway 3.9 plugin, in its own repository and installable with `luarocks install kong-plugin-headroom` or as a Konnect custom plugin, that implements both halves: it sends every chat request through `/v1/compress` with `config.session_id` and a `gateway` block, swaps `body` in, relays usage from the `log` phase, and runs the re-drive loop in `access` when a `redrive` obligation comes back. Install steps, configuration and limits are in its README. Headroom's docker end-to-end test (`tests/gateway/test_kong_integration.py`, `HEADROOM_KONG_E2E=1`) expects a checkout of it next to this repository or at `HEADROOM_KONG_PLUGIN_DIR`.
+
+**The contract is itself an extension.** Core exposes a compress-turn seam (`headroom.proxy.compress_turn`): an extension registers a contract with `register_compress_turn_extension`, and per request it may claim the body (`begin`), prepare executor-side work (`prepare`), rewrite the outbound messages at the one safe moment in session mode (`transform`, after the prefix replay and before the tracker records what was returned), add response fields and transform labels (`finish`), take ownership of the outcome (`commit`), and answer the fail-open cases (`fail_open_fields`). The gateway turn contract described above is installed through that seam by `headroom.proxy.gateway_extension` (on by default; `HEADROOM_GATEWAY_CONTRACT=0` leaves it out, after which a `gateway` block is ignored and the endpoint answers in legacy shape). A third-party contract's `install(app, config)` finds the `/v1/compress` exposure policy on `app.state.compress_route_dependencies` for any route it adds.
+
<Callout type="info" title="Not the same as HEADROOM_KOMPRESS_ENDPOINT">
`HEADROOM_KOMPRESS_ENDPOINT` points *outbound* at a remote Kompress ML model server that happens to expose a `/compress` path. It is unrelated to this inbound endpoint.
</Callout>
diff --git a/headroom/proxy/compress_turn.py b/headroom/proxy/compress_turn.py
new file mode 100644
index 000000000..1db795712
--- /dev/null
+++ b/headroom/proxy/compress_turn.py
@@ -0,0 +1,179 @@
+"""Compress-turn extensions: the seam that lets a gateway contract live outside
+``POST /v1/compress``'s handler.
+
+The compress handler does one thing well — it compresses a message list, in
+legacy or session mode — and it exposes five moments to an extension that
+wants to wrap that into a richer, gateway-facing turn:
+
+1. ``begin`` — the handler has parsed the body; the extension decides whether
+ this request is one of its (a gateway would look for its ``gateway`` block),
+ validates its own fields (raise :class:`CompressTurnError` for a 400) and
+ returns a per-request :class:`CompressTurn`, or ``None`` to stay out.
+2. ``prepare`` — model, tags and config are resolved; the turn may build
+ whatever it needs for the executor (a tokenizer, hooks, a scope binding).
+3. ``transform`` — EXECUTOR SIDE. Called once, after the pipeline (legacy) or
+ after the session engine's prefix replay (session mode) and before the
+ session tracker records what was returned. What this returns IS what the
+ caller forwards to the provider, so it must be a pure function of its input
+ in session mode or it busts the replayed prefix.
+4. ``finish`` — back on the event loop with the final messages and counts:
+ the turn adds its own transform labels, extra response fields and may
+ replace the outgoing messages (a gateway builds the provider ``body`` here).
+5. ``commit`` — the handler has built the :class:`RequestOutcome`; the turn
+ may take ownership of recording it (return ``True`` to defer) when it is
+ waiting for more information, such as a gateway's relayed usage.
+
+Plus ``fail_open_fields`` for the three fail-open answers (bypass header,
+empty messages, compression timeout), where the caller must still get
+whatever it needs to forward the original request.
+
+Exactly one extension claims a request: the first whose ``begin`` returns a
+turn. The built-in gateway turn contract (``headroom.proxy.gateway_extension``)
+is registered through this same seam, so a third-party contract has nothing
+core does not.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass, field
+from typing import Any, Protocol, runtime_checkable
+
+from headroom.proxy.outcome import RequestOutcome
+
+log = logging.getLogger(__name__)
+
+
+class CompressTurnError(ValueError):
+ """Raised from ``begin`` for a malformed extension-specific request; the
+ handler answers 400 ``invalid_request`` with ``message`` — a validation
+ sentence the extension wrote for the caller, never an exception's text."""
+
+ def __init__(self, message: str) -> None:
+ super().__init__(message)
+ self.message = str(message)
+
+
+@dataclass
+class FinishedTurn:
+ """What ``finish`` hands back to the handler."""
+
+ #: Extra top-level keys merged into the JSON answer (a gateway's ``body``,
+ #: ``turn_id``, ``route``, ``obligations``, ``headers`` …).
+ fields: dict[str, Any] = field(default_factory=dict)
+ #: The complete ``transforms_applied`` list for the answer AND the outcome
+ #: (the pipeline's plus the turn's own).
+ transforms: list[str] = field(default_factory=list)
+ #: The messages to return; ``None`` keeps the handler's.
+ messages: list[dict[str, Any]] | None = None
+
+
+@runtime_checkable
+class CompressTurn(Protocol):
+ """One request's turn, created by :meth:`CompressTurnExtension.begin`."""
+
+ def fail_open_fields(self, messages: list[dict[str, Any]]) -> dict[str, Any]:
+ """Fields to merge into a fail-open answer (originals, no obligations)."""
+
+ def prepare(self, *, model_name: str, tags: dict[str, Any], config: Any) -> None:
+ """Called once before the executor with the resolved model and tags."""
+
+ def transform(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Executor side; see the module docstring for the exact moment."""
+
+ @property
+ def folded_messages(self) -> bool:
+ """Whether ``transform`` changed the messages' token count (the handler
+ must then recount ``tokens_after``)."""
+
+ def count_messages(self, messages: list[dict[str, Any]], fallback: int) -> int:
+ """Recount with the turn's own tokenizer; ``fallback`` on failure."""
+
+ def finish(
+ self,
+ *,
+ messages: list[dict[str, Any]],
+ tokens_before: int,
+ transforms_applied: list[str],
+ mode: str | None,
+ ccr_hashes: list[str],
+ ) -> FinishedTurn:
+ """Event-loop side, after the executor; before the outcome is built."""
+
+ def commit(
+ self,
+ outcome: RequestOutcome,
+ *,
+ session_key: str | None,
+ session_id: str | None,
+ ) -> bool:
+ """The outcome is built. Return ``True`` to take ownership of recording
+ it later; ``False`` and the handler records it now."""
+
+
+@runtime_checkable
+class CompressTurnExtension(Protocol):
+ name: str
+
+ def begin(
+ self,
+ *,
+ proxy: Any,
+ request: Any,
+ body: dict[str, Any],
+ client: str | None,
+ ) -> CompressTurn | None:
+ """Claim the request (return a turn) or decline (``None``). Raise
+ :class:`CompressTurnError` for a 400."""
+
+
+def _registry(proxy: Any) -> list[CompressTurnExtension]:
+ """Per-proxy registry (one proxy per app, so two apps in one process — the
+ test suite, an embedded proxy — never see each other's contracts)."""
+ registry = getattr(proxy, "compress_turn_extensions", None)
+ if registry is None:
+ registry = []
+ try:
+ proxy.compress_turn_extensions = registry
+ except Exception: # a proxy that cannot hold attributes: nothing installs
+ return []
+ return registry
+
+
+def register_compress_turn_extension(proxy: Any, extension: CompressTurnExtension) -> None:
+ """Register a contract on ``proxy`` (``app.state.proxy``). Called by an
+ extension's ``install(app, config)``."""
+ _registry(proxy).append(extension)
+ log.info("registered compress-turn extension: %s", getattr(extension, "name", extension))
+
+
+def unregister_compress_turn_extension(proxy: Any, extension: CompressTurnExtension) -> None:
+ registry = _registry(proxy)
+ while extension in registry:
+ registry.remove(extension)
+
+
+def registered_compress_turn_extensions(proxy: Any) -> list[CompressTurnExtension]:
+ return list(_registry(proxy))
+
+
+def begin_compress_turn(
+ *, proxy: Any, request: Any, body: dict[str, Any], client: str | None
+) -> CompressTurn | None:
+ """The first extension that claims the body wins. A ``CompressTurnError``
+ propagates (the handler answers 400); any other exception disables that
+ extension for this request only (fail-open, logged)."""
+ for extension in registered_compress_turn_extensions(proxy):
+ try:
+ turn = extension.begin(proxy=proxy, request=request, body=body, client=client)
+ except CompressTurnError:
+ raise
+ except Exception: # an extension must never break /v1/compress
+ log.exception(
+ "compress-turn extension %r failed to begin; ignored for this request",
+ getattr(extension, "name", extension),
+ )
+ continue
+ if turn is not None:
+ return turn
+ return None
diff --git a/headroom/proxy/gateway_extension.py b/headroom/proxy/gateway_extension.py
new file mode 100644
index 000000000..6eef84ca8
--- /dev/null
+++ b/headroom/proxy/gateway_extension.py
@@ -0,0 +1,295 @@
+"""The gateway turn contract as a compress-turn extension.
+
+Everything a gateway (Kong, Envoy, LiteLLM, Cloudflare …) needs from
+``POST /v1/compress`` — the ``gateway`` capability block, the full provider
+``body``, ``turn_id`` / ``route`` / ``obligations`` / ``headers``, the
+``POST /v1/compress/response`` second half, the pending-turn registry and the
+parked re-drive hooks — is installed here through the same seams a third-party
+contract would use (:mod:`headroom.proxy.compress_turn`). The contract LOGIC
+stays in :mod:`headroom.proxy.gateway_turn`; this module is the glue that used
+to be inlined in the compress handler, plus the route and registry setup.
+
+Installed by ``create_app`` by default; ``HEADROOM_GATEWAY_CONTRACT=0`` leaves
+it out, in which case a body's ``gateway`` block is ignored and the endpoint
+answers in legacy shape (a gateway then fails open on its side).
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from typing import Any
+
+from starlette.requests import Request
+
+from headroom.proxy.compress_turn import (
+ CompressTurnError,
+ FinishedTurn,
+ register_compress_turn_extension,
+ registered_compress_turn_extensions,
+)
+from headroom.proxy.gateway_turn import (
+ OBLIGATION_RELAY_USAGE,
+ GatewayCapabilities,
+ GatewayRequestError,
+ PendingTurnRegistry,
+ RequestTransformer,
+ arm_ccr_redrive,
+ compute_obligations,
+ gateway_response_fields,
+ handle_compress_response,
+ new_turn_id,
+ on_turn_expired,
+ parse_gateway_block,
+ provider_for_model,
+ register_pending_turn,
+ shape_gateway_body,
+)
+from headroom.proxy.outcome import RequestOutcome
+
+log = logging.getLogger(__name__)
+
+ENV_GATEWAY_CONTRACT = "HEADROOM_GATEWAY_CONTRACT"
+EXTENSION_NAME = "gateway_turn_contract"
+
+
+def gateway_contract_enabled() -> bool:
+ return os.environ.get(ENV_GATEWAY_CONTRACT, "1").strip().lower() not in (
+ "0",
+ "false",
+ "no",
+ "off",
+ )
+
+
+class GatewayTurn:
+ """One gateway-mode request, from ``begin`` to ``commit``."""
+
+ def __init__(
+ self,
+ *,
+ proxy: Any,
+ request: Any,
+ body: dict[str, Any],
+ caps: GatewayCapabilities,
+ client: str | None,
+ ) -> None:
+ self.proxy = proxy
+ self.request = request
+ self.body = body
+ self.caps = caps
+ self.client = client
+ self.provider = provider_for_model(str(body.get("model") or ""))
+ self.model_name = str(body.get("model") or "")
+ self.tags: dict[str, Any] = {}
+ self._transformer: RequestTransformer | None = None
+ self._fields: dict[str, Any] | None = None
+ self._obligations: list[str] = []
+ self._turn_id: str | None = None
+ self._ccr_armed = False
+
+ # -- fail-open ---------------------------------------------------------
+ def fail_open_fields(self, messages: list[dict[str, Any]]) -> dict[str, Any]:
+ # Originals, no obligations: the gateway forwards the body as sent.
+ return gateway_response_fields(
+ request=self.request,
+ body=self.body,
+ caps=self.caps,
+ provider=self.provider,
+ messages=messages,
+ tools=self.body.get("tools"),
+ obligations=[],
+ turn_id=new_turn_id(),
+ )
+
+ # -- before the executor ----------------------------------------------
+ def prepare(self, *, model_name: str, tags: dict[str, Any], config: Any) -> None:
+ from headroom.proxy.savings_attribution import bind_scope
+
+ # bind_scope first so a hook's savings attribute to this outcome,
+ # exactly as the chat path does.
+ bind_scope(tags, self.request.scope)
+ self.model_name = model_name
+ self.tags = tags
+ self.provider = provider_for_model(model_name)
+ self._transformer = RequestTransformer(
+ provider=self.provider,
+ model_name=model_name,
+ tools=self.body.get("tools"),
+ config=config,
+ tags=tags,
+ caps=self.caps,
+ )
+
+ # -- executor side -----------------------------------------------------
+ def transform(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ if self._transformer is None:
+ return messages
+ return self._transformer.run(messages)
+
+ @property
+ def folded_messages(self) -> bool:
+ return self._transformer is not None and self._transformer.folded_messages
+
+ def count_messages(self, messages: list[dict[str, Any]], fallback: int) -> int:
+ if self._transformer is None:
+ return fallback
+ return self._transformer.count_messages(messages, fallback)
+
+ # -- event-loop side ---------------------------------------------------
+ def finish(
+ self,
+ *,
+ messages: list[dict[str, Any]],
+ tokens_before: int,
+ transforms_applied: list[str],
+ mode: str | None,
+ ccr_hashes: list[str],
+ ) -> FinishedTurn:
+ result = self._transformer.result if self._transformer is not None else None
+ if result is None:
+ return FinishedTurn(fields={}, transforms=list(transforms_applied), messages=None)
+ # mode="ccr" markers are only useful if the model can resolve them:
+ # inject headroom_retrieve and let the response half answer it (a
+ # re-drive), or leave it to the caller otherwise.
+ self._ccr_armed = arm_ccr_redrive(
+ result,
+ provider=self.provider,
+ caps=self.caps,
+ mode=mode,
+ ccr_hashes=ccr_hashes,
+ )
+ transforms = list(transforms_applied or ()) + list(result.transforms)
+ # Gateway fields are built BEFORE the outcome: output shaping runs on
+ # the provider body and its (arm, stratum) label must be on the
+ # outcome's transforms for the response half's relayed output_tokens
+ # to become output savings.
+ self._obligations = compute_obligations(
+ self.caps, redrive_armed=result.redrive_armed or self._ccr_armed
+ )
+ self._turn_id = new_turn_id()
+ self._fields = gateway_response_fields(
+ request=self.request,
+ body=self.body,
+ caps=self.caps,
+ provider=self.provider,
+ messages=messages,
+ tools=result.tools,
+ obligations=self._obligations,
+ turn_id=self._turn_id,
+ headers=result.headers,
+ )
+ shape_gateway_body(
+ self._fields["body"],
+ provider=self.provider,
+ model_name=self.model_name,
+ config=self.proxy.config,
+ input_tokens=tokens_before,
+ transforms=transforms,
+ )
+ # I-BODY: top-level `messages` and `body.messages` are one list.
+ return FinishedTurn(
+ fields=self._fields,
+ transforms=transforms,
+ messages=self._fields["body"]["messages"],
+ )
+
+ def commit(
+ self,
+ outcome: RequestOutcome,
+ *,
+ session_key: str | None,
+ session_id: str | None,
+ ) -> bool:
+ if self._fields is None or self._transformer is None or self._transformer.result is None:
+ return False
+ # With relay_usage owed, the outcome waits for the response half
+ # (billed input/output, cache counts, provider status); the registry
+ # records the draft as-is if that never comes.
+ defer = OBLIGATION_RELAY_USAGE in self._obligations
+ register_pending_turn(
+ self.proxy,
+ turn_id=self._turn_id or new_turn_id(),
+ session_key=session_key,
+ session_id=session_id,
+ provider=self.provider,
+ model=str(self._fields["body"].get("model")),
+ body=self._fields["body"],
+ ctx=self._transformer.result.ctx,
+ obligations=self._obligations,
+ outcome_draft=outcome if defer else None,
+ tags=self.tags,
+ client=self.client,
+ ccr_armed=self._ccr_armed,
+ )
+ return defer
+
+
+class GatewayTurnExtension:
+ """Claims every ``/v1/compress`` body that carries a ``gateway`` block."""
+
+ name = EXTENSION_NAME
+
+ def begin(
+ self, *, proxy: Any, request: Any, body: dict[str, Any], client: str | None
+ ) -> GatewayTurn | None:
+ try:
+ caps = parse_gateway_block(body)
+ except GatewayRequestError as e:
+ raise CompressTurnError(e.message) from e
+ if caps is None:
+ return None
+ return GatewayTurn(proxy=proxy, request=request, body=body, caps=caps, client=client)
+
+
+def install(app: Any, config: Any, *, route_dependencies: list[Any] | None = None) -> None:
+ """Install the contract: registry on the proxy, the extension, the route.
+
+ ``route_dependencies`` is the same FastAPI dependency list ``/v1/compress``
+ uses (loopback-only unless ``HEADROOM_COMPRESS_ALLOW_REMOTE``), so the two
+ halves keep one exposure policy. Idempotent per app.
+ """
+ proxy = getattr(app.state, "proxy", None)
+ if proxy is None:
+ raise RuntimeError("gateway contract: app.state.proxy is not set yet")
+ if getattr(proxy, "gateway_turns", None) is None:
+ # Turns whose response half is still owed by an external gateway. Same
+ # replica affinity as the session caches. Expiry records the deferred
+ # outcome draft and drops any parked re-drive coroutine.
+ proxy.gateway_turns = PendingTurnRegistry(
+ on_expire=lambda turn: on_turn_expired(proxy, turn)
+ )
+ if not any(
+ getattr(ext, "name", None) == EXTENSION_NAME
+ for ext in registered_compress_turn_extensions(proxy)
+ ):
+ register_compress_turn_extension(proxy, GatewayTurnExtension())
+
+ # Response half: the gateway posts the provider's answer (or just its
+ # usage) under the turn_id the request half returned. Same exposure
+ # policy as /v1/compress — the two halves are one contract.
+ async def compress_response(request: Request) -> Any:
+ return await handle_compress_response(proxy, request)
+
+ app.add_api_route(
+ "/v1/compress/response",
+ compress_response,
+ methods=["POST"],
+ dependencies=list(route_dependencies or []),
+ name="compress_response",
+ )
+ log.info(
+ "gateway turn contract installed (request half via compress-turn seam, response half at /v1/compress/response)"
+ )
+
+
+def install_builtin(app: Any, config: Any, *, route_dependencies: list[Any] | None = None) -> bool:
+ """``create_app``'s default install, honouring ``HEADROOM_GATEWAY_CONTRACT``."""
+ if not gateway_contract_enabled():
+ log.info(
+ "gateway turn contract disabled (%s=0); `gateway` blocks are ignored",
+ ENV_GATEWAY_CONTRACT,
+ )
+ return False
+ install(app, config, route_dependencies=route_dependencies)
+ return True
diff --git a/headroom/proxy/gateway_turn.py b/headroom/proxy/gateway_turn.py
new file mode 100644
index 000000000..b1899f5c4
--- /dev/null
+++ b/headroom/proxy/gateway_turn.py
@@ -0,0 +1,1484 @@
+"""Gateway turn contract — one model turn split across two HTTP calls.
+
+An external gateway (Kong, LiteLLM, a custom sidecar) owns routing, so Headroom
+never sees the provider response on the ``/v1/compress`` path. The turn
+contract closes that gap in two halves:
+
+* the **request half** (``POST /v1/compress`` with a top-level ``gateway``
+ object) returns the complete provider body, a ``turn_id``, routing advice
+ and the *obligations* the gateway must redeem for the transforms Headroom
+ applied;
+* the **response half** (``POST /v1/compress/response``) takes the provider's
+ answer under that ``turn_id`` and either finishes the turn (``done``) or
+ asks the gateway to call the provider again (``redrive``).
+
+The rule behind it is the proxy's own "no shrink without reload", moved to the
+API boundary: a transform whose reload step needs the response runs only when
+the gateway said it can re-drive (``gateway.can_redrive``). A body without a
+``gateway`` key is *legacy mode* and this module is never consulted — the
+handler keeps today's stateless/session behaviour byte-for-byte.
+
+The subtle part is :class:`SuspendedHookRunner`. Turn hooks (``turn_hooks``)
+re-drive the model by ``await call_model(messages)`` inside one coroutine. On
+the proxy path that await is an upstream HTTP call; here the "call" is the
+gateway's next request, so the hook coroutine is parked as an ``asyncio.Task``
+between the two HTTP requests and handed the provider's JSON when it arrives.
+The hook never learns the difference, which is what keeps the extension
+packages unchanged.
+
+Everything here is in-process state with the same replica-affinity requirement
+as the replay cache and prefix tracker: the gateway must pin a session to one
+Headroom replica (``gateway.session_affinity``); when it cannot, re-driving
+transforms are switched off for the turn.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import copy
+import dataclasses
+import json
+import logging
+import os
+import threading
+import time
+import uuid
+from collections import OrderedDict
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from typing import Any
+
+from headroom.proxy.outcome import RequestOutcome
+from headroom.proxy.turn_hooks import (
+ TurnContext,
+ merge_provider_headers,
+ registered_turn_hooks,
+ run_request_hooks,
+ run_response_hooks,
+)
+
+logger = logging.getLogger(__name__)
+
+# Keys that steer Headroom itself and must never reach the provider.
+BODY_CONTROL_KEYS: frozenset[str] = frozenset({"config", "gateway", "token_budget"})
+
+OBLIGATION_REDRIVE = "redrive"
+OBLIGATION_RELAY_USAGE = "relay_usage"
+
+ANTHROPIC_BETA_HEADER = "anthropic-beta"
+# Request headers the gateway may hand over; every other name is ignored.
+GATEWAY_REQUEST_HEADERS: frozenset[str] = frozenset({ANTHROPIC_BETA_HEADER})
+
+DEFAULT_TURN_TTL_SECONDS = 120.0
+DEFAULT_MAX_PENDING_TURNS = 10_000
+DEFAULT_MAX_REDRIVES = 8
+
+# Strong references to fire-and-forget bookkeeping tasks (outcome recording
+# for an expired turn, cancelling its parked coroutine). asyncio keeps only a
+# weak reference to a task, so without this set a GC pass could drop the task
+# before it ran.
+_BACKGROUND_TASKS: set[asyncio.Task[Any]] = set()
+
+
+def _env_float(name: str, default: float) -> float:
+ try:
+ return float(os.environ.get(name, "") or default)
+ except ValueError:
+ return default
+
+
+def _env_int(name: str, default: int) -> int:
+ try:
+ return int(os.environ.get(name, "") or default)
+ except ValueError:
+ return default
+
+
+# --------------------------------------------------------------------------- #
+# Capabilities #
+# --------------------------------------------------------------------------- #
+
+
+class GatewayRequestError(ValueError):
+ """A malformed ``gateway`` block; the handler answers 400 with the message."""
+
+ def __init__(self, message: str) -> None:
+ super().__init__(message)
+ self.message = str(message)
+
+
+@dataclass(frozen=True)
+class GatewayCapabilities:
+ """What the gateway declared it can do for this turn.
+
+ ``redrive_allowed`` is the one the transforms gate on: a gateway that
+ cannot pin the session to this replica cannot be asked to come back with
+ the provider response, so ``session_affinity=False`` disables re-driving
+ even when ``can_redrive`` is set.
+ """
+
+ can_redrive: bool = False
+ can_relay_response: bool = False
+ session_affinity: bool = True
+ plugin_version: str | None = None
+ # Client request headers the gateway forwarded (lowercase name -> value),
+ # only the ones Headroom merges into the ``headers`` it hands back
+ # (``anthropic-beta`` today). Never forwarded anywhere by Headroom.
+ request_headers: dict[str, str] = field(default_factory=dict)
+
+ @property
+ def redrive_allowed(self) -> bool:
+ return self.can_redrive and self.session_affinity
+
+ @property
+ def client_anthropic_beta(self) -> str | None:
+ return self.request_headers.get(ANTHROPIC_BETA_HEADER)
+
+ def echo(self) -> dict[str, bool]:
+ """The capabilities Headroom honoured, echoed back to the gateway."""
+ return {
+ "can_redrive": self.can_redrive,
+ "can_relay_response": self.can_relay_response,
+ "session_affinity": self.session_affinity,
+ }
+
+
+_BOOL_FIELDS: tuple[tuple[str, bool], ...] = (
+ ("can_redrive", False),
+ ("can_relay_response", False),
+ ("session_affinity", True),
+)
+
+
+def parse_gateway_block(body: dict[str, Any]) -> GatewayCapabilities | None:
+ """``None`` in legacy mode (no ``gateway`` key); raises on a malformed block.
+
+ Presence of the key is the mode switch, so ``{"gateway": {}}`` is gateway
+ mode with every default. Unknown keys inside the block are ignored so a
+ newer plugin can talk to an older Headroom.
+ """
+ if "gateway" not in body:
+ return None
+ raw = body["gateway"]
+ if not isinstance(raw, dict):
+ raise GatewayRequestError(f"gateway must be an object, got {type(raw).__name__}.")
+ values: dict[str, Any] = {}
+ for name, default in _BOOL_FIELDS:
+ value = raw.get(name, default)
+ if not isinstance(value, bool):
+ raise GatewayRequestError(f"gateway.{name} must be a boolean, got {value!r}.")
+ values[name] = value
+ plugin_version = raw.get("plugin_version")
+ values["plugin_version"] = str(plugin_version) if plugin_version is not None else None
+ values["request_headers"] = _parse_request_headers(raw.get("request_headers"))
+ return GatewayCapabilities(**values)
+
+
+def _parse_request_headers(raw: Any) -> dict[str, str]:
+ """``gateway.request_headers``: an object of header name -> string value.
+
+ Names are lowercased; only the ones in :data:`GATEWAY_REQUEST_HEADERS` are
+ kept (a gateway may hand over the whole client header map). A non-object
+ block or a non-string value is a 400, like the boolean flags.
+ """
+ if raw is None:
+ return {}
+ if not isinstance(raw, dict):
+ raise GatewayRequestError(
+ f"gateway.request_headers must be an object, got {type(raw).__name__}."
+ )
+ out: dict[str, str] = {}
+ for name, value in raw.items():
+ key = str(name).strip().lower()
+ if key not in GATEWAY_REQUEST_HEADERS:
+ continue
+ if value is None:
+ continue
+ if not isinstance(value, str):
+ raise GatewayRequestError(
+ f"gateway.request_headers[{key!r}] must be a string, got {value!r}."
+ )
+ out[key] = value
+ return out
+
+
+def provider_for_model(model_name: str) -> str:
+ """The tracker-provider inference ``/v1/compress`` already uses."""
+ lowered = (model_name or "").lower()
+ return "anthropic" if ("claude" in lowered or "anthropic" in lowered) else "openai"
+
+
+# --------------------------------------------------------------------------- #
+# Usage normalization #
+# --------------------------------------------------------------------------- #
+
+
+@dataclass(frozen=True)
+class NormalizedUsage:
+ """Provider usage reduced to the four counters Headroom acts on.
+
+ ``None`` means the provider (or the gateway's relay) did not report the
+ field — distinct from 0, which is an assertion. That distinction is what
+ keeps an OpenAI relay with no cache fields from being read as "provider
+ confirmed fully cold" and wiping the tracker's cached-prefix state.
+ """
+
+ input_tokens: int | None = None
+ output_tokens: int | None = None
+ cache_read: int | None = None
+ cache_write: int | None = None
+
+ @property
+ def has_cache_signal(self) -> bool:
+ return self.cache_read is not None or self.cache_write is not None
+
+ @property
+ def should_apply(self) -> bool:
+ """Same rule as ``/v1/usage``: a positive count, or BOTH fields at 0.
+
+ A relay whose only present cache field is 0 (an OpenAI-mapped gateway
+ naturally sends ``cached_tokens: 0`` with no write field) carries no
+ positive signal and must not reset the tracker.
+ """
+ read, write = self.cache_read or 0, self.cache_write or 0
+ if read + write > 0:
+ return True
+ return self.cache_read is not None and self.cache_write is not None
+
+ def merged_with(self, other: NormalizedUsage) -> NormalizedUsage:
+ """Sum the billed counters across re-drive rounds; cache fields come
+ from the latest round that carried them (the last provider call is the
+ one whose cache state describes the returned prefix)."""
+
+ def _sum(a: int | None, b: int | None) -> int | None:
+ if a is None and b is None:
+ return None
+ return (a or 0) + (b or 0)
+
+ return NormalizedUsage(
+ input_tokens=_sum(self.input_tokens, other.input_tokens),
+ output_tokens=_sum(self.output_tokens, other.output_tokens),
+ cache_read=other.cache_read if other.has_cache_signal else self.cache_read,
+ cache_write=other.cache_write if other.has_cache_signal else self.cache_write,
+ )
+
+
+def _usage_int(usage: dict[str, Any], name: str) -> int | None:
+ if name not in usage:
+ return None
+ value = usage[name]
+ if value is None:
+ return None
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise GatewayRequestError(f"usage.{name} must be an integer, got {value!r}.")
+ if value < 0:
+ raise GatewayRequestError(f"usage.{name} must be non-negative, got {value}.")
+ return int(value)
+
+
+def normalize_usage(usage: dict[str, Any]) -> NormalizedUsage:
+ """Accept Anthropic, OpenAI chat, OpenAI Responses and Kong ``ai.proxy``
+ usage shapes; raise ``GatewayRequestError`` (a ``ValueError``) on booleans or negative counts.
+
+ Descends once into a nested ``usage`` key so a gateway can relay the whole
+ provider response body, or Kong's log ``ai.proxy`` block, unchanged.
+ """
+ if not isinstance(usage, dict):
+ raise GatewayRequestError("usage must be an object.")
+ nested = usage.get("usage")
+ if isinstance(nested, dict):
+ usage = nested
+
+ input_tokens = _usage_int(usage, "input_tokens")
+ if input_tokens is None:
+ input_tokens = _usage_int(usage, "prompt_tokens")
+ output_tokens = _usage_int(usage, "output_tokens")
+ if output_tokens is None:
+ output_tokens = _usage_int(usage, "completion_tokens")
+
+ cache_read = _usage_int(usage, "cache_read_input_tokens")
+ cache_write = _usage_int(usage, "cache_creation_input_tokens")
+ if cache_read is None:
+ # OpenAI reports reads only (no write counter exists), nested under
+ # prompt_tokens_details (chat), input_tokens_details (Responses) or —
+ # in Kong's flattened log shape — at the top level.
+ for details_key in ("prompt_tokens_details", "input_tokens_details"):
+ details = usage.get(details_key)
+ if isinstance(details, dict):
+ cache_read = _usage_int(details, "cached_tokens")
+ if cache_read is not None:
+ break
+ if cache_read is None:
+ cache_read = _usage_int(usage, "cached_tokens")
+
+ return NormalizedUsage(
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cache_read=cache_read,
+ cache_write=cache_write,
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Suspended hook runner #
+# --------------------------------------------------------------------------- #
+
+
+@dataclass(frozen=True)
+class Step:
+ """One driver step: the hook wants the provider called again, or is done.
+
+ ``response`` on a ``done`` step is the replacement the hook produced, or
+ ``None`` when the gateway should forward the provider response it already
+ holds (the latest one it posted).
+ """
+
+ kind: str # "redrive" | "done"
+ messages: list[dict[str, Any]] | None = None
+ tools: Any = None
+ response: dict[str, Any] | None = None
+
+ @property
+ def is_redrive(self) -> bool:
+ return self.kind == "redrive"
+
+
+class SuspendedHookRunner:
+ """Run ``run_response_hooks`` as a task that parks at every ``call_model``.
+
+ The hook coroutine and the HTTP handlers share one event loop (uvicorn's),
+ so the handshake is two futures: ``_suspend`` resolves when the hook asks
+ for a re-drive, ``_resume`` resolves when the gateway brings the answer.
+ The driver waits on ``{task, _suspend}`` and reports whichever finished.
+
+ Nothing here leaks: ``cancel()`` cancels the task AND awaits it, and the
+ signal futures are plain futures rather than helper tasks, so a cancelled
+ turn leaves ``asyncio.all_tasks()`` exactly as it found it.
+ """
+
+ def __init__(
+ self,
+ ctx: TurnContext,
+ *,
+ run: Callable[..., Any] | None = None,
+ ) -> None:
+ self._ctx = ctx
+ self._run = run or run_response_hooks
+ self._task: asyncio.Task[Any] | None = None
+ self._suspend: asyncio.Future[None] | None = None
+ self._resume: asyncio.Future[dict[str, Any]] | None = None
+ # The provider response the gateway holds right now; a hook that hands
+ # this exact object back has replaced nothing.
+ self._latest: dict[str, Any] | None = None
+ self.pending_request: list[dict[str, Any]] | None = None
+ self.state = "idle" # idle | running | awaiting_redrive | done
+ self.rounds = 0
+ self.last_step: Step | None = None
+
+ async def _call_model(self, messages: list[dict[str, Any]]) -> dict[str, Any]:
+ loop = asyncio.get_running_loop()
+ self.pending_request = messages
+ self._resume = loop.create_future()
+ self.state = "awaiting_redrive"
+ if self._suspend is not None and not self._suspend.done():
+ self._suspend.set_result(None)
+ return await self._resume
+
+ async def start(self, response: dict[str, Any]) -> Step:
+ if self._task is not None:
+ raise RuntimeError("SuspendedHookRunner.start() called twice")
+ self._latest = response
+ self.state = "running"
+ self._task = asyncio.create_task(self._run(self._ctx, response, self._call_model))
+ return await self._drive()
+
+ async def resume(self, provider_response: dict[str, Any]) -> Step:
+ if self.state != "awaiting_redrive" or self._resume is None:
+ raise RuntimeError(f"SuspendedHookRunner.resume() in state {self.state!r}")
+ self._latest = provider_response
+ self.rounds += 1
+ self.state = "running"
+ fut, self._resume = self._resume, None
+ fut.set_result(provider_response)
+ return await self._drive()
+
+ async def _drive(self) -> Step:
+ assert self._task is not None
+ loop = asyncio.get_running_loop()
+ self._suspend = loop.create_future()
+ try:
+ await asyncio.wait({self._task, self._suspend}, return_when=asyncio.FIRST_COMPLETED)
+ except asyncio.CancelledError:
+ # The driver — the response-half handler — was cancelled (client
+ # disconnect, shutdown). Left alone the hook task keeps running:
+ # a gateway retry would then find it "awaiting_redrive" and feed
+ # it the round-0 response as the answer to a re-drive it never
+ # sent, or answer "done" and leave it parked forever. Cancel it
+ # with the driver; the retry gets a plain "done" (hooks are
+ # best-effort by contract).
+ await self.cancel()
+ raise
+ if not self._task.done():
+ # Parked inside call_model: the gateway must call the provider.
+ self.last_step = Step("redrive", messages=self.pending_request, tools=self._ctx.tools)
+ return self.last_step
+ self._suspend = None
+ self.state = "done"
+ final: Any = None
+ if not self._task.cancelled():
+ try:
+ final = self._task.result()
+ except Exception:
+ # run_response_hooks already swallows hook exceptions; this
+ # catches a broken runner, which must not fail the turn.
+ logger.exception("gateway turn: response hook runner failed")
+ replaced = final if isinstance(final, dict) and final is not self._latest else None
+ self.last_step = Step("done", response=replaced)
+ return self.last_step
+
+ async def cancel(self) -> None:
+ task = self._task
+ if task is not None and not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError, Exception):
+ await task
+ if self._resume is not None and not self._resume.done():
+ self._resume.cancel()
+ self._resume = None
+ self._suspend = None
+ self.state = "done"
+
+
+# --------------------------------------------------------------------------- #
+# Pending turns #
+# --------------------------------------------------------------------------- #
+
+
+@dataclass
+class PendingTurn:
+ """Everything the response half needs from the request half."""
+
+ turn_id: str
+ session_key: str | None
+ session_id: str | None
+ provider: str
+ model: str
+ body: dict[str, Any]
+ ctx: TurnContext | None
+ obligations: list[str]
+ outcome_draft: RequestOutcome | None
+ created_at: float
+ deadline: float
+ rounds: int = 0
+ max_rounds: int = DEFAULT_MAX_REDRIVES
+ runner: SuspendedHookRunner | None = None
+ tags: dict[str, Any] = field(default_factory=dict)
+ client: str | None = None
+ # Billed usage accumulated across every response-half call for the turn.
+ usage: NormalizedUsage | None = None
+ # A second response-half call while one is being driven would race the
+ # parked coroutine; the handler answers 409 instead.
+ in_flight: bool = False
+ # config.mode="ccr" with markers inserted and re-drive allowed: the
+ # response half answers headroom_retrieve calls itself (see arm_ccr_redrive).
+ ccr_armed: bool = False
+
+ @property
+ def hooks_armed(self) -> bool:
+ """The response half has something to run: turn hooks and/or CCR."""
+ return OBLIGATION_REDRIVE in self.obligations and self.ctx is not None
+
+
+class PendingTurnRegistry:
+ """In-process, thread-safe registry of turns awaiting their response half.
+
+ Lazy sweep on every ``register``/``get`` (the same pattern as the
+ compression-cache registry) so no background task is needed. Expired or
+ capacity-evicted turns are handed to ``on_expire`` — the proxy wires it to
+ record the deferred outcome draft and cancel a parked coroutine. Never
+ raises out of the callback.
+ """
+
+ def __init__(
+ self,
+ *,
+ ttl_seconds: float | None = None,
+ max_entries: int | None = None,
+ on_expire: Callable[[PendingTurn], None] | None = None,
+ clock: Callable[[], float] = time.time,
+ ) -> None:
+ self.ttl_seconds = (
+ ttl_seconds
+ if ttl_seconds is not None
+ else _env_float("HEADROOM_GATEWAY_TURN_TTL_SECONDS", DEFAULT_TURN_TTL_SECONDS)
+ )
+ self.max_entries = (
+ max_entries
+ if max_entries is not None
+ else _env_int("HEADROOM_GATEWAY_MAX_PENDING_TURNS", DEFAULT_MAX_PENDING_TURNS)
+ )
+ self._on_expire = on_expire
+ self._clock = clock
+ self._turns: OrderedDict[str, PendingTurn] = OrderedDict()
+ self._lock = threading.Lock()
+ self._expired = 0
+ self._evicted = 0
+ # Outcome drafts whose expiry ran with no event loop to record them
+ # on; flushed by the next expiry that does (see on_turn_expired).
+ self.orphaned_outcomes: list[RequestOutcome] = []
+
+ def register(self, turn: PendingTurn) -> None:
+ now = self._clock()
+ with self._lock:
+ dropped = self._sweep_locked(now)
+ while len(self._turns) >= self.max_entries and self._turns:
+ # Oldest first, but not one being driven right now: evicting
+ # it cancels the hook mid-step and its replacement response is
+ # lost (the sweep skips in-flight turns for the same reason).
+ # Only when every turn is in flight does the bound win.
+ oldest = next((t for t in self._turns.values() if not t.in_flight), None)
+ if oldest is None:
+ _, oldest = self._turns.popitem(last=False)
+ else:
+ del self._turns[oldest.turn_id]
+ self._evicted += 1
+ dropped.append(oldest)
+ self._turns[turn.turn_id] = turn
+ self._notify(dropped)
+
+ def get(self, turn_id: str) -> PendingTurn | None:
+ now = self._clock()
+ with self._lock:
+ dropped = self._sweep_locked(now)
+ turn = self._turns.get(turn_id)
+ self._notify(dropped)
+ return turn
+
+ def pop(self, turn_id: str) -> PendingTurn | None:
+ with self._lock:
+ return self._turns.pop(turn_id, None)
+
+ def sweep(self, now: float | None = None) -> list[PendingTurn]:
+ with self._lock:
+ dropped = self._sweep_locked(self._clock() if now is None else now)
+ self._notify(dropped)
+ return dropped
+
+ def _sweep_locked(self, now: float) -> list[PendingTurn]:
+ expired = [t for t in self._turns.values() if t.deadline <= now and not t.in_flight]
+ for turn in expired:
+ self._turns.pop(turn.turn_id, None)
+ self._expired += len(expired)
+ return expired
+
+ def _notify(self, dropped: list[PendingTurn]) -> None:
+ if not dropped or self._on_expire is None:
+ return
+ for turn in dropped:
+ try:
+ self._on_expire(turn)
+ except Exception: # bookkeeping must never break a request
+ logger.exception("gateway turn %s: on_expire callback failed", turn.turn_id)
+
+ def __len__(self) -> int:
+ with self._lock:
+ return len(self._turns)
+
+ def stats(self) -> dict[str, Any]:
+ with self._lock:
+ return {
+ "pending": len(self._turns),
+ "expired": self._expired,
+ "evicted": self._evicted,
+ "ttl_seconds": self.ttl_seconds,
+ "max_entries": self.max_entries,
+ }
+
+
+def _spawn(coro: Any) -> asyncio.Task[Any] | None:
+ """Schedule bookkeeping on the running loop; ``None`` when there is none."""
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ coro.close()
+ return None
+ task = loop.create_task(coro)
+ _BACKGROUND_TASKS.add(task)
+ task.add_done_callback(_BACKGROUND_TASKS.discard)
+ return task
+
+
+def on_turn_expired(proxy: Any, turn: PendingTurn) -> None:
+ """Registry ``on_expire`` hook: record the deferred outcome, drop the coroutine.
+
+ The sweep runs inside ``register``/``get``, which only the HTTP handlers
+ call, so in production there is always a running loop and both the
+ outcome record (``proxy._record_request_outcome`` is async — it shields the
+ funnel and appends to the ledger in a worker thread) and the coroutine
+ cancel are scheduled as tasks on it. Without a loop (direct registry use
+ from a thread or a test) the draft cannot be recorded safely — the funnel's
+ async primitives belong to the server loop — so it is parked on the
+ registry's ``orphaned_outcomes`` list and flushed by the next expiry that
+ does run on the loop. Recording is the safe direction to fail: a dropped
+ draft is a missing row, a misrecorded one is a wrong dashboard.
+ """
+ registry = getattr(proxy, "gateway_turns", None)
+ orphans: list[RequestOutcome] | None = getattr(registry, "orphaned_outcomes", None)
+
+ if turn.runner is not None:
+ _spawn(turn.runner.cancel())
+
+ draft = turn.outcome_draft
+ turn.outcome_draft = None
+ to_record: list[RequestOutcome] = []
+ if orphans:
+ to_record.extend(orphans)
+ orphans.clear()
+ if draft is not None:
+ to_record.append(draft)
+ for outcome in to_record:
+ if _spawn(proxy._record_request_outcome(outcome)) is None:
+ if orphans is not None:
+ orphans.append(outcome)
+ logger.warning(
+ "gateway turn %s expired outside an event loop; outcome deferred",
+ turn.turn_id,
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Request half #
+# --------------------------------------------------------------------------- #
+
+
+def _count_tools_with(tokenizer: Any) -> Callable[[Any], int]:
+ return lambda value: tokenizer.count_text(json.dumps(value, default=str)) if value else 0
+
+
+def compact_gateway_tools(tools: Any) -> tuple[Any, list[str]]:
+ """Deterministic, request-only tool schema compaction (chat-handler parity).
+
+ Layer 1 (annotation stripping) always runs; layer 2 (description
+ truncation) only behind ``HEADROOM_TOOL_DESC_MAX_CHARS``. The compaction
+ module caches by tools digest and hands back the SAME cached list on every
+ hit, so the result is deep-copied before a hook may mutate it in place —
+ otherwise one turn's hook edits would leak into every later turn's
+ "identical" compaction and break byte stability.
+
+ Native tool-search deferral runs AFTER this, in :func:`defer_gateway_tools`,
+ in the chat handler's order (compaction, deferral, hooks, history repair).
+ """
+ if not isinstance(tools, list) or not tools:
+ return tools, []
+ from headroom.proxy.tool_schema_compaction import (
+ compact_tool_descriptions,
+ compact_tools,
+ tool_desc_max_chars,
+ )
+
+ transforms: list[str] = []
+ payload, modified, _, _ = compact_tools({"tools": tools})
+ if modified and payload.get("tools") is not None:
+ tools = copy.deepcopy(payload["tools"])
+ transforms.append("tool_schema_compaction")
+ max_chars = tool_desc_max_chars()
+ if max_chars > 0:
+ payload, modified, _, _ = compact_tool_descriptions({"tools": tools}, max_chars)
+ if modified and payload.get("tools") is not None:
+ tools = copy.deepcopy(payload["tools"])
+ if "tool_schema_compaction" not in transforms:
+ transforms.append("tool_schema_compaction")
+ transforms.append("tool_desc_compaction")
+ return tools, transforms
+
+
+# Emitted when a turn hook (the tool-search extension's native tier) deferred
+# tool schemas: it writes core's ``tool_search_deferred_*`` tags and the label
+# is derived from them here, so /stats, the outcome and the response half see
+# exactly what the chat path's built-in deferral produces.
+NATIVE_DEFERRAL_LABEL = "tool_search:native_deferral"
+TOOL_SEARCH_REPAIR_LABEL = "router:tool_search_repair"
+
+
+def repair_tool_search_history(
+ messages: list[dict[str, Any]], tools: Any, *, provider: str
+) -> tuple[list[dict[str, Any]], int]:
+ """Tool-search history repair (chat-handler parity, request-only).
+
+ Once a turn deferred, the client's transcript carries Anthropic's
+ ``server_tool_use`` / ``tool_search_tool_result`` blocks for good, and
+ upstream validates every ``tool_reference`` in them against THIS request's
+ tools. A side request with a different, smaller tools array (Claude Code's
+ Stop-hook evaluator, ``/compact``) would 400 — so, as on the chat path,
+ the blocks the outbound tools cannot support are dropped. Deterministic
+ (same request -> same output), and it must be the LAST stage that can
+ invalidate a reference: after deferral and after the hooks.
+ """
+ if provider != "anthropic":
+ return messages, 0
+ from headroom.proxy.helpers import strip_unsupported_tool_search_blocks
+
+ repaired, stripped = strip_unsupported_tool_search_blocks(messages, tools)
+ if not stripped:
+ return messages, 0
+ return repaired, int(stripped)
+
+
+@dataclass
+class RequestTransformResult:
+ messages: list[dict[str, Any]]
+ tools: Any
+ ctx: TurnContext | None
+ transforms: list[str]
+ redrive_armed: bool
+ # Headers the gateway must SET on the provider request (name -> value);
+ # empty when no transform needs one.
+ headers: dict[str, str] = field(default_factory=dict)
+ # Messages were rewritten by a stage the pipeline's own count never saw
+ # (a hook fold, history repair): the caller must recount ``tokens_after``.
+ messages_rewritten: bool = False
+
+
+class RequestTransformer:
+ """Tool compaction + request-side turn hooks for one gateway turn.
+
+ Synchronous and CPU-bound (token counts, schema walks), so the handler
+ runs it on the compression executor — in session mode after
+ ``finalize_turn`` and before the tracker snapshots, because the hook
+ output is what the gateway forwards and therefore what ``record_returned``
+ must remember. A hook that is not a pure function of its input will bust
+ the replayed prefix in session mode, exactly as it would on the proxy path.
+ """
+
+ def __init__(
+ self,
+ *,
+ provider: str,
+ model_name: str,
+ tools: Any,
+ config: Any,
+ tags: dict[str, Any],
+ caps: GatewayCapabilities,
+ ) -> None:
+ self.provider = provider
+ self.model_name = model_name
+ self.tools = tools
+ self.config = config
+ self.tags = tags
+ self.caps = caps
+ self.result: RequestTransformResult | None = None
+ self._tokenizer: Any = None
+
+ def _get_tokenizer(self) -> Any:
+ if self._tokenizer is None:
+ from headroom.tokenizers import get_tokenizer
+
+ self._tokenizer = get_tokenizer(self.model_name)
+ return self._tokenizer
+
+ def count_messages(self, messages: list[dict[str, Any]], fallback: int) -> int:
+ """Recount after a hook folded; the pipeline's own count is stale then.
+ Same per-model tokenizer the derived pipelines use, so the scale
+ matches ``tokens_before``. Falls back to the pipeline count."""
+ try:
+ return int(self._get_tokenizer().count_messages(messages))
+ except Exception:
+ return fallback
+
+ @property
+ def folded_messages(self) -> bool:
+ return self.result is not None and self.result.messages_rewritten
+
+ def run(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ transforms: list[str] = []
+ headers: dict[str, str] = {}
+ messages_rewritten = False
+ tools, tool_transforms = compact_gateway_tools(self.tools)
+ transforms.extend(tool_transforms)
+
+ ctx: TurnContext | None = None
+ redrive_armed = False
+ hooks = registered_turn_hooks()
+ count_messages: Callable[[list[dict[str, Any]]], int] | None = None
+ count_tools: Callable[[Any], int] | None = None
+ try:
+ tokenizer = self._get_tokenizer()
+ count_messages = tokenizer.count_messages
+ count_tools = _count_tools_with(tokenizer)
+ except Exception:
+ logger.debug("gateway turn: tokenizer unavailable; hook savings uncounted")
+
+ # Built even with no hook registered: the response half drives CCR
+ # retrieval through the same context (messages + live tools).
+ ctx = TurnContext(
+ provider=self.provider,
+ model=self.model_name,
+ messages=messages,
+ tools=tools,
+ config=self.config,
+ tags=self.tags,
+ count_messages=count_messages,
+ count_tools=count_tools,
+ )
+ if hooks:
+ msg_before = _safe_count(count_messages, messages)
+ tools_before = _safe_count(count_tools, tools)
+ deferred_before = self.tags.get("tool_search_deferred_tools")
+ run_request_hooks(ctx, stream_safe_only=not self.caps.redrive_allowed)
+ messages = ctx.messages
+ tools = ctx.tools
+ # Provider headers the hooks asked for become the contract's
+ # ``headers`` object; the gateway sets them on the provider call.
+ headers = merge_provider_headers(self.caps.request_headers, ctx.provider_headers)
+ deferred_after = self.tags.get("tool_search_deferred_tools")
+ if deferred_after and deferred_after != deferred_before:
+ transforms.append(
+ f"{NATIVE_DEFERRAL_LABEL}:{int(deferred_after)}tools:"
+ f"{int(self.tags.get('tool_search_deferred_tokens', 0) or 0)}tok"
+ )
+ msg_after = _safe_count(count_messages, messages)
+ if msg_before is not None and msg_after is not None and msg_after < msg_before:
+ transforms.append("turn_hook")
+ messages_rewritten = True
+ tools_after = _safe_count(count_tools, tools)
+ if tools_before is not None and tools_after is not None:
+ saved = max(0, tools_before - tools_after)
+ if saved > 0:
+ self.tags["turn_hook_tools_saved_tokens"] = (
+ int(self.tags.get("turn_hook_tools_saved_tokens", 0) or 0) + saved
+ )
+ transforms.append(f"turn_hook:tools:{saved}tok")
+ # Only hooks that ran can re-drive, and with redrive allowed every
+ # hook ran; a fold-only (stream_safe) hook never comes back.
+ redrive_armed = self.caps.redrive_allowed and any(
+ getattr(h, "on_response", None) is not None and not getattr(h, "stream_safe", False)
+ for h in hooks
+ )
+
+ # History repair last: nothing past this point may change the tools
+ # the references are validated against (CCR injection only adds).
+ try:
+ messages, stripped = repair_tool_search_history(messages, tools, provider=self.provider)
+ if stripped:
+ transforms.append(f"{TOOL_SEARCH_REPAIR_LABEL}:{stripped}blocks")
+ messages_rewritten = True
+ ctx.messages = messages
+ except Exception:
+ logger.exception("gateway turn: tool-search history repair failed; messages unchanged")
+
+ self.result = RequestTransformResult(
+ messages=messages,
+ tools=tools,
+ ctx=ctx,
+ transforms=transforms,
+ redrive_armed=redrive_armed,
+ headers=headers,
+ messages_rewritten=messages_rewritten,
+ )
+ return messages
+
+
+def _safe_count(counter: Callable[[Any], int] | None, value: Any) -> int | None:
+ if counter is None:
+ return None
+ try:
+ return int(counter(value))
+ except Exception:
+ return None
+
+
+def arm_ccr_redrive(
+ result: RequestTransformResult,
+ *,
+ provider: str,
+ caps: GatewayCapabilities,
+ mode: str | None,
+ ccr_hashes: list[str],
+) -> bool:
+ """``config.mode="ccr"`` on the gateway contract: inject ``headroom_retrieve``
+ and make the response half answer it.
+
+ Only when markers were actually inserted (nothing to retrieve otherwise)
+ and the gateway can re-drive — a marker the model cannot resolve is a
+ shrink without reload. The tool goes into the live ``ctx.tools`` too, so a
+ re-drive request carries it. Chat-completions and Anthropic tool shapes
+ only (``create_ccr_tool_definition``); the Responses API flat shape is
+ not produced here.
+ """
+ if mode != "ccr" or not caps.redrive_allowed or not ccr_hashes:
+ return False
+ from headroom.ccr import CCR_TOOL_NAME
+ from headroom.ccr.tool_injection import create_ccr_tool_definition
+
+ tools = list(result.tools) if isinstance(result.tools, list) else []
+ present = any(
+ isinstance(t, dict)
+ and (
+ t.get("name") == CCR_TOOL_NAME
+ or (isinstance(t.get("function"), dict) and t["function"].get("name") == CCR_TOOL_NAME)
+ )
+ for t in tools
+ )
+ if not present:
+ tools.append(create_ccr_tool_definition(provider))
+ result.transforms.append("ccr_tool_injected")
+ result.tools = tools
+ if result.ctx is not None:
+ result.ctx.tools = tools
+ return True
+
+
+def make_response_runner(proxy: Any, turn: PendingTurn) -> Callable[..., Any]:
+ """The coroutine the ``SuspendedHookRunner`` parks for this turn.
+
+ CCR retrieval first (the model asked for original bytes; it must have them
+ before any hook sees a "final" answer), then the registered turn hooks —
+ the order the chat path uses. Both re-drive through the same suspending
+ ``call_model``. A CCR failure never propagates: the gateway forwards the
+ response it holds, tool call and all, which is what the proxy path does
+ when a continuation fails.
+ """
+
+ async def run(ctx: TurnContext, response: dict[str, Any], call_model: Any) -> Any:
+ current = response
+ handler = getattr(proxy, "ccr_response_handler", None)
+ if turn.ccr_armed and handler is not None:
+ try:
+ if handler.has_ccr_tool_calls(current, turn.provider):
+
+ async def api_call_fn(messages: list[dict[str, Any]], tools: Any) -> Any:
+ # Mirrors the chat path's continuation closure: the
+ # re-drive request carries the handler's tools.
+ if tools is not None:
+ ctx.tools = tools
+ return await call_model(messages)
+
+ current = await handler.handle_response(
+ current, ctx.messages, ctx.tools, api_call_fn, provider=turn.provider
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.exception("gateway turn %s: CCR retrieval failed", turn.turn_id)
+ return await run_response_hooks(ctx, current, call_model)
+
+ return run
+
+
+def build_provider_body(
+ body: dict[str, Any],
+ messages: list[dict[str, Any]],
+ tools: Any,
+) -> dict[str, Any]:
+ """The complete provider request: every pass-through field, final
+ ``messages`` and ``tools``; never the Headroom control keys."""
+ out = {k: v for k, v in body.items() if k not in BODY_CONTROL_KEYS}
+ out["messages"] = messages
+ if tools is not None:
+ out["tools"] = tools
+ return out
+
+
+def build_route(request: Any, provider_body: dict[str, Any], provider: str) -> dict[str, Any]:
+ """Routing advice for the gateway. Headroom only advises — the gateway
+ picks the upstream — but a routing extension's model choice is written
+ into the body, as ``BackendResolver.for_request`` does on the proxy path,
+ so ``route.model`` and ``body.model`` never disagree."""
+ from headroom.proxy.route_advice import advice_from
+
+ advice = advice_from(request)
+ if advice is not None:
+ provider_body["model"] = advice.model
+ return {
+ "model": provider_body.get("model"),
+ "provider": (advice.provider if advice is not None and advice.provider else provider),
+ "service_tier": provider_body.get("service_tier"),
+ "reason": advice.reason if advice is not None else "",
+ }
+
+
+def compute_obligations(caps: GatewayCapabilities, *, redrive_armed: bool) -> list[str]:
+ obligations: list[str] = []
+ if caps.redrive_allowed and redrive_armed:
+ obligations.append(OBLIGATION_REDRIVE)
+ if caps.can_relay_response:
+ obligations.append(OBLIGATION_RELAY_USAGE)
+ return obligations
+
+
+def new_turn_id() -> str:
+ return uuid.uuid4().hex
+
+
+def gateway_response_fields(
+ *,
+ request: Any,
+ body: dict[str, Any],
+ caps: GatewayCapabilities,
+ provider: str,
+ messages: list[dict[str, Any]],
+ tools: Any,
+ obligations: list[str],
+ turn_id: str,
+ headers: dict[str, str] | None = None,
+) -> dict[str, Any]:
+ """The keys gateway mode adds to every ``/v1/compress`` answer, including
+ the fail-open ones (originals, no obligations, no headers)."""
+ provider_body = build_provider_body(body, messages, tools)
+ return {
+ "body": provider_body,
+ "turn_id": turn_id,
+ "route": build_route(request, provider_body, provider),
+ "obligations": list(obligations),
+ "gateway": caps.echo(),
+ "headers": dict(headers or {}),
+ }
+
+
+# --------------------------------------------------------------------------- #
+# Output shaping #
+# --------------------------------------------------------------------------- #
+
+
+def shape_gateway_body(
+ provider_body: dict[str, Any],
+ *,
+ provider: str,
+ model_name: str,
+ config: Any,
+ input_tokens: int,
+ transforms: list[str],
+) -> bool:
+ """Verbosity steering on the provider body (chat-handler parity, request-only).
+
+ Same gates as both chat handlers: ``shaper_enabled_for(config)`` (the
+ ``proxy_output_shaper`` rollout / ``HEADROOM_OUTPUT_SHAPER``),
+ ``steering_allowed_for(config)`` (off in ``mode="cache"``), the
+ conversation-stable ``HEADROOM_OUTPUT_HOLDOUT`` arm, and the level from
+ ``resolve_verbosity_level``. Anthropic bodies get the block appended to
+ ``system``; OpenAI chat bodies to the last system/developer message.
+
+ The (arm, stratum) label always goes on ``transforms`` when the shaper is
+ enabled — treatment or control — because that label is what the outcome
+ funnel (``record_from_labels`` / ``estimate_request_savings``) reads to
+ turn the relayed ``output_tokens`` into output savings. The steering block
+ is byte-stable per level, so turn N+1 reproduces turn N's prefix.
+
+ Mutates ``provider_body`` in place on copies of the fields it writes, so a
+ session snapshot taken before this call (``record_returned``) never sees
+ the steering block: the client resends its own system prompt every turn
+ and the block is re-appended deterministically. Never raises.
+ """
+ try:
+ from headroom.proxy import runtime_env
+ from headroom.proxy.output_savings import (
+ assign_arm,
+ conversation_key_from_body,
+ stratum_key,
+ stratum_label,
+ )
+ from headroom.proxy.output_shaper import (
+ OutputShaperSettings,
+ classify_turn,
+ resolve_verbosity_level,
+ shape_openai_chat_request,
+ shape_request,
+ shaper_enabled_for,
+ steering_allowed_for,
+ )
+
+ settings = OutputShaperSettings.from_env(
+ enabled=shaper_enabled_for(config),
+ steering_enabled=steering_allowed_for(config),
+ )
+ if not settings.enabled:
+ return False
+ try:
+ holdout = float(runtime_env.getenv("HEADROOM_OUTPUT_HOLDOUT", "0") or "0")
+ except ValueError:
+ holdout = 0.0
+ arm = assign_arm(conversation_key_from_body(provider_body), holdout)
+ messages = provider_body.get("messages")
+ turn_kind = classify_turn(messages if isinstance(messages, list) else []).value
+ stratum = stratum_key(
+ turn_kind=turn_kind,
+ input_tokens=int(input_tokens or 0),
+ model=model_name,
+ has_tools=bool(provider_body.get("tools")),
+ )
+ transforms.append(stratum_label(arm, stratum))
+ if arm != "treatment":
+ return False
+ level, _src = resolve_verbosity_level(settings)
+
+ if provider == "anthropic":
+ if provider_body.get("system") is not None:
+ provider_body["system"] = copy.deepcopy(provider_body["system"])
+ result = shape_request(provider_body, settings, level_override=level)
+ else:
+ if isinstance(messages, list):
+ # The injector mutates the target message dict in place; give
+ # it a private copy so the session snapshot stays pristine.
+ shallow = list(messages)
+ target_index = None
+ for index, message in enumerate(shallow):
+ if isinstance(message, dict) and message.get("role") in ("system", "developer"):
+ target_index = index
+ if target_index is not None:
+ shallow[target_index] = copy.deepcopy(shallow[target_index])
+ provider_body["messages"] = shallow
+ result = shape_openai_chat_request(provider_body, settings, level_override=level)
+ if result.changed:
+ transforms.extend(result.labels or [])
+ return bool(result.changed)
+ except Exception: # shaping is best-effort; never fail the turn
+ logger.exception("gateway turn: output shaping failed; body left as built")
+ return False
+
+
+def register_pending_turn(
+ proxy: Any,
+ *,
+ turn_id: str,
+ session_key: str | None,
+ session_id: str | None,
+ provider: str,
+ model: str,
+ body: dict[str, Any],
+ ctx: TurnContext | None,
+ obligations: list[str],
+ outcome_draft: RequestOutcome | None,
+ tags: dict[str, Any],
+ client: str | None,
+ ccr_armed: bool = False,
+) -> PendingTurn | None:
+ """Register the turn when there is something to wait for; ``None`` otherwise."""
+ registry = getattr(proxy, "gateway_turns", None)
+ if registry is None or not obligations:
+ return None
+ now = time.time()
+ turn = PendingTurn(
+ turn_id=turn_id,
+ session_key=session_key,
+ session_id=session_id,
+ provider=provider,
+ model=model,
+ body=body,
+ ctx=ctx,
+ obligations=list(obligations),
+ outcome_draft=outcome_draft,
+ created_at=now,
+ deadline=now + registry.ttl_seconds,
+ max_rounds=_env_int("HEADROOM_GATEWAY_MAX_REDRIVES", DEFAULT_MAX_REDRIVES),
+ tags=tags,
+ client=client,
+ ccr_armed=ccr_armed,
+ )
+ registry.register(turn)
+ return turn
+
+
+# --------------------------------------------------------------------------- #
+# Response half #
+# --------------------------------------------------------------------------- #
+
+
+def _error(status: int, error_type: str, message: str) -> Any:
+ from fastapi.responses import JSONResponse
+
+ return JSONResponse(
+ status_code=status, content={"error": {"type": error_type, "message": message}}
+ )
+
+
+async def apply_session_usage(
+ proxy: Any, turn: PendingTurn, usage: NormalizedUsage | None
+) -> tuple[int | None, bool]:
+ """Feed provider-confirmed cache counts to the session tracker.
+
+ Same rules and same locking as ``/v1/usage``: only under the session turn
+ lock, on the executor, and only when the usage carries a positive cache
+ signal or a genuine both-zero cold assertion. Returns
+ ``(frozen_message_count, applied)``; ``(None, False)`` for a stateless
+ turn or an expired session. A lock timeout is reported as not applied
+ rather than raised: the turn is finishing and the gateway has nothing to
+ retry with.
+ """
+ if turn.session_key is None:
+ return None, False
+ tracker = proxy.session_tracker_store.peek(turn.session_key)
+ if tracker is None:
+ return None, False
+ if usage is None or not usage.should_apply:
+ return tracker.get_frozen_message_count(), False
+ comp_cache = proxy._peek_compression_cache(turn.session_key)
+ cache_read = usage.cache_read or 0
+ cache_write = usage.cache_write or 0
+
+ from headroom.proxy.handlers.openai import _SESSION_TURN_LOCK_TIMEOUT_SECONDS
+ from headroom.proxy.helpers import COMPRESSION_TIMEOUT_SECONDS
+
+ def _apply() -> int | None:
+ lock = comp_cache.session_turn_lock if comp_cache is not None else None
+ if lock is not None and not lock.acquire(timeout=_SESSION_TURN_LOCK_TIMEOUT_SECONDS):
+ raise TimeoutError(f"session turn lock busy for {turn.session_id!r}")
+ try:
+ last_returned = tracker.get_last_forwarded_messages()
+ if not last_returned:
+ return None
+ tracker.update_from_response(
+ cache_read_tokens=cache_read,
+ cache_write_tokens=cache_write,
+ messages=last_returned,
+ original_messages=tracker.get_last_original_messages(),
+ )
+ return int(tracker.get_frozen_message_count())
+ finally:
+ if lock is not None:
+ lock.release()
+
+ try:
+ frozen = await proxy._run_compression_in_executor(
+ _apply, timeout=COMPRESSION_TIMEOUT_SECONDS
+ )
+ except TimeoutError:
+ logger.warning(
+ "gateway turn %s: session %r busy; usage relay not applied",
+ turn.turn_id,
+ turn.session_id,
+ )
+ return tracker.get_frozen_message_count(), False
+ if frozen is None:
+ return tracker.get_frozen_message_count(), False
+ return frozen, True
+
+
+def complete_outcome(
+ draft: RequestOutcome,
+ usage: NormalizedUsage | None,
+ *,
+ status: int,
+ latency_ms: float | None,
+) -> RequestOutcome:
+ """Fill the response-side fields of a deferred outcome draft.
+
+ Only fields ``RequestOutcome`` already carries: billed input lands in
+ ``provider_input_tokens`` (never ``optimized_tokens`` — different
+ tokenizer scale), output and the two cache counters as reported, provider
+ status so a 5xx is funnelled as a failure, and the gateway's provider
+ latency added to the compress-side wall clock.
+ """
+ usage = usage or NormalizedUsage()
+ return dataclasses.replace(
+ draft,
+ output_tokens=usage.output_tokens or 0,
+ provider_input_tokens=usage.input_tokens or 0,
+ cache_read_tokens=usage.cache_read or 0,
+ cache_write_tokens=usage.cache_write or 0,
+ status_code=status,
+ total_latency_ms=draft.total_latency_ms + float(latency_ms or 0.0),
+ )
+
+
+def _emit_response_received(proxy: Any, turn: PendingTurn, response: Any, status: int) -> None:
+ pipeline = getattr(proxy, "pipeline_extensions", None)
+ if pipeline is None or not getattr(pipeline, "enabled", False):
+ return
+ try:
+ from headroom.pipeline import PipelineStage
+
+ pipeline.emit(
+ PipelineStage.RESPONSE_RECEIVED,
+ operation="gateway.turn",
+ request_id=(turn.outcome_draft.request_id if turn.outcome_draft else turn.turn_id),
+ provider=turn.provider,
+ model=turn.model,
+ response=response,
+ metadata={
+ "path": "/v1/compress/response",
+ "stream": False,
+ "status_code": status,
+ "turn_id": turn.turn_id,
+ "rounds": turn.rounds,
+ },
+ )
+ except Exception: # telemetry must never break a response
+ logger.debug("RESPONSE_RECEIVED emit failed", exc_info=True)
+
+
+def _redrive_payload(turn: PendingTurn, step: Step) -> dict[str, Any]:
+ """The ``redrive`` answer for ``step``; also what a stale retry gets again.
+
+ Mirrors ``_hook_call_model`` on the proxy path: the hook's message list plus
+ its (possibly reloaded) tools, everything else exactly as the gateway sent.
+ """
+ redrive_body = dict(turn.body)
+ redrive_body["messages"] = step.messages
+ if step.tools is not None:
+ redrive_body["tools"] = step.tools
+ return {
+ "action": "redrive",
+ "turn_id": turn.turn_id,
+ "request": redrive_body,
+ "round": turn.rounds,
+ }
+
+
+async def handle_compress_response(proxy: Any, request: Any) -> Any:
+ """``POST /v1/compress/response`` — finish or re-drive a pending turn."""
+ from fastapi.responses import JSONResponse
+
+ from headroom.proxy.helpers import _read_request_json
+
+ try:
+ body = await _read_request_json(request)
+ except Exception:
+ return _error(400, "invalid_request", "Invalid JSON in request body.")
+ if not isinstance(body, dict):
+ return _error(400, "invalid_request", "Request body must be a JSON object.")
+
+ turn_id = body.get("turn_id")
+ if not isinstance(turn_id, str) or not turn_id.strip() or len(turn_id) > 128:
+ return _error(400, "invalid_request", "Missing or invalid turn_id.")
+
+ status = body.get("status", 200)
+ if status is None:
+ status = 200
+ if isinstance(status, bool) or not isinstance(status, int) or not (100 <= status <= 599):
+ return _error(400, "invalid_request", "status must be an HTTP status code.")
+ latency_ms = body.get("latency_ms")
+ if latency_ms is not None and (
+ isinstance(latency_ms, bool) or not isinstance(latency_ms, (int, float)) or latency_ms < 0
+ ):
+ return _error(400, "invalid_request", "latency_ms must be a non-negative number.")
+ raw_usage = body.get("usage")
+ if raw_usage is not None and not isinstance(raw_usage, dict):
+ return _error(400, "invalid_request", "usage must be an object when present.")
+ response = body.get("response")
+ if response is not None and not isinstance(response, dict):
+ return _error(400, "invalid_request", "response must be an object when present.")
+ # Validate the usage before touching the turn: a bad relay must not leave
+ # a half-driven coroutine behind.
+ usage: NormalizedUsage | None = None
+ if raw_usage is not None:
+ try:
+ usage = normalize_usage(raw_usage)
+ except GatewayRequestError as e:
+ return _error(400, "invalid_request", e.message)
+
+ registry = getattr(proxy, "gateway_turns", None)
+ turn = registry.get(turn_id) if registry is not None else None
+ if turn is None:
+ return _error(
+ 404,
+ "unknown_turn",
+ f"No pending turn {turn_id!r} (never registered, already finished, or expired).",
+ )
+ if OBLIGATION_REDRIVE in turn.obligations and response is None:
+ return _error(
+ 400,
+ "missing_response",
+ "This turn carries the 'redrive' obligation; the provider response is required.",
+ )
+ if turn.in_flight:
+ return _error(409, "turn_busy", f"Turn {turn_id!r} is already being driven.")
+
+ # `round` makes the half idempotent. It names which provider call this
+ # response answers: 0 is the original forward, n is the n-th re-drive
+ # (the `round` this endpoint returned). Without it a gateway whose socket
+ # dropped after we answered "redrive" would re-post round 0 and the parked
+ # hook would take it as the answer to a re-drive the gateway never sent —
+ # and the usage below would bill that response twice.
+ round_no = body.get("round")
+ if round_no is not None and (
+ isinstance(round_no, bool) or not isinstance(round_no, int) or round_no < 0
+ ):
+ return _error(400, "invalid_request", "round must be a non-negative integer.")
+ if round_no is not None and round_no != turn.rounds:
+ if round_no > turn.rounds:
+ return _error(
+ 400,
+ "round_out_of_sequence",
+ f"Turn {turn_id!r} is waiting for round {turn.rounds}, got {round_no}.",
+ )
+ # A stale retry: repeat the last answer without consuming anything.
+ last = turn.runner.last_step if turn.runner is not None else None
+ if last is not None and last.is_redrive:
+ return JSONResponse(_redrive_payload(turn, last))
+ return _error(
+ 409,
+ "round_already_answered",
+ f"Round {round_no} of turn {turn_id!r} was already answered.",
+ )
+
+ turn.in_flight = True
+ try:
+ if usage is not None:
+ turn.usage = usage if turn.usage is None else turn.usage.merged_with(usage)
+
+ step: Step | None = None
+ if turn.hooks_armed and turn.ctx is not None:
+ runner = turn.runner
+ try:
+ if runner is None:
+ if status == 200 and isinstance(response, dict):
+ runner = turn.runner = SuspendedHookRunner(
+ turn.ctx, run=make_response_runner(proxy, turn)
+ )
+ step = await runner.start(response)
+ elif runner.state == "awaiting_redrive":
+ step = await runner.resume(response) # type: ignore[arg-type]
+ else:
+ # A repeated call after the hooks finished (gateway retry):
+ # answer the same thing again rather than re-running.
+ step = runner.last_step
+ except Exception:
+ # A failure to start/resume ends the turn with the gateway's
+ # own response; hooks are best-effort by contract.
+ logger.exception("gateway turn %s: hook driver failed", turn_id)
+ if runner is not None:
+ await runner.cancel()
+ step = Step("done", response=None)
+
+ if step is not None and step.is_redrive:
+ turn.rounds += 1
+ if turn.rounds > turn.max_rounds:
+ logger.warning(
+ "gateway turn %s: hit max re-drive rounds (%d); returning latest response",
+ turn_id,
+ turn.max_rounds,
+ )
+ if turn.runner is not None:
+ await turn.runner.cancel()
+ step = Step("done", response=None)
+ else:
+ # Refresh the deadline: the gateway is actively working the turn.
+ turn.deadline = time.time() + (registry.ttl_seconds if registry else 0)
+ return JSONResponse(_redrive_payload(turn, step))
+
+ final_response = step.response if step is not None else None
+ frozen, applied = await apply_session_usage(proxy, turn, turn.usage)
+ if turn.outcome_draft is not None:
+ outcome = complete_outcome(
+ turn.outcome_draft, turn.usage, status=status, latency_ms=latency_ms
+ )
+ turn.outcome_draft = None
+ await proxy._record_request_outcome(outcome)
+ _emit_response_received(
+ proxy, turn, final_response if final_response is not None else response, status
+ )
+ if registry is not None:
+ registry.pop(turn_id)
+ return JSONResponse(
+ {
+ "action": "done",
+ "turn_id": turn_id,
+ "response": final_response,
+ "frozen_message_count": frozen,
+ "usage_applied": applied,
+ "rounds": turn.rounds,
+ }
+ )
+ finally:
+ turn.in_flight = False
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.py
index b648ba0a1..3920a1332 100644
--- a/headroom/proxy/handlers/anthropic.py
+++ b/headroom/proxy/handlers/anthropic.py
@@ -3111,6 +3111,20 @@ class AnthropicHandlerMixin:
tags["turn_hook_tools_saved_tokens"] = (
int(tags.get("turn_hook_tools_saved_tokens", 0) or 0) + _th_saved
)
+ # Provider headers a hook asked for (``TurnContext.provider_headers``):
+ # allow-listed names only, ``anthropic-beta`` merged behind the
+ # client's own tokens — the same reduction the gateway contract
+ # applies before handing ``headers`` to the gateway.
+ _hook_headers = getattr(_req_ctx, "provider_headers", None)
+ if isinstance(_hook_headers, dict) and _hook_headers:
+ from headroom.proxy.turn_hooks import merge_provider_headers
+
+ for _hh_key, _hh_value in merge_provider_headers(
+ {"anthropic-beta": headers.get("anthropic-beta", "")}, _hook_headers
+ ).items():
+ if _hh_key == "anthropic-beta" and headers.get(_hh_key) != _hh_value:
+ _headroom_beta_added = True
+ headers[_hh_key] = _hh_value
# Tool-search history repair (#2805). Once deferral is on, the client
# stores Anthropic's server_tool_use / tool_search_tool_result blocks in
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index 9d49650e5..42edd7024 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -9705,8 +9705,32 @@ class OpenAIHandlerMixin:
"""
from fastapi.responses import JSONResponse
+ # Compress-turn extensions (headroom/proxy/compress_turn.py). A
+ # registered contract — the built-in gateway turn contract, installed
+ # by create_app through the same seam a third party would use — may
+ # claim the body (`begin`), transform the outbound messages on the
+ # executor, add response fields (`finish`) and take ownership of the
+ # outcome (`commit`). With none claiming it — legacy mode — nothing
+ # below this comment changes behaviour.
+ from headroom.proxy.compress_turn import CompressTurnError, begin_compress_turn
from headroom.proxy.helpers import _read_request_json
+ def _gateway_invalid(e: CompressTurnError) -> JSONResponse:
+ return JSONResponse(
+ status_code=400,
+ content={"error": {"type": "invalid_request", "message": e.message}},
+ )
+
+ def _begin_turn(body: Any):
+ if not isinstance(body, dict):
+ return None
+ return begin_compress_turn(
+ proxy=self,
+ request=request,
+ body=body,
+ client=classify_client(dict(request.headers)),
+ )
+
# Check bypass header
if request.headers.get("x-headroom-bypass", "").lower() == "true":
try:
@@ -9717,17 +9741,22 @@ class OpenAIHandlerMixin:
content={"error": f"Invalid request body: {e!s}"},
)
messages = body.get("messages", [])
- return JSONResponse(
- {
- "messages": messages,
- "tokens_before": 0,
- "tokens_after": 0,
- "tokens_saved": 0,
- "compression_ratio": 1.0,
- "transforms_applied": [],
- "ccr_hashes": [],
- }
- )
+ _bypass_payload = {
+ "messages": messages,
+ "tokens_before": 0,
+ "tokens_after": 0,
+ "tokens_saved": 0,
+ "compression_ratio": 1.0,
+ "transforms_applied": [],
+ "ccr_hashes": [],
+ }
+ try:
+ _bypass_turn = _begin_turn(body)
+ except CompressTurnError as e:
+ return _gateway_invalid(e)
+ if _bypass_turn is not None:
+ _bypass_payload.update(_bypass_turn.fail_open_fields(messages))
+ return JSONResponse(_bypass_payload)
try:
body = await _read_request_json(request)
@@ -9767,18 +9796,24 @@ class OpenAIHandlerMixin:
},
)
+ try:
+ _turn = _begin_turn(body)
+ except CompressTurnError as e:
+ return _gateway_invalid(e)
+
if not messages:
- return JSONResponse(
- {
- "messages": [],
- "tokens_before": 0,
- "tokens_after": 0,
- "tokens_saved": 0,
- "compression_ratio": 1.0,
- "transforms_applied": [],
- "ccr_hashes": [],
- }
- )
+ _empty_payload = {
+ "messages": [],
+ "tokens_before": 0,
+ "tokens_after": 0,
+ "tokens_saved": 0,
+ "compression_ratio": 1.0,
+ "transforms_applied": [],
+ "ccr_hashes": [],
+ }
+ if _turn is not None:
+ _empty_payload.update(_turn.fail_open_fields([]))
+ return JSONResponse(_empty_payload)
start_time = time.time()
headers = dict(request.headers)
@@ -9990,13 +10025,25 @@ class OpenAIHandlerMixin:
_session_key, _tracker_provider
)
+ # A claimed turn prepares its executor-side work here (tokenizer,
+ # hooks, scope binding) — CPU-bound parts run inside the closures
+ # below with the rest of the turn.
+ if _turn is not None:
+ _turn.prepare(model_name=model_name, tags=tags, config=self.config)
+
def _run_stateless():
result = pipeline.apply(messages=messages, model=model, **pipeline_kwargs)
+ final = result.messages
+ tokens_after = result.tokens_after
+ if _turn is not None:
+ final = _turn.transform(final)
+ if _turn.folded_messages:
+ tokens_after = _turn.count_messages(final, tokens_after)
return (
result,
- result.messages,
+ final,
result.tokens_before,
- result.tokens_after,
+ tokens_after,
None,
)
@@ -10053,6 +10100,14 @@ class OpenAIHandlerMixin:
# the caller forwards on.
turn = finalize_turn(result.messages, messages, prev_original, prev_returned)
final = turn.messages
+ if _turn is not None:
+ # AFTER the replay overlay, BEFORE update_from_result /
+ # record_returned: the turn's output is what the caller
+ # forwards, so it must be what next turn's snapshot
+ # replays. A transform that is not a pure function of
+ # its input busts the prefix here as it would on the
+ # proxy.
+ final = _turn.transform(final)
# Savings are reported against the caller's RAW payload,
# not the cache-swapped pipeline input: on a warm turn the
# swap has already shrunk the input before the pipeline
@@ -10115,34 +10170,58 @@ class OpenAIHandlerMixin:
tokens_saved = max(0, tokens_before - tokens_after)
latency_ms = (time.time() - start_time) * 1000
- await self._record_request_outcome(
- RequestOutcome(
- request_id=(
- await self._next_request_id()
- if hasattr(self, "_next_request_id")
- else f"compress_{int(time.time())}"
- ),
- provider="compress",
- model=model if isinstance(model, str) else str(model),
- original_tokens=tokens_before,
- optimized_tokens=tokens_after,
- output_tokens=0,
- tokens_saved=tokens_saved,
- attempted_input_tokens=tokens_before,
- total_latency_ms=latency_ms,
- overhead_ms=latency_ms,
- num_messages=len(messages) if isinstance(messages, list) else 0,
- transforms_applied=tuple(result.transforms_applied or ()),
- waste_signals=(
- result.waste_signals.to_dict()
- if getattr(result, "waste_signals", None) is not None
- else None
- ),
- pipeline_timing=getattr(result, "timing", None) or None,
- tags=tags,
- client=client,
+ _transforms_applied = list(result.transforms_applied or ())
+ # The claimed turn adds its labels and response fields BEFORE the
+ # outcome is built, so the outcome's transforms carry them.
+ _finished = None
+ if _turn is not None:
+ _finished = _turn.finish(
+ messages=final_messages,
+ tokens_before=tokens_before,
+ transforms_applied=_transforms_applied,
+ mode=mode,
+ ccr_hashes=ccr_hashes,
)
+ _transforms_applied = list(_finished.transforms)
+ if _finished.messages is not None:
+ final_messages = _finished.messages
+ _outcome = RequestOutcome(
+ request_id=(
+ await self._next_request_id()
+ if hasattr(self, "_next_request_id")
+ else f"compress_{int(time.time())}"
+ ),
+ provider="compress",
+ model=model if isinstance(model, str) else str(model),
+ original_tokens=tokens_before,
+ optimized_tokens=tokens_after,
+ output_tokens=0,
+ tokens_saved=tokens_saved,
+ attempted_input_tokens=tokens_before,
+ total_latency_ms=latency_ms,
+ overhead_ms=latency_ms,
+ num_messages=len(messages) if isinstance(messages, list) else 0,
+ transforms_applied=tuple(_transforms_applied or ()),
+ waste_signals=(
+ result.waste_signals.to_dict()
+ if getattr(result, "waste_signals", None) is not None
+ else None
+ ),
+ pipeline_timing=getattr(result, "timing", None) or None,
+ tags=tags,
+ client=client,
)
+ # A claimed turn may take ownership of the outcome (a gateway waits
+ # for the relayed usage); otherwise it is recorded now.
+ _deferred = False
+ if _turn is not None:
+ _deferred = _turn.commit(
+ _outcome,
+ session_key=(_session_key if session_id else None),
+ session_id=session_id,
+ )
+ if not _deferred:
+ await self._record_request_outcome(_outcome)
_payload = {
"messages": final_messages,
@@ -10154,12 +10233,14 @@ class OpenAIHandlerMixin:
# telemetry records 0 would be two answers for one number.
"tokens_saved": tokens_saved,
"compression_ratio": (tokens_after / tokens_before if tokens_before > 0 else 1.0),
- "transforms_applied": result.transforms_applied,
+ "transforms_applied": _transforms_applied,
"transforms_summary": result.transforms_summary,
"ccr_hashes": ccr_hashes,
}
if session_info is not None:
_payload["session"] = session_info
+ if _finished is not None and _finished.fields:
+ _payload.update(_finished.fields)
return JSONResponse(_payload)
except TimeoutError:
self.metrics.record_compression_failed("timeout")
@@ -10242,20 +10323,21 @@ class OpenAIHandlerMixin:
client=client,
)
)
- return JSONResponse(
- content={
- "messages": messages,
- "tokens_before": 0,
- "tokens_after": 0,
- "tokens_saved": 0,
- "compression_ratio": 1.0,
- "transforms_applied": [],
- "transforms_summary": {},
- "ccr_hashes": [],
- "compression_skipped": True,
- "skip_reason": "compression_timeout",
- },
- )
+ _timeout_payload = {
+ "messages": messages,
+ "tokens_before": 0,
+ "tokens_after": 0,
+ "tokens_saved": 0,
+ "compression_ratio": 1.0,
+ "transforms_applied": [],
+ "transforms_summary": {},
+ "ccr_hashes": [],
+ "compression_skipped": True,
+ "skip_reason": "compression_timeout",
+ }
+ if _turn is not None:
+ _timeout_payload.update(_turn.fail_open_fields(messages))
+ return JSONResponse(content=_timeout_payload)
except Exception as e:
logger.exception("Compression failed: %s", e)
await self.metrics.record_failed(provider="compress")
@@ -10315,6 +10397,17 @@ class OpenAIHandlerMixin:
usage = body.get("usage")
if not isinstance(usage, dict):
return _invalid("Missing or invalid usage: expected an object.")
+ # OpenAI-shaped relays (Kong's log statistics, an OpenAI-mapped
+ # gateway) carry the cache read under prompt_tokens_details.cached_tokens
+ # or a flat cached_tokens. Map it to the Anthropic read field so the
+ # relay is not a 400. OpenAI has no write signal, so the write field
+ # stays absent and the only-present-field-is-zero rule below applies.
+ if "cache_read_input_tokens" not in usage and "cache_creation_input_tokens" not in usage:
+ _details = usage.get("prompt_tokens_details")
+ if isinstance(_details, dict) and "cached_tokens" in _details:
+ usage = {**usage, "cache_read_input_tokens": _details["cached_tokens"]}
+ elif "cached_tokens" in usage:
+ usage = {**usage, "cache_read_input_tokens": usage["cached_tokens"]}
# A usage block carrying NEITHER cache field is a no-signal relay (an
# OpenAI-style {"prompt_tokens": N} forwarded verbatim, for example).
# Defaulting the absent fields to 0 would make update_from_response
diff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.py
index 2231f9ae0..2d4f1d700 100644
--- a/headroom/proxy/helpers.py
+++ b/headroom/proxy/helpers.py
@@ -3130,6 +3130,68 @@ _TOOL_SEARCH_DEFAULT_NAME = "tool_search_tool_regex"
_TOOL_SEARCH_MIN_TOOLS = 12
+# Model-id shapes that name a Bedrock or Vertex deployment. The chat path
+# excludes those upstreams by base URL / backend (it knows where it forwards);
+# on the gateway contract the gateway routes, so the model id is the only
+# signal. Shared with the tool-search extension, which applies deferral on the
+# gateway path.
+_NON_FIRST_PARTY_MODEL_PREFIXES: tuple[str, ...] = (
+ "bedrock/",
+ "vertex_ai/",
+ "vertex/",
+ "anthropic.", # bare Bedrock ids: anthropic.claude-3-5-sonnet-20241022-v2:0
+ "us.anthropic.",
+ "eu.anthropic.",
+ "apac.anthropic.",
+ "global.anthropic.",
+)
+_BEDROCK_VERSION_SUFFIX = re.compile(r"-v\d+(:\d+)?$")
+
+
+def anthropic_model_is_first_party(model_name: str) -> bool:
+ """Whether ``model_name`` is a first-party Claude API id (not Bedrock/Vertex).
+
+ First-party tool search (``tool_search_tool_*`` + ``defer_loading``) is
+ rejected by Bedrock and Vertex, which the chat path skips by upstream URL.
+ Gateway callers name those deployments in the model id instead:
+ ``bedrock/anthropic.claude-…``, ``anthropic.claude-…-v2:0``,
+ ``vertex_ai/claude-…``, ``claude-sonnet-4@20250514``. A LiteLLM-style
+ ``anthropic/claude-…`` prefix is first-party and stays eligible.
+ """
+ lowered = (model_name or "").strip().lower()
+ if not lowered:
+ return False
+ if lowered.startswith(_NON_FIRST_PARTY_MODEL_PREFIXES):
+ return False
+ if "@" in lowered: # Vertex dated ids
+ return False
+ return not _BEDROCK_VERSION_SUFFIX.search(lowered)
+
+
+def tools_are_anthropic_shaped(tools: Any) -> bool:
+ """Every dict tool is Anthropic-shaped (top-level ``name``/``input_schema``
+ or a typed server tool), and none carries the OpenAI ``function`` wrapper.
+
+ ``provider`` is inferred from the model name, and a LiteLLM-style caller
+ can pair a Claude model with chat-completions tools; deferral must not
+ touch those (Anthropic would never see this shape as-is anyway).
+ """
+ if not isinstance(tools, list) or not tools:
+ return False
+ saw_real_tool = False
+ for tool in tools:
+ if not isinstance(tool, dict):
+ return False
+ if "function" in tool:
+ return False
+ if tool.get("type"):
+ continue # typed server tool (web_search, computer, …)
+ if not tool.get("name") or "input_schema" not in tool:
+ return False
+ saw_real_tool = True
+ return saw_real_tool
+
+
def _tool_search_resident_key(name: Any) -> str:
"""Normalize a client tool name for resident-tool membership checks."""
# Oh My Pi prefixes every built-in with ``_``. Strip only leading namespace
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index d215d9752..9cd7694d7 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -1104,6 +1104,11 @@ class HeadroomProxy(
self._compression_caches_last_cleanup: float = time.time()
self._compression_caches_lock = threading.RLock()
+ # Gateway turn contract: its pending-turn registry (`gateway_turns`) is
+ # attached by headroom.proxy.gateway_extension.install, which
+ # create_app runs by default (HEADROOM_GATEWAY_CONTRACT=0 leaves it out).
+ self.gateway_turns = None
+
self.logger = (
RequestLogger(
log_file=config.log_file,
@@ -5509,6 +5514,16 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
async def compress_usage(request: Request):
return await proxy.handle_compress_usage(request)
+ # Contracts layered on /v1/compress install through the compress-turn seam
+ # (headroom/proxy/compress_turn.py). The gateway turn contract is built in
+ # and on by default; it adds /v1/compress/response under the same exposure
+ # policy as /v1/compress. A third-party contract's install(app, config)
+ # can read the policy from app.state.compress_route_dependencies.
+ app.state.compress_route_dependencies = list(_compress_dependencies)
+ from headroom.proxy.gateway_extension import install_builtin as _install_gateway_contract
+
+ _install_gateway_contract(app, config, route_dependencies=_compress_dependencies)
+
register_provider_routes(app, proxy)
return app
diff --git a/headroom/proxy/turn_hooks.py b/headroom/proxy/turn_hooks.py
index 05d22c1cf..1b10aeaa8 100644
--- a/headroom/proxy/turn_hooks.py
+++ b/headroom/proxy/turn_hooks.py
@@ -53,6 +53,12 @@ class TurnContext:
tags: dict[str, Any] = field(default_factory=dict)
count_messages: Callable[[list[dict[str, Any]]], int] | None = None
count_tools: Callable[[Any], int] | None = None
+ # Outbound headers a request hook wants on the provider request, name ->
+ # value. The handler merges them through :func:`merge_provider_headers`:
+ # only allow-listed names are honoured, and ``anthropic-beta`` is merged as
+ # a token set behind the client's own value rather than overwritten. On the
+ # gateway contract the merged map is the response's ``headers`` object.
+ provider_headers: dict[str, str] = field(default_factory=dict)
def record_savings(
self,
@@ -91,6 +97,14 @@ class TurnHook(Protocol):
# False (conservative). See :func:`run_request_hooks`.
stream_safe: bool
+ # Optional: run order among registered hooks, lowest first (stable for
+ # ties; absent ⇒ DEFAULT_HOOK_PRIORITY). Convention: routers that change
+ # ``ctx.model`` 10-49, message folds 50-99, tool-catalog shaping that is
+ # gated on the final model (deferral) 200+. Registration order is
+ # entry-point discovery order, which an operator does not control, so a
+ # hook whose correctness depends on running after another must say so.
+ priority: int
+
def on_request(self, ctx: TurnContext) -> None:
"""Inspect / mutate ``ctx`` (e.g. ``ctx.tools``) before it goes upstream."""
@@ -105,15 +119,65 @@ class TurnHook(Protocol):
_hooks: list[TurnHook] = []
+DEFAULT_HOOK_PRIORITY = 100
+
+#: Provider header names a hook may request through ``TurnContext.provider_headers``.
+PROVIDER_HEADER_ALLOWLIST: frozenset[str] = frozenset({"anthropic-beta"})
+
+
+def _priority(hook: Any) -> int:
+ try:
+ return int(getattr(hook, "priority", DEFAULT_HOOK_PRIORITY))
+ except (TypeError, ValueError):
+ return DEFAULT_HOOK_PRIORITY
+
def register_turn_hook(hook: TurnHook) -> None:
"""Register a hook. Called by an extension's ``install(app, config)``."""
_hooks.append(hook)
- log.info("registered turn hook: %s", getattr(hook, "name", type(hook).__name__))
+ log.info(
+ "registered turn hook: %s (priority %d)",
+ getattr(hook, "name", type(hook).__name__),
+ _priority(hook),
+ )
def registered_turn_hooks() -> list[TurnHook]:
- return list(_hooks)
+ """Registered hooks in run order: ``priority`` ascending, registration
+ order for ties."""
+ return sorted(_hooks, key=_priority)
+
+
+def merge_provider_headers(
+ client_headers: dict[str, str] | None, requested: dict[str, str] | None
+) -> dict[str, str]:
+ """Reduce hook-requested provider headers to what the handler may set.
+
+ Names outside :data:`PROVIDER_HEADER_ALLOWLIST` are dropped (debug log).
+ ``anthropic-beta`` merges as a token set: the client's tokens first, the
+ hook's appended, deduplicated — a hook may add a beta the feature needs
+ but never strip one the client asked for. Other allow-listed names are set
+ verbatim. Returns only the headers to set; an empty map means "nothing".
+ """
+ out: dict[str, str] = {}
+ if not isinstance(requested, dict) or not requested:
+ return out
+ client = {str(k).strip().lower(): v for k, v in (client_headers or {}).items()}
+ for name, value in requested.items():
+ key = str(name).strip().lower()
+ if key not in PROVIDER_HEADER_ALLOWLIST:
+ log.debug("turn hook requested header %r outside the allowlist; dropped", name)
+ continue
+ if not isinstance(value, str) or not value.strip():
+ continue
+ if key == "anthropic-beta":
+ from headroom.proxy.beta_header_merge import merge_anthropic_beta
+
+ tokens = [t.strip() for t in value.split(",") if t.strip()]
+ out[key] = merge_anthropic_beta(client.get(key) or None, tokens)
+ else:
+ out[key] = value
+ return out
def clear_turn_hooks() -> None:
@@ -134,7 +198,7 @@ def run_request_hooks(ctx: TurnContext, *, stream_safe_only: bool = False) -> No
working on streamed OpenAI-compatible traffic. Default off ⇒ conservative:
a hook is treated as buffered-only unless it declares itself stream-safe.
"""
- for hook in _hooks:
+ for hook in registered_turn_hooks():
if stream_safe_only and not getattr(hook, "stream_safe", False):
continue
fn = getattr(hook, "on_request", None)
@@ -179,7 +243,7 @@ async def run_response_hooks(
(returns ``response`` unchanged); a failing hook is logged and skipped.
"""
current = response
- for hook in _hooks:
+ for hook in registered_turn_hooks():
fn = getattr(hook, "on_response", None)
if fn is None:
continue
diff --git a/tests/gateway/__init__.py b/tests/gateway/__init__.py
new file mode 100644
index 000000000..1b251c952
--- /dev/null
+++ b/tests/gateway/__init__.py
@@ -0,0 +1,11 @@
+"""Gateway turn contract harness and tests (see the spec's section 6).
+
+Contents:
+
+* ``fake_provider`` - scriptable OpenAI/Anthropic upstream (ASGI + uvicorn thread)
+* ``fake_gateway`` - a Python "Kong": drives the two-half contract exactly as
+ the Lua plugin algorithm does, including the redrive loop
+* ``redrive_hook_ext`` - a re-driving turn hook shaped like headroom-tool-search
+* ``fold_only_hook`` - a stream-safe, fold-only turn hook
+* ``samples`` - deterministic conversation/tool builders shared by tests
+"""
diff --git a/tests/gateway/conftest.py b/tests/gateway/conftest.py
new file mode 100644
index 000000000..87ba36759
--- /dev/null
+++ b/tests/gateway/conftest.py
@@ -0,0 +1,162 @@
+"""Fixtures for the gateway turn contract tests.
+
+* ``make_headroom_client`` / ``headroom_client`` - the proxy app built like
+ ``tests/test_compress_session_mode.py::_make_client`` and served through a
+ loopback ``TestClient`` (``/v1/compress`` and ``/v1/compress/response`` are
+ loopback-gated).
+* ``fake_provider`` / ``provider_client`` - a :class:`FakeProvider` and a
+ ``TestClient`` mounted on its ASGI app.
+* ``make_gateway`` - a :class:`FakeGateway` factory bound to the two clients.
+* ``outcome_spy`` - captures every ``RequestOutcome`` the proxy records.
+* Autouse: turn hooks cleared before/after each test; ``HEADROOM_GATEWAY_*``
+ scrubbed (the repo conftest already scrubs every ``HEADROOM_*`` var, this one
+ makes the dependency explicit for the knobs these tests set).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+from collections.abc import Callable, Iterator
+from typing import Any
+
+import pytest
+
+pytest.importorskip("fastapi")
+
+from fastapi.testclient import TestClient # noqa: E402
+
+from headroom.proxy.server import ProxyConfig, create_app # noqa: E402
+from headroom.proxy.turn_hooks import clear_turn_hooks # noqa: E402
+from tests.gateway.fake_gateway import FakeGateway # noqa: E402
+from tests.gateway.fake_provider import FakeProvider # noqa: E402
+
+LOOPBACK = ("127.0.0.1", 12345)
+
+
[email protected](autouse=True)
+def _clear_hooks() -> Iterator[None]:
+ clear_turn_hooks()
+ yield
+ clear_turn_hooks()
+
+
[email protected](autouse=True)
+def _scrub_gateway_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ for key in list(os.environ):
+ if key.startswith("HEADROOM_GATEWAY_") or key.startswith("HEADROOM_TEST_REDRIVE_"):
+ monkeypatch.delenv(key, raising=False)
+
+
+def proxy_config(**overrides: Any) -> ProxyConfig:
+ """The same posture as the session-mode tests: optimize on, everything that
+ would reach the network or add per-request noise off."""
+ kwargs: dict[str, Any] = {
+ "optimize": True,
+ "cache_enabled": False,
+ "rate_limit_enabled": False,
+ "cost_tracking_enabled": False,
+ "log_requests": False,
+ "image_optimize": False,
+ }
+ kwargs.update(overrides)
+ return ProxyConfig(**kwargs)
+
+
+def make_headroom_client() -> Iterator[Callable[..., TestClient]]:
+ """Factory: ``make_headroom_client(**ProxyConfig overrides) -> TestClient``.
+
+ Each client is entered (lifespan started) and closed at teardown. Use the
+ factory when a test must set env vars BEFORE the app is created."""
+ opened: list[TestClient] = []
+
+ def _make(**overrides: Any) -> TestClient:
+ app = create_app(proxy_config(**overrides))
+ client = TestClient(app, base_url="http://127.0.0.1", client=LOOPBACK)
+ client.__enter__()
+ opened.append(client)
+ return client
+
+ yield _make
+ for client in reversed(opened):
+ client.__exit__(None, None, None)
+
+
+def headroom_client(make_headroom_client: Callable[..., TestClient]) -> TestClient:
+ return make_headroom_client()
+
+
+def fake_provider() -> FakeProvider:
+ return FakeProvider()
+
+
+def provider_client(fake_provider: FakeProvider) -> Iterator[TestClient]:
+ with TestClient(fake_provider.app) as client:
+ yield client
+
+
+def make_gateway(
+ headroom_client: TestClient, provider_client: TestClient
+) -> Callable[..., FakeGateway]:
+ def _make(**kwargs: Any) -> FakeGateway:
+ kwargs.setdefault("can_redrive", True)
+ kwargs.setdefault("can_relay_response", True)
+ return FakeGateway(headroom_client, provider_client, **kwargs)
+
+ return _make
+
+
+def outcome_spy(monkeypatch: pytest.MonkeyPatch) -> Callable[[Any], list[Any]]:
+ """``outcome_spy(client_or_app_or_proxy) -> list`` that fills with every
+ ``RequestOutcome`` recorded by that proxy instance (patched on the instance,
+ so two apps in one test get separate lists)."""
+
+ def _attach(target: Any) -> list[Any]:
+ proxy = target
+ if hasattr(target, "app"):
+ proxy = target.app.state.proxy
+ elif hasattr(target, "state"):
+ proxy = target.state.proxy
+ outcomes: list[Any] = []
+
+ async def _spy(outcome: Any, *args: Any, **kwargs: Any) -> None:
+ outcomes.append(outcome)
+
+ monkeypatch.setattr(proxy, "_record_request_outcome", _spy)
+ return outcomes
+
+ return _attach
+
+
+# --------------------------------------------------------------------------- #
+# Helpers (plain functions, importable from the tests) #
+# --------------------------------------------------------------------------- #
+
+
+def compress(
+ client: TestClient, body: dict[str, Any], *, headers: dict[str, str] | None = None
+) -> Any:
+ return client.post("/v1/compress", json=body, headers=headers)
+
+
+def gateway_block(**flags: Any) -> dict[str, Any]:
+ return dict(flags)
+
+
+def count_loop_tasks(client: TestClient) -> int:
+ """Number of asyncio tasks alive on the app's event loop (the TestClient
+ portal thread). Used to prove the response half leaks no suspended hook
+ tasks."""
+ assert client.portal is not None, "client must be entered"
+ return client.portal.call(lambda: len(asyncio.all_tasks()))
+
+
+def registry_of(client: TestClient) -> Any:
+ """The proxy's ``PendingTurnRegistry`` (``None`` until the core lands)."""
+ return getattr(client.app.state.proxy, "gateway_turns", None)
diff --git a/tests/gateway/deferral_hook.py b/tests/gateway/deferral_hook.py
new file mode 100644
index 000000000..0ad1feb34
--- /dev/null
+++ b/tests/gateway/deferral_hook.py
@@ -0,0 +1,111 @@
+"""Reference native tool-search deferral hook for the gateway contract tests.
+
+OSS core no longer defers tool schemas on the gateway path; the licensed
+tool-search extension's native tier does, through the ordinary turn-hook
+contract. This module is the smallest hook that exercises every seam that tier
+relies on, so the contract tests prove core carries a hook's deferral end to
+end without depending on the extension package:
+
+* the OSS primitives (``inject_tool_search_deferral`` and the two gate helpers
+ in ``headroom.proxy.helpers``) applied as a pure function of ``ctx.tools``;
+* the savings tags core's ``/stats`` headline reads
+ (``tool_search_deferred_tools`` / ``tool_search_deferred_tokens``) and the
+ ``tool_search`` attribution entry;
+* ``ctx.provider_headers`` for the ``anthropic-beta`` token, merged by core
+ behind the client's own value and surfaced as the response's ``headers``;
+* ``stream_safe = True`` so it runs when the gateway cannot re-drive (every
+ streamed Claude Code turn), and ``priority = 200`` so a router that changes
+ ``ctx.model`` has run before the first-party gate is evaluated.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from typing import Any
+
+from headroom.proxy.helpers import (
+ _TOOL_SEARCH_CORE_TOOLS,
+ anthropic_model_is_first_party,
+ inject_tool_search_deferral,
+ tools_are_anthropic_shaped,
+)
+from headroom.proxy.turn_hooks import register_turn_hook
+
+BETA_TOKEN = "advanced-tool-use-2025-11-20"
+_ON = ("1", "true", "yes", "on", "auto")
+
+
+@dataclass
+class DeferralHook:
+ name: str = "test_native_deferral"
+ savings_source: str = "tool_search"
+ stream_safe: bool = True
+ priority: int = 200
+ # Extra provider headers to request (tests the allowlist).
+ extra_headers: dict[str, str] | None = None
+ request_calls: int = 0
+ applied: int = 0
+
+ def on_request(self, ctx: Any) -> None:
+ self.request_calls += 1
+ if ctx.provider != "anthropic":
+ return
+ if os.environ.get("HEADROOM_TOOL_SEARCH", "1").strip().lower() not in _ON:
+ return
+ if not anthropic_model_is_first_party(ctx.model):
+ return
+ if not tools_are_anthropic_shaped(ctx.tools):
+ return
+ after = inject_tool_search_deferral(ctx.tools, core_tools=_TOOL_SEARCH_CORE_TOOLS)
+ if after is ctx.tools:
+ return
+ ctx.tools = after
+ deferred = [t for t in after if isinstance(t, dict) and t.get("defer_loading")]
+ saved = 0
+ if ctx.count_tools is not None:
+ try:
+ saved = int(ctx.count_tools(deferred))
+ except Exception:
+ saved = 0
+ ctx.tags["tool_search_deferred_tools"] = len(deferred)
+ ctx.tags["tool_search_deferred_tokens"] = saved
+ ctx.record_savings("tool_search", tokens=saved)
+ ctx.provider_headers["anthropic-beta"] = BETA_TOKEN
+ for key, value in (self.extra_headers or {}).items():
+ ctx.provider_headers[key] = value
+ self.applied += 1
+
+
+@dataclass
+class BufferedDeferralHook(DeferralHook):
+ """Same deferral, but declared NOT stream-safe: the gateway request half
+ must skip it whenever it cannot re-drive."""
+
+ name: str = "test_native_deferral_buffered"
+ stream_safe: bool = False
+
+
+@dataclass
+class ModelRouterHook:
+ """A router that rewrites ``ctx.model``; ``priority`` decides whether the
+ deferral hook sees the routed id or the original."""
+
+ target_model: str
+ name: str = "test_model_router"
+ stream_safe: bool = True
+ priority: int = 10
+
+ def on_request(self, ctx: Any) -> None:
+ ctx.model = self.target_model
+
+
+def register(hook: Any | None = None, **kwargs: Any) -> Any:
+ hook = hook if hook is not None else DeferralHook(**kwargs)
+ register_turn_hook(hook)
+ return hook
+
+
+def install(app: Any, config: Any) -> None:
+ """``headroom.proxy_extension`` entry-point shape."""
+ register()
diff --git a/tests/gateway/fake_gateway.py b/tests/gateway/fake_gateway.py
new file mode 100644
index 000000000..7b86aaa43
--- /dev/null
+++ b/tests/gateway/fake_gateway.py
@@ -0,0 +1,428 @@
+"""A Python "Kong": drives the gateway turn contract exactly as the Lua plugin does.
+
+Algorithm (spec section 5, ``access``/``body_filter``/``log`` phases collapsed
+into one synchronous ``turn``):
+
+1. POST ``{...body, config: {session_id, ...}, gateway: {...}}`` to
+ ``<headroom>/v1/compress``. ``can_redrive`` is ``allow_redrive and not
+ body.stream`` - a streaming client cannot be re-driven.
+2. Any transport error, non-200, or malformed answer from headroom -> FAIL OPEN:
+ forward the ORIGINAL body to the provider, no relay.
+3. Otherwise the provider-bound body is ``compress["body"]`` (legacy answers
+ without ``body`` fall back to ``{...body, messages: compress["messages"]}``).
+4. ``"redrive" in obligations`` -> LOOP PATH: call the provider, POST
+ ``{turn_id, status, latency_ms, usage, response}`` to
+ ``/v1/compress/response``; while ``action == "redrive"`` POST ``request`` to
+ the provider and post the answer back; on ``done`` the client sees
+ ``done.response`` or, when that is null, the last provider response.
+5. Else PROXY PATH: forward once; if ``relay`` and ``can_relay_response`` and a
+ ``turn_id`` came back, POST ``{turn_id, status, latency_ms, model, usage}``
+ (usage pulled from the JSON body, or from the SSE frames the way the Lua
+ ``body_filter`` does).
+
+Headers: the client headers handed to ``turn(..., headers=...)`` travel to
+headroom, and the ones headroom may need to merge (``anthropic-beta``) are
+echoed as ``gateway.request_headers``. The provider-bound headers are the
+constructor's ``provider_headers``, then the client's passthrough set
+(``authorization``, ``x-api-key``, ``anthropic-version``, ``anthropic-beta``,
+``openai-organization``, ``openai-project``), then whatever headroom returned
+in ``compress["headers"]`` - which wins on the same name, on both paths.
+
+Both clients need only ``.post(path, json=..., headers=...)`` returning an
+object with ``.status_code``, ``.headers``, ``.content`` and ``.json()`` -
+``fastapi.testclient.TestClient`` and ``httpx.Client`` both qualify.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from dataclasses import dataclass, field
+from typing import Any
+
+from tests.gateway.fake_provider import ANTHROPIC_MESSAGES_PATH, OPENAI_CHAT_PATH, extract_usage
+
+COMPRESS_PATH = "/v1/compress"
+RESPONSE_HALF_PATH = "/v1/compress/response"
+
+# Client headers echoed to headroom as ``gateway.request_headers`` (the Lua
+# plugin's ``GATEWAY_REQUEST_HEADERS``).
+GATEWAY_REQUEST_HEADERS = ("anthropic-beta",)
+# Client headers copied onto the provider call (the plugin's
+# ``provider_auth_header_passthrough`` set).
+PROVIDER_PASSTHROUGH_HEADERS = (
+ "authorization",
+ "x-api-key",
+ "anthropic-version",
+ "anthropic-beta",
+ "openai-organization",
+ "openai-project",
+)
+
+
+def _lower(headers: dict[str, str] | None) -> dict[str, str]:
+ return {str(k).lower(): v for k, v in (headers or {}).items()}
+
+
+def request_headers_block(client_headers: dict[str, str] | None) -> dict[str, str] | None:
+ """``gateway.request_headers`` for these client headers, or None when empty."""
+ lowered = _lower(client_headers)
+ picked = {name: lowered[name] for name in GATEWAY_REQUEST_HEADERS if lowered.get(name)}
+ return picked or None
+
+
+def required_provider_headers(compress: Any) -> dict[str, str]:
+ """The ``headers`` object of a /v1/compress answer, lower-cased; ``{}`` when
+ absent or malformed (older headroom)."""
+ if not isinstance(compress, dict):
+ return {}
+ raw = compress.get("headers")
+ if not isinstance(raw, dict):
+ return {}
+ return {str(k).lower(): str(v) for k, v in raw.items() if isinstance(v, (str, int, float))}
+
+
+@dataclass
+class ResponseHalfExchange:
+ """One ``POST /v1/compress/response`` round trip."""
+
+ request: dict[str, Any]
+ status: int
+ response: dict[str, Any] | None
+
+
+@dataclass
+class ProviderExchange:
+ """One provider-bound request and what came back."""
+
+ request: dict[str, Any]
+ status: int
+ headers: dict[str, str]
+ content: bytes
+ json: dict[str, Any] | None
+ latency_ms: float
+ request_headers: dict[str, str] = field(default_factory=dict) # what we sent, lower-cased
+
+ @property
+ def usage(self) -> dict[str, Any] | None:
+ return extract_usage(self.content, self.headers.get("content-type", ""))
+
+
+@dataclass
+class GatewayTurnResult:
+ """Everything a test needs to assert about one gateway turn."""
+
+ path: str # "loop" | "proxy" | "fail_open"
+ compress_status: int | None
+ compress_response: dict[str, Any] | None
+ provider_exchanges: list[ProviderExchange] = field(default_factory=list)
+ response_half_calls: list[ResponseHalfExchange] = field(default_factory=list)
+ final_status: int = 0
+ final_headers: dict[str, str] = field(default_factory=dict)
+ final_content: bytes = b""
+ final_response: dict[str, Any] | None = None
+ fail_open_reason: str | None = None
+
+ # --- conveniences ------------------------------------------------------
+
+ @property
+ def provider_calls(self) -> list[dict[str, Any]]:
+ """The provider-bound request bodies, in order."""
+ return [x.request for x in self.provider_exchanges]
+
+ @property
+ def provider_headers_sent(self) -> list[dict[str, str]]:
+ """The provider-bound request headers, in order (lower-cased)."""
+ return [x.request_headers for x in self.provider_exchanges]
+
+ @property
+ def required_headers(self) -> dict[str, str]:
+ """Headers headroom asked the gateway to set (``compress["headers"]``)."""
+ return required_provider_headers(self.compress_response)
+
+ @property
+ def turn_id(self) -> str | None:
+ if isinstance(self.compress_response, dict):
+ tid = self.compress_response.get("turn_id")
+ return tid if isinstance(tid, str) else None
+ return None
+
+ @property
+ def obligations(self) -> list[str]:
+ if isinstance(self.compress_response, dict):
+ obs = self.compress_response.get("obligations")
+ return list(obs) if isinstance(obs, list) else []
+ return []
+
+ @property
+ def rounds(self) -> int:
+ """Redrive rounds actually driven (provider calls beyond the first)."""
+ return max(0, len(self.provider_exchanges) - 1)
+
+ @property
+ def done(self) -> dict[str, Any] | None:
+ for x in reversed(self.response_half_calls):
+ if isinstance(x.response, dict) and x.response.get("action") == "done":
+ return x.response
+ return None
+
+
+def provider_path_for(body: dict[str, Any]) -> str:
+ model = str(body.get("model") or "").lower()
+ if "claude" in model or "anthropic" in model:
+ return ANTHROPIC_MESSAGES_PATH
+ return OPENAI_CHAT_PATH
+
+
+class FakeGateway:
+ def __init__(
+ self,
+ headroom_client: Any,
+ provider_client: Any,
+ *,
+ can_redrive: bool,
+ can_relay_response: bool,
+ session_affinity: bool = True,
+ relay: bool = True,
+ plugin_version: str = "fake-gateway/0.1.0",
+ headroom_headers: dict[str, str] | None = None,
+ provider_headers: dict[str, str] | None = None,
+ provider_path: str | None = None,
+ compress_mode: str | None = None,
+ max_redrives: int = 8,
+ ) -> None:
+ self.headroom = headroom_client
+ self.provider = provider_client
+ self.can_redrive = can_redrive
+ self.can_relay_response = can_relay_response
+ self.session_affinity = session_affinity
+ self.relay = relay
+ self.plugin_version = plugin_version
+ self.headroom_headers = dict(headroom_headers or {})
+ self.provider_headers = dict(provider_headers or {})
+ self.provider_path = provider_path
+ self.compress_mode = compress_mode
+ self.max_redrives = max_redrives
+ self.turns: list[GatewayTurnResult] = []
+
+ # --- helpers -------------------------------------------------------------
+
+ def gateway_block(
+ self, body: dict[str, Any], client_headers: dict[str, str] | None = None
+ ) -> dict[str, Any]:
+ block = {
+ "can_redrive": bool(self.can_redrive and not body.get("stream")),
+ "can_relay_response": bool(self.can_relay_response),
+ "session_affinity": bool(self.session_affinity),
+ "plugin_version": self.plugin_version,
+ }
+ request_headers = request_headers_block(client_headers)
+ if request_headers is not None:
+ block["request_headers"] = request_headers
+ return block
+
+ def compress_request(
+ self,
+ body: dict[str, Any],
+ session_id: str | None,
+ config: dict[str, Any] | None,
+ client_headers: dict[str, str] | None = None,
+ ) -> dict[str, Any]:
+ cfg: dict[str, Any] = dict(config or {})
+ if session_id is not None:
+ cfg["session_id"] = session_id
+ if self.compress_mode is not None:
+ cfg.setdefault("mode", self.compress_mode)
+ return {**body, "config": cfg, "gateway": self.gateway_block(body, client_headers)}
+
+ def provider_call_headers(
+ self,
+ client_headers: dict[str, str] | None = None,
+ required: dict[str, str] | None = None,
+ ) -> dict[str, str]:
+ """Provider-bound headers: constructor set, client passthrough, then
+ headroom's ``headers`` (which win on the same name)."""
+ out = _lower(self.provider_headers)
+ lowered = _lower(client_headers)
+ for name in PROVIDER_PASSTHROUGH_HEADERS:
+ if lowered.get(name):
+ out[name] = lowered[name]
+ out.update(_lower(required))
+ return out
+
+ def _call_provider(
+ self, body: dict[str, Any], headers: dict[str, str] | None = None
+ ) -> ProviderExchange:
+ path = self.provider_path or provider_path_for(body)
+ sent_headers = _lower(headers) if headers is not None else _lower(self.provider_headers)
+ started = time.perf_counter()
+ resp = self.provider.post(path, json=body, headers=sent_headers or None)
+ latency_ms = (time.perf_counter() - started) * 1000
+ headers = {k.lower(): v for k, v in resp.headers.items()}
+ parsed: dict[str, Any] | None = None
+ if not headers.get("content-type", "").startswith("text/event-stream"):
+ try:
+ candidate = resp.json()
+ except ValueError:
+ candidate = None
+ parsed = candidate if isinstance(candidate, dict) else None
+ return ProviderExchange(
+ request=body,
+ status=resp.status_code,
+ headers=headers,
+ content=resp.content,
+ json=parsed,
+ latency_ms=latency_ms,
+ request_headers=sent_headers,
+ )
+
+ def _post_response_half(
+ self, result: GatewayTurnResult, payload: dict[str, Any]
+ ) -> ResponseHalfExchange:
+ try:
+ resp = self.headroom.post(
+ RESPONSE_HALF_PATH, json=payload, headers=self.headroom_headers or None
+ )
+ try:
+ parsed = resp.json()
+ except ValueError:
+ parsed = None
+ exchange = ResponseHalfExchange(
+ request=payload,
+ status=resp.status_code,
+ response=parsed if isinstance(parsed, dict) else None,
+ )
+ except Exception as exc: # the plugin never lets a relay failure reach the client
+ exchange = ResponseHalfExchange(
+ request=payload, status=0, response={"error": {"message": str(exc)}}
+ )
+ result.response_half_calls.append(exchange)
+ return exchange
+
+ @staticmethod
+ def _finish(result: GatewayTurnResult, exchange: ProviderExchange, override: Any = None):
+ if isinstance(override, dict):
+ result.final_status = 200
+ result.final_headers = {"content-type": "application/json"}
+ result.final_content = json.dumps(override).encode()
+ result.final_response = override
+ else:
+ result.final_status = exchange.status
+ result.final_headers = dict(exchange.headers)
+ result.final_content = exchange.content
+ result.final_response = exchange.json
+ return result
+
+ # --- the turn ------------------------------------------------------------
+
+ def turn(
+ self,
+ body: dict[str, Any],
+ session_id: str | None,
+ *,
+ config: dict[str, Any] | None = None,
+ headers: dict[str, str] | None = None,
+ ) -> GatewayTurnResult:
+ """Run one client request through the gateway; see the module docstring."""
+ req_headers = {**self.headroom_headers, **(headers or {})}
+ compress_body = self.compress_request(body, session_id, config, headers)
+ # Fail-open and pre-contract answers send the client's own headers only.
+ client_provider_headers = self.provider_call_headers(headers)
+
+ # --- request half ------------------------------------------------------
+ try:
+ resp = self.headroom.post(
+ COMPRESS_PATH, json=compress_body, headers=req_headers or None
+ )
+ status = resp.status_code
+ try:
+ compress = resp.json()
+ except ValueError:
+ compress = None
+ except Exception as exc: # headroom unreachable -> fail open
+ status, compress = None, None
+ reason = f"transport: {exc!r}"
+ else:
+ reason = None if status == 200 and isinstance(compress, dict) else f"status {status}"
+
+ if reason is not None or not isinstance(compress, dict):
+ result = GatewayTurnResult(
+ path="fail_open",
+ compress_status=status,
+ compress_response=compress if isinstance(compress, dict) else None,
+ fail_open_reason=reason or "malformed compress response",
+ )
+ exchange = self._call_provider(body, client_provider_headers)
+ result.provider_exchanges.append(exchange)
+ self.turns.append(self._finish(result, exchange))
+ return result
+
+ provider_body = compress.get("body")
+ if not isinstance(provider_body, dict):
+ # Legacy (pre-contract) answer: only ``messages`` came back.
+ provider_body = {**body, "messages": compress.get("messages", body.get("messages"))}
+ turn_id = compress.get("turn_id")
+ obligations = (
+ compress.get("obligations") if isinstance(compress.get("obligations"), list) else []
+ )
+ # ``headers``: what headroom needs on the provider request (today the
+ # merged ``anthropic-beta``); applied on both paths, over the client's own.
+ provider_headers = self.provider_call_headers(headers, required_provider_headers(compress))
+
+ # --- loop path -----------------------------------------------------------
+ if "redrive" in obligations and isinstance(turn_id, str):
+ result = GatewayTurnResult(
+ path="loop", compress_status=status, compress_response=compress
+ )
+ exchange = self._call_provider(provider_body, provider_headers)
+ result.provider_exchanges.append(exchange)
+ final_override: Any = None
+ round_no = 0 # which provider call this answers; the plugin sends it too
+ for _ in range(self.max_redrives + 1):
+ if exchange.json is None:
+ break # non-JSON provider answer: nothing headroom can drive
+ step = self._post_response_half(
+ result,
+ {
+ "turn_id": turn_id,
+ "round": round_no,
+ "status": exchange.status,
+ "latency_ms": exchange.latency_ms,
+ "model": exchange.json.get("model"),
+ "usage": exchange.usage,
+ "response": exchange.json,
+ },
+ )
+ answer = step.response or {}
+ if step.status != 200:
+ break # headroom refused/expired: client gets the last provider answer
+ if answer.get("action") == "redrive" and isinstance(answer.get("request"), dict):
+ round_no = int(answer.get("round", round_no + 1))
+ exchange = self._call_provider(answer["request"], provider_headers)
+ result.provider_exchanges.append(exchange)
+ continue
+ if answer.get("action") == "done":
+ final_override = answer.get("response")
+ break
+ self.turns.append(self._finish(result, exchange, final_override))
+ return result
+
+ # --- proxy path ----------------------------------------------------------
+ result = GatewayTurnResult(path="proxy", compress_status=status, compress_response=compress)
+ exchange = self._call_provider(provider_body, provider_headers)
+ result.provider_exchanges.append(exchange)
+ self._finish(result, exchange)
+ if self.relay and self.can_relay_response and isinstance(turn_id, str):
+ model = exchange.json.get("model") if isinstance(exchange.json, dict) else None
+ self._post_response_half(
+ result,
+ {
+ "turn_id": turn_id,
+ "status": exchange.status,
+ "latency_ms": exchange.latency_ms,
+ "model": model,
+ "usage": exchange.usage,
+ },
+ )
+ self.turns.append(result)
+ return result
diff --git a/tests/gateway/fake_provider.py b/tests/gateway/fake_provider.py
new file mode 100644
index 000000000..59cea0950
--- /dev/null
+++ b/tests/gateway/fake_provider.py
@@ -0,0 +1,578 @@
+"""A scriptable fake LLM provider for the gateway contract tests.
+
+Public API (kept deliberately small - the docker/Kong driver imports it too)::
+
+ provider = FakeProvider()
+ provider.script([openai_text_response("hi"), openai_tool_call_response("f", {})])
+ provider.calls # list[ProviderCall]: every request, in order
+ provider.app # the FastAPI app (mount in a TestClient / ASGITransport)
+ provider.handle(path, body, headers) -> ProviderReply # pure-Python dispatch
+ base_url = provider.start(port) # uvicorn in a daemon thread; port 0 = ephemeral
+ provider.stop()
+ provider.reset() # clears the queue and the call log
+
+Endpoints:
+
+* ``POST /v1/chat/completions`` - OpenAI chat. JSON, or SSE when ``stream`` is
+ true. The final SSE chunk carries ``usage`` when
+ ``stream_options.include_usage`` is set (exactly what OpenAI does).
+* ``POST /v1/messages`` - Anthropic messages. JSON, or SSE with ``message_start``
+ (input usage) and ``message_delta`` (output usage).
+
+Scripting: each queued item is either a response *body* (dict, status 200) or a
+:class:`ScriptedResponse` (status/headers/body), or a callable taking the
+:class:`ProviderCall` and returning one of those. When the queue is empty the
+provider answers with ``default`` (a shape-appropriate one-line text response
+unless the constructor was given something else), so tests that only care about
+the request side need not script anything.
+
+Builders (all deterministic given their arguments):
+``openai_text_response``, ``openai_tool_call_response``,
+``anthropic_text_response``, ``anthropic_tool_use_response``,
+``openai_usage``, ``anthropic_usage``.
+"""
+
+from __future__ import annotations
+
+import json
+import socket
+import threading
+import time
+from collections import deque
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from typing import Any
+
+try: # fastapi is an optional extra; the pure-Python ``handle`` path needs none of it
+ from fastapi import FastAPI, Request
+ from fastapi.responses import Response
+except ImportError: # pragma: no cover - exercised only in lean environments
+ FastAPI = Request = Response = None # type: ignore[assignment,misc]
+
+OPENAI_CHAT_PATH = "/v1/chat/completions"
+ANTHROPIC_MESSAGES_PATH = "/v1/messages"
+
+
+# --------------------------------------------------------------------------- #
+# Records #
+# --------------------------------------------------------------------------- #
+
+
+@dataclass
+class ProviderCall:
+ """One request the fake provider received."""
+
+ path: str
+ body: dict[str, Any]
+ headers: dict[str, str] # lower-cased keys
+ received_at: float = field(default_factory=time.time)
+
+ @property
+ def stream(self) -> bool:
+ return bool(self.body.get("stream"))
+
+ @property
+ def messages(self) -> list[dict[str, Any]]:
+ return list(self.body.get("messages") or [])
+
+ @property
+ def tools(self) -> Any:
+ return self.body.get("tools")
+
+
+@dataclass
+class ScriptedResponse:
+ """A fully specified provider answer."""
+
+ body: dict[str, Any]
+ status: int = 200
+ headers: dict[str, str] = field(default_factory=dict)
+
+
+@dataclass
+class ProviderReply:
+ """What the provider sent back, in wire form plus the parsed JSON (when JSON)."""
+
+ status: int
+ headers: dict[str, str]
+ content: bytes
+ json: dict[str, Any] | None
+
+ @property
+ def is_sse(self) -> bool:
+ return self.headers.get("content-type", "").startswith("text/event-stream")
+
+
+Script = dict[str, Any] | ScriptedResponse | Callable[[ProviderCall], Any]
+
+
+# --------------------------------------------------------------------------- #
+# Builders #
+# --------------------------------------------------------------------------- #
+
+
+def openai_usage(
+ prompt: int, completion: int, cached: int | None = None, **extra: Any
+) -> dict[str, Any]:
+ usage: dict[str, Any] = {
+ "prompt_tokens": prompt,
+ "completion_tokens": completion,
+ "total_tokens": prompt + completion,
+ }
+ if cached is not None:
+ usage["prompt_tokens_details"] = {"cached_tokens": cached}
+ usage.update(extra)
+ return usage
+
+
+def anthropic_usage(
+ input_tokens: int,
+ output_tokens: int,
+ cache_read: int | None = None,
+ cache_write: int | None = None,
+) -> dict[str, Any]:
+ usage: dict[str, Any] = {"input_tokens": input_tokens, "output_tokens": output_tokens}
+ if cache_read is not None:
+ usage["cache_read_input_tokens"] = cache_read
+ if cache_write is not None:
+ usage["cache_creation_input_tokens"] = cache_write
+ return usage
+
+
+def openai_text_response(
+ text: str,
+ usage: dict[str, Any] | None = None,
+ *,
+ model: str = "gpt-4o",
+ response_id: str = "chatcmpl-fake",
+) -> dict[str, Any]:
+ return {
+ "id": response_id,
+ "object": "chat.completion",
+ "created": 1_700_000_000,
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": text},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": usage if usage is not None else openai_usage(10, 5),
+ }
+
+
+def openai_tool_call_response(
+ name: str,
+ arguments: dict[str, Any] | str,
+ usage: dict[str, Any] | None = None,
+ *,
+ call_id: str = "call_fake_1",
+ model: str = "gpt-4o",
+ response_id: str = "chatcmpl-fake-tool",
+) -> dict[str, Any]:
+ args = arguments if isinstance(arguments, str) else json.dumps(arguments)
+ return {
+ "id": response_id,
+ "object": "chat.completion",
+ "created": 1_700_000_000,
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "message": {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": call_id,
+ "type": "function",
+ "function": {"name": name, "arguments": args},
+ }
+ ],
+ },
+ "finish_reason": "tool_calls",
+ }
+ ],
+ "usage": usage if usage is not None else openai_usage(10, 5),
+ }
+
+
+def anthropic_text_response(
+ text: str,
+ usage: dict[str, Any] | None = None,
+ *,
+ model: str = "claude-sonnet-4-5",
+ response_id: str = "msg_fake",
+) -> dict[str, Any]:
+ return {
+ "id": response_id,
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [{"type": "text", "text": text}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": usage if usage is not None else anthropic_usage(10, 5),
+ }
+
+
+def anthropic_tool_use_response(
+ name: str,
+ tool_input: dict[str, Any],
+ usage: dict[str, Any] | None = None,
+ *,
+ tool_use_id: str = "toolu_fake_1",
+ model: str = "claude-sonnet-4-5",
+ response_id: str = "msg_fake_tool",
+) -> dict[str, Any]:
+ return {
+ "id": response_id,
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [{"type": "tool_use", "id": tool_use_id, "name": name, "input": tool_input}],
+ "stop_reason": "tool_use",
+ "stop_sequence": None,
+ "usage": usage if usage is not None else anthropic_usage(10, 5),
+ }
+
+
+# --------------------------------------------------------------------------- #
+# SSE rendering #
+# --------------------------------------------------------------------------- #
+
+
+def _sse(event: str | None, data: Any) -> bytes:
+ head = f"event: {event}\n" if event else ""
+ return (head + "data: " + json.dumps(data, separators=(",", ":")) + "\n\n").encode()
+
+
+def render_openai_sse(response: dict[str, Any], include_usage: bool) -> bytes:
+ """Chunk a chat-completion JSON body the way OpenAI streams it."""
+ base = {
+ "id": response.get("id", "chatcmpl-fake"),
+ "object": "chat.completion.chunk",
+ "created": response.get("created", 0),
+ "model": response.get("model", ""),
+ }
+ choice = (response.get("choices") or [{}])[0]
+ message = choice.get("message") or {}
+ out = bytearray()
+ out += _sse(
+ None,
+ {**base, "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}]},
+ )
+ if message.get("content"):
+ out += _sse(
+ None,
+ {
+ **base,
+ "choices": [
+ {"index": 0, "delta": {"content": message["content"]}, "finish_reason": None}
+ ],
+ },
+ )
+ for i, tc in enumerate(message.get("tool_calls") or []):
+ out += _sse(
+ None,
+ {
+ **base,
+ "choices": [
+ {
+ "index": 0,
+ "delta": {"tool_calls": [{"index": i, **tc}]},
+ "finish_reason": None,
+ }
+ ],
+ },
+ )
+ out += _sse(
+ None,
+ {
+ **base,
+ "choices": [{"index": 0, "delta": {}, "finish_reason": choice.get("finish_reason")}],
+ },
+ )
+ if include_usage and response.get("usage") is not None:
+ out += _sse(None, {**base, "choices": [], "usage": response["usage"]})
+ out += b"data: [DONE]\n\n"
+ return bytes(out)
+
+
+def render_anthropic_sse(response: dict[str, Any]) -> bytes:
+ """Stream a Messages JSON body the way Anthropic does."""
+ usage = dict(response.get("usage") or {})
+ start_usage = {k: v for k, v in usage.items() if k != "output_tokens"}
+ start_usage.setdefault("output_tokens", 1)
+ head = {k: v for k, v in response.items() if k not in ("content", "usage")}
+ out = bytearray()
+ out += _sse(
+ "message_start",
+ {"type": "message_start", "message": {**head, "content": [], "usage": start_usage}},
+ )
+ for i, block in enumerate(response.get("content") or []):
+ if block.get("type") == "text":
+ out += _sse(
+ "content_block_start",
+ {
+ "type": "content_block_start",
+ "index": i,
+ "content_block": {"type": "text", "text": ""},
+ },
+ )
+ out += _sse(
+ "content_block_delta",
+ {
+ "type": "content_block_delta",
+ "index": i,
+ "delta": {"type": "text_delta", "text": block.get("text", "")},
+ },
+ )
+ else:
+ start_block = {k: v for k, v in block.items() if k != "input"}
+ start_block["input"] = {}
+ out += _sse(
+ "content_block_start",
+ {"type": "content_block_start", "index": i, "content_block": start_block},
+ )
+ out += _sse(
+ "content_block_delta",
+ {
+ "type": "content_block_delta",
+ "index": i,
+ "delta": {
+ "type": "input_json_delta",
+ "partial_json": json.dumps(block.get("input") or {}),
+ },
+ },
+ )
+ out += _sse("content_block_stop", {"type": "content_block_stop", "index": i})
+ out += _sse(
+ "message_delta",
+ {
+ "type": "message_delta",
+ "delta": {"stop_reason": response.get("stop_reason"), "stop_sequence": None},
+ "usage": {"output_tokens": usage.get("output_tokens", 0)},
+ },
+ )
+ out += _sse("message_stop", {"type": "message_stop"})
+ return bytes(out)
+
+
+# --------------------------------------------------------------------------- #
+# The provider #
+# --------------------------------------------------------------------------- #
+
+
+def _default_body(call: ProviderCall) -> dict[str, Any]:
+ if call.path.endswith(ANTHROPIC_MESSAGES_PATH):
+ return anthropic_text_response("ok", model=str(call.body.get("model", "")))
+ return openai_text_response("ok", model=str(call.body.get("model", "")))
+
+
+class FakeProvider:
+ """See the module docstring for the API summary."""
+
+ def __init__(self, default: Script | None = None) -> None:
+ self.calls: list[ProviderCall] = []
+ self._queue: deque[Script] = deque()
+ self._default: Script = default if default is not None else _default_body
+ self._lock = threading.Lock()
+ self._server: Any = None
+ self._thread: threading.Thread | None = None
+ self._app: Any = None
+
+ # --- scripting ---------------------------------------------------------
+
+ def script(self, responses: list[Script]) -> FakeProvider:
+ """Replace the queue with ``responses`` (consumed in order)."""
+ with self._lock:
+ self._queue = deque(responses)
+ return self
+
+ def push(self, *responses: Script) -> FakeProvider:
+ with self._lock:
+ self._queue.extend(responses)
+ return self
+
+ def reset(self) -> None:
+ with self._lock:
+ self._queue.clear()
+ self.calls.clear()
+
+ @property
+ def pending(self) -> int:
+ return len(self._queue)
+
+ # --- dispatch ----------------------------------------------------------
+
+ def _next(self, call: ProviderCall) -> ScriptedResponse:
+ with self._lock:
+ item: Script = self._queue.popleft() if self._queue else self._default
+ if callable(item) and not isinstance(item, dict):
+ item = item(call)
+ if isinstance(item, ScriptedResponse):
+ return item
+ if isinstance(item, dict):
+ return ScriptedResponse(body=item)
+ raise TypeError(f"unsupported scripted item: {type(item).__name__}")
+
+ def handle(self, path: str, body: dict[str, Any], headers: dict[str, str]) -> ProviderReply:
+ """Pure-Python request dispatch: record the call, pick the next scripted
+ answer and render it (JSON or SSE). Used by the ASGI app, and directly by
+ tests that bridge the proxy's httpx upstream into this provider."""
+ call = ProviderCall(
+ path=path, body=body, headers={k.lower(): v for k, v in headers.items()}
+ )
+ self.calls.append(call)
+ scripted = self._next(call)
+ response_headers = {k.lower(): v for k, v in scripted.headers.items()}
+ if call.stream and scripted.status == 200:
+ if path.endswith(ANTHROPIC_MESSAGES_PATH):
+ content = render_anthropic_sse(scripted.body)
+ else:
+ opts = body.get("stream_options") or {}
+ content = render_openai_sse(scripted.body, bool(opts.get("include_usage")))
+ response_headers.setdefault("content-type", "text/event-stream")
+ return ProviderReply(scripted.status, response_headers, content, None)
+ response_headers.setdefault("content-type", "application/json")
+ return ProviderReply(
+ scripted.status,
+ response_headers,
+ json.dumps(scripted.body).encode(),
+ scripted.body,
+ )
+
+ # --- ASGI ----------------------------------------------------------------
+
+ @property
+ def app(self) -> Any:
+ if self._app is None:
+ self._app = self._build_app()
+ return self._app
+
+ def _build_app(self) -> Any:
+ if FastAPI is None:
+ raise RuntimeError("fastapi is required for FakeProvider.app")
+ app = FastAPI(title="fake-provider")
+ provider = self
+
+ async def _serve(request: Request) -> Response:
+ raw = await request.body()
+ try:
+ body = json.loads(raw) if raw else {}
+ except ValueError:
+ return Response(
+ content=json.dumps({"error": {"message": "invalid json"}}),
+ status_code=400,
+ media_type="application/json",
+ )
+ reply = provider.handle(request.url.path, body, dict(request.headers))
+ return Response(
+ content=reply.content,
+ status_code=reply.status,
+ headers={k: v for k, v in reply.headers.items() if k != "content-type"},
+ media_type=reply.headers.get("content-type", "application/json"),
+ )
+
+ # Registered under both the bare path and a ``/openai`` / ``/anthropic``
+ # prefix so a Kong route can point at either without rewriting.
+ for prefix in ("", "/openai", "/anthropic"):
+ app.add_api_route(f"{prefix}{OPENAI_CHAT_PATH}", _serve, methods=["POST"])
+ app.add_api_route(f"{prefix}{ANTHROPIC_MESSAGES_PATH}", _serve, methods=["POST"])
+
+ @app.get("/health")
+ async def _health() -> dict[str, Any]:
+ return {"ok": True, "calls": len(provider.calls), "pending": provider.pending}
+
+ @app.get("/calls")
+ async def _calls() -> list[dict[str, Any]]:
+ return [{"path": c.path, "body": c.body, "headers": c.headers} for c in provider.calls]
+
+ return app
+
+ # --- uvicorn thread ------------------------------------------------------
+
+ def start(self, port: int = 0, host: str = "127.0.0.1", timeout: float = 10.0) -> str:
+ """Serve ``app`` with uvicorn in a daemon thread; returns the base URL."""
+ import uvicorn
+
+ if self._server is not None:
+ raise RuntimeError("fake provider already started")
+ if port == 0:
+ with socket.socket() as s:
+ s.bind((host, 0))
+ port = s.getsockname()[1]
+ config = uvicorn.Config(self.app, host=host, port=port, log_level="warning", lifespan="off")
+ self._server = uvicorn.Server(config)
+ self._thread = threading.Thread(target=self._server.run, name="fake-provider", daemon=True)
+ self._thread.start()
+ deadline = time.time() + timeout
+ while not self._server.started:
+ if time.time() > deadline:
+ self.stop()
+ raise RuntimeError("fake provider did not start in time")
+ if not self._thread.is_alive():
+ raise RuntimeError("fake provider thread exited during startup")
+ time.sleep(0.02)
+ return f"http://{host}:{port}"
+
+ def stop(self, timeout: float = 5.0) -> None:
+ if self._server is None:
+ return
+ self._server.should_exit = True
+ if self._thread is not None:
+ self._thread.join(timeout)
+ self._server = None
+ self._thread = None
+
+
+# --------------------------------------------------------------------------- #
+# Usage extraction from a wire response (what the Kong body_filter does) #
+# --------------------------------------------------------------------------- #
+
+
+def extract_usage(content: bytes, content_type: str) -> dict[str, Any] | None:
+ """Pull the usage object out of a JSON or SSE provider response.
+
+ JSON: ``body["usage"]``. OpenAI SSE: the last ``data:`` frame carrying a
+ ``usage`` object. Anthropic SSE: ``message_start.message.usage`` merged with
+ ``message_delta.usage`` (input side from the start, output side from the
+ delta) - exactly the merge the Lua ``body_filter`` performs.
+ """
+ if not content_type.startswith("text/event-stream"):
+ try:
+ parsed = json.loads(content)
+ except ValueError:
+ return None
+ usage = parsed.get("usage") if isinstance(parsed, dict) else None
+ return usage if isinstance(usage, dict) else None
+ merged: dict[str, Any] = {}
+ last_openai: dict[str, Any] | None = None
+ for raw_line in content.decode("utf-8", errors="replace").splitlines():
+ if not raw_line.startswith("data:"):
+ continue
+ payload = raw_line[5:].strip()
+ if not payload or payload == "[DONE]":
+ continue
+ try:
+ frame = json.loads(payload)
+ except ValueError:
+ continue
+ if not isinstance(frame, dict):
+ continue
+ kind = frame.get("type")
+ if kind == "message_start":
+ msg_usage = (frame.get("message") or {}).get("usage")
+ if isinstance(msg_usage, dict):
+ merged.update(msg_usage)
+ elif kind == "message_delta":
+ delta_usage = frame.get("usage")
+ if isinstance(delta_usage, dict):
+ merged.update(delta_usage)
+ elif isinstance(frame.get("usage"), dict):
+ last_openai = frame["usage"]
+ if last_openai is not None:
+ return last_openai
+ return merged or None
diff --git a/tests/gateway/fold_only_hook.py b/tests/gateway/fold_only_hook.py
new file mode 100644
index 000000000..768d4b7d3
--- /dev/null
+++ b/tests/gateway/fold_only_hook.py
@@ -0,0 +1,110 @@
+"""A stream-safe, fold-only turn hook: truncates long tool results deterministically.
+
+``stream_safe = True`` because ``on_request`` needs no later re-drive, so the
+proxy runs it on streaming turns and the gateway request half runs it even when
+``can_redrive`` is false.
+
+Idempotent by construction: a result that already carries the fold marker is
+left alone, so in session mode (where the hook's output is what the next turn's
+prefix replays) turn N+1 reproduces turn N's bytes exactly. The hook rebinds
+``ctx.messages`` to a new list with fresh dicts for the messages it changed and
+never mutates the caller's objects.
+
+Handles the chat-completions ``role: "tool"`` string content and Anthropic
+``tool_result`` blocks (string content or a list of text blocks).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+from headroom.proxy.turn_hooks import register_turn_hook
+
+FOLD_MARKER = " ...[folded by test_fold_only]"
+
+
+def fold_text(text: str, max_chars: int) -> str:
+ if len(text) <= max_chars or text.endswith(FOLD_MARKER):
+ return text
+ return text[:max_chars] + FOLD_MARKER
+
+
+@dataclass
+class FoldOnlyHook:
+ name: str = "test_fold_only"
+ savings_source: str = "test_fold_only"
+ stream_safe: bool = True
+ max_chars: int = 200
+ request_calls: int = 0
+ folded: int = 0
+ seen_messages: list[list[dict[str, Any]]] = field(default_factory=list)
+
+ def _fold_block(self, block: Any) -> Any:
+ if not isinstance(block, dict) or block.get("type") != "tool_result":
+ return block
+ content = block.get("content")
+ if isinstance(content, str):
+ new = fold_text(content, self.max_chars)
+ if new is not content:
+ self.folded += 1
+ return {**block, "content": new}
+ return block
+ if isinstance(content, list):
+ changed = False
+ parts = []
+ for part in content:
+ if (
+ isinstance(part, dict)
+ and part.get("type") == "text"
+ and isinstance(part.get("text"), str)
+ ):
+ new = fold_text(part["text"], self.max_chars)
+ if new is not part["text"]:
+ changed = True
+ part = {**part, "text": new}
+ parts.append(part)
+ if changed:
+ self.folded += 1
+ return {**block, "content": parts}
+ return block
+
+ def on_request(self, ctx: Any) -> None:
+ self.request_calls += 1
+ messages = ctx.messages
+ if not isinstance(messages, list):
+ return
+ self.seen_messages.append(messages)
+ out: list[Any] = []
+ changed = False
+ for m in messages:
+ if not isinstance(m, dict):
+ out.append(m)
+ continue
+ if m.get("role") == "tool" and isinstance(m.get("content"), str):
+ new = fold_text(m["content"], self.max_chars)
+ if new is not m["content"]:
+ self.folded += 1
+ changed = True
+ out.append({**m, "content": new})
+ continue
+ if m.get("role") == "user" and isinstance(m.get("content"), list):
+ blocks = [self._fold_block(b) for b in m["content"]]
+ if any(a is not b for a, b in zip(blocks, m["content"])):
+ changed = True
+ out.append({**m, "content": blocks})
+ continue
+ out.append(m)
+ if changed:
+ ctx.messages = out
+
+
+def register(**kwargs: Any) -> FoldOnlyHook:
+ hook = FoldOnlyHook(**kwargs)
+ register_turn_hook(hook)
+ return hook
+
+
+def install(app: Any, config: Any) -> None:
+ """``headroom.proxy_extension`` entry-point shape."""
+ register()
diff --git a/tests/gateway/redrive_hook_ext.py b/tests/gateway/redrive_hook_ext.py
new file mode 100644
index 000000000..ea572d411
--- /dev/null
+++ b/tests/gateway/redrive_hook_ext.py
@@ -0,0 +1,266 @@
+"""A minimal re-driving turn hook with the SAME loop shape as headroom-tool-search.
+
+Shrink (``on_request``): every tool whose name starts with ``defer_prefix``
+(default ``"deferred_"``) is removed from ``ctx.tools`` and remembered in a
+catalog; a single ``search_tools`` function is appended whose description lists
+the deferred names. The output is a pure function of the input tools, so a
+gateway session re-sending the same tools gets byte-identical shrunk tools every
+turn.
+
+Reload (``on_response``): if the model called ``search_tools`` - OpenAI chat
+shape (``choices[0].message.tool_calls[]``) or Anthropic shape
+(``content[]`` ``tool_use`` block) - resolve the query against the catalog
+(substring match on name/description; no match -> every deferred tool), restore
+the resolved definitions into ``ctx.tools`` (appended after the search tool,
+sorted by name, exactly like the tool-search adapter's I2/I3 rules), append the
+assistant call plus a tool result naming the loaded tools to ``ctx.messages``,
+``await call_model(messages)`` and loop, up to ``max_rounds``. Returns the final
+provider response, or ``None`` when it never drove the model.
+
+``stream_safe = False``: the reload needs a re-drive, so the proxy (and the
+gateway request half) must skip this hook whenever nothing can re-drive.
+
+Entry points:
+
+* ``register(**kwargs) -> RedriveHook`` - build + ``register_turn_hook`` (tests).
+* ``install(app, config)`` - the ``headroom.proxy_extension`` entry-point shape.
+ The OSS loader discovers extensions through ``importlib.metadata`` entry points
+ only, so a subprocess driver (the Kong docker test) that wants this hook in a
+ uvicorn process must either register a temporary entry point or start the app
+ from Python after calling ``register()``. Env knobs honoured by ``install``:
+ ``HEADROOM_TEST_REDRIVE_PREFIX`` and ``HEADROOM_TEST_REDRIVE_MAX_ROUNDS``.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import dataclass, field
+from typing import Any
+
+from headroom.proxy.turn_hooks import register_turn_hook
+
+SEARCH_TOOL_NAME = "search_tools"
+SEARCH_TOOL_PARAMETERS: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "What capability you need, in a few words."}
+ },
+ "required": ["query"],
+}
+LOADED_PREFIX = "Loaded tools: "
+
+
+def _name(tool: Any) -> str:
+ if not isinstance(tool, dict):
+ return ""
+ fn = tool.get("function")
+ if isinstance(fn, dict) and fn.get("name"):
+ return str(fn["name"])
+ return str(tool.get("name") or "")
+
+
+def _description(tool: Any) -> str:
+ if not isinstance(tool, dict):
+ return ""
+ fn = tool.get("function")
+ if isinstance(fn, dict):
+ return str(fn.get("description") or "")
+ return str(tool.get("description") or "")
+
+
+def _is_openai_shape(tools: list[Any]) -> bool:
+ """Chat-completions tools nest the function; Anthropic tools are flat with
+ ``input_schema``. Decide from the tools, not the provider string, so an
+ Anthropic-shaped body sent with an OpenAI-looking model still round-trips."""
+ for t in tools:
+ if isinstance(t, dict):
+ if isinstance(t.get("function"), dict):
+ return True
+ if "input_schema" in t:
+ return False
+ return True
+
+
+def search_tool(openai_shape: bool, deferred_names: list[str]) -> dict[str, Any]:
+ description = (
+ "Search for additional tools by capability. Hidden tools: "
+ + ", ".join(sorted(deferred_names))
+ + ". Call this with a short description of what you need and the matching "
+ "tools will be loaded so you can call them next."
+ )
+ if openai_shape:
+ return {
+ "type": "function",
+ "function": {
+ "name": SEARCH_TOOL_NAME,
+ "description": description,
+ "parameters": SEARCH_TOOL_PARAMETERS,
+ },
+ }
+ return {
+ "name": SEARCH_TOOL_NAME,
+ "description": description,
+ "input_schema": SEARCH_TOOL_PARAMETERS,
+ }
+
+
+@dataclass
+class SearchCall:
+ query: str
+ call_id: str
+ raw: dict[str, Any]
+ shape: str # "openai" | "anthropic"
+
+
+def detect_search_call(response: Any) -> SearchCall | None:
+ """Find a ``search_tools`` call in an OpenAI chat or Anthropic response."""
+ if not isinstance(response, dict):
+ return None
+ choices = response.get("choices")
+ if isinstance(choices, list) and choices:
+ msg = (choices[0] or {}).get("message") or {}
+ for tc in msg.get("tool_calls") or []:
+ fn = tc.get("function") or {}
+ if fn.get("name") == SEARCH_TOOL_NAME:
+ args = fn.get("arguments")
+ if isinstance(args, str):
+ try:
+ args = json.loads(args or "{}")
+ except ValueError:
+ args = {"query": args}
+ query = str((args or {}).get("query") or "") if isinstance(args, dict) else ""
+ return SearchCall(
+ query=query, call_id=str(tc.get("id") or ""), raw=tc, shape="openai"
+ )
+ content = response.get("content")
+ if isinstance(content, list):
+ for block in content:
+ if (
+ isinstance(block, dict)
+ and block.get("type") == "tool_use"
+ and block.get("name") == SEARCH_TOOL_NAME
+ ):
+ inp = block.get("input") or {}
+ query = str(inp.get("query") or "") if isinstance(inp, dict) else ""
+ return SearchCall(
+ query=query, call_id=str(block.get("id") or ""), raw=block, shape="anthropic"
+ )
+ return None
+
+
+@dataclass
+class RedriveHook:
+ name: str = "test_redrive"
+ savings_source: str = "test_redrive"
+ stream_safe: bool = False
+ defer_prefix: str = "deferred_"
+ max_rounds: int = 4
+ # Observability for tests.
+ catalog: dict[str, dict[str, Any]] = field(default_factory=dict)
+ shrink_calls: int = 0
+ response_calls: int = 0
+ rounds_driven: int = 0
+ queries: list[str] = field(default_factory=list)
+
+ # --- request: shrink ---------------------------------------------------
+
+ def on_request(self, ctx: Any) -> None:
+ tools = ctx.tools
+ if not isinstance(tools, list) or not tools:
+ return
+ deferred = [t for t in tools if _name(t).startswith(self.defer_prefix)]
+ if not deferred:
+ return
+ self.shrink_calls += 1
+ for t in deferred:
+ self.catalog[_name(t)] = t
+ kept = [t for t in tools if not _name(t).startswith(self.defer_prefix)]
+ kept = [t for t in kept if _name(t) != SEARCH_TOOL_NAME]
+ # Rebind, never mutate in place: ctx.tools is the caller's list.
+ ctx.tools = [*kept, search_tool(_is_openai_shape(tools), [_name(t) for t in deferred])]
+
+ # --- response: reload loop ---------------------------------------------
+
+ def _resolve(self, query: str) -> list[dict[str, Any]]:
+ q = query.lower().strip()
+ hits = [
+ d
+ for n, d in self.catalog.items()
+ if q and (q in n.lower() or any(w in _description(d).lower() for w in q.split()))
+ ]
+ return hits or list(self.catalog.values())
+
+ def _restore(self, ctx: Any, resolved: list[dict[str, Any]]) -> None:
+ tools = ctx.tools if isinstance(ctx.tools, list) else []
+ head: list[Any] = []
+ tail: list[Any] = []
+ seen_search = False
+ for t in tools:
+ (tail if seen_search else head).append(t)
+ if _name(t) == SEARCH_TOOL_NAME:
+ seen_search = True
+ head_names = {_name(t) for t in head}
+ block = {_name(t): t for t in tail}
+ for d in resolved:
+ if _name(d) not in head_names:
+ block.setdefault(_name(d), d)
+ rebuilt = [*head, *(block[n] for n in sorted(block))]
+ if rebuilt != tools:
+ ctx.tools = rebuilt
+
+ @staticmethod
+ def _reload_items(
+ response: dict[str, Any], call: SearchCall, loaded: str
+ ) -> list[dict[str, Any]]:
+ text = f"{LOADED_PREFIX}{loaded}. They are now available - call the one you need."
+ if call.shape == "openai":
+ assistant = (response.get("choices") or [{}])[0].get("message") or {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [call.raw],
+ }
+ return [assistant, {"role": "tool", "tool_call_id": call.call_id, "content": text}]
+ return [
+ {"role": "assistant", "content": list(response.get("content") or [call.raw])},
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": call.call_id, "content": text}],
+ },
+ ]
+
+ async def on_response(self, ctx: Any, response: dict[str, Any], call_model: Any) -> Any:
+ self.response_calls += 1
+ current = response
+ drove = False
+ for _ in range(self.max_rounds):
+ call = detect_search_call(current)
+ if call is None:
+ return current if drove else None
+ self.queries.append(call.query)
+ resolved = self._resolve(call.query)
+ self._restore(ctx, resolved)
+ loaded = ", ".join(sorted(_name(d) for d in resolved)) or "(no match)"
+ messages = [*ctx.messages, *self._reload_items(current, call, loaded)]
+ ctx.messages = messages
+ current = await call_model(messages)
+ self.rounds_driven += 1
+ drove = True
+ return current # hit the round cap while the model was still searching
+
+
+def register(**kwargs: Any) -> RedriveHook:
+ """Build a hook, register it with the proxy's turn-hook registry, return it."""
+ hook = RedriveHook(**kwargs)
+ register_turn_hook(hook)
+ return hook
+
+
+def install(app: Any, config: Any) -> None:
+ """``headroom.proxy_extension`` entry-point shape."""
+ prefix = os.environ.get("HEADROOM_TEST_REDRIVE_PREFIX", "deferred_")
+ try:
+ rounds = int(os.environ.get("HEADROOM_TEST_REDRIVE_MAX_ROUNDS", "4"))
+ except ValueError:
+ rounds = 4
+ register(defer_prefix=prefix, max_rounds=max(1, rounds))
diff --git a/tests/gateway/samples.py b/tests/gateway/samples.py
new file mode 100644
index 000000000..af9990ad2
--- /dev/null
+++ b/tests/gateway/samples.py
@@ -0,0 +1,170 @@
+"""Deterministic sample payloads shared by the gateway contract tests.
+
+Everything here is a pure function of its arguments so two calls produce
+byte-identical JSON - the byte-stability invariants depend on that.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+# --------------------------------------------------------------------------- #
+# Conversations #
+# --------------------------------------------------------------------------- #
+
+
+def big_tool_history(n_items: int = 200, call_id: str = "c1") -> list[dict[str, Any]]:
+ """A chat-completions conversation whose tool result is large enough to be
+ compressed (mirrors ``tests/test_compress_session_mode.py::_big_tool_history``)."""
+ items = [
+ {
+ "id": i,
+ "score": 0.99 if i % 30 == 0 else 0.6,
+ "msg": f"Result {i:03d}{' error' if i % 30 == 0 else ' ok'}",
+ "blob": f"payload-{i:04d}-" + "".join(chr(97 + (i * 7 + j) % 26) for j in range(240)),
+ }
+ for i in range(n_items)
+ ]
+ return [
+ {"role": "user", "content": "Get items"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": call_id,
+ "type": "function",
+ "function": {"name": "get_items", "arguments": "{}"},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": call_id, "content": json.dumps(items)},
+ ]
+
+
+def anthropic_tool_history(n_items: int = 200) -> list[dict[str, Any]]:
+ """The same conversation in Anthropic Messages shape."""
+ items = [
+ {"id": i, "msg": f"Result {i:03d}", "blob": f"payload-{i:04d}-" + "x" * 200}
+ for i in range(n_items)
+ ]
+ return [
+ {"role": "user", "content": "Get items"},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "tool_use", "id": "toolu_1", "name": "get_items", "input": {}},
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {"type": "tool_result", "tool_use_id": "toolu_1", "content": json.dumps(items)}
+ ],
+ },
+ ]
+
+
+# --------------------------------------------------------------------------- #
+# Tools #
+# --------------------------------------------------------------------------- #
+
+
+def _verbose_params(prefix: str) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": (
+ f"The {prefix} query string. This description is deliberately long so "
+ "that the tool schema compaction pass has something to remove. " * 3
+ ),
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Maximum number of results to return. " * 4,
+ "default": 10,
+ },
+ },
+ "required": ["query"],
+ "additionalProperties": False,
+ }
+
+
+def openai_tools(deferred_prefix: str = "deferred_") -> list[dict[str, Any]]:
+ """Chat-completions tools: one core tool plus two deferrable ones.
+
+ ``deferred_prefix`` matches ``redrive_hook_ext.RedriveHook``'s default so a
+ test can register the hook with no arguments.
+ """
+ return [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_items",
+ "description": "Fetch the item list from the catalogue service.",
+ "parameters": _verbose_params("catalogue"),
+ },
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": f"{deferred_prefix}create_issue",
+ "description": "Create a GitHub issue in the given repository.",
+ "parameters": _verbose_params("issue"),
+ },
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": f"{deferred_prefix}query_db",
+ "description": "Run a read-only SQL query against Postgres.",
+ "parameters": _verbose_params("sql"),
+ },
+ },
+ ]
+
+
+def anthropic_tools(deferred_prefix: str = "deferred_") -> list[dict[str, Any]]:
+ """The same three tools in Anthropic Messages shape."""
+ return [
+ {
+ "name": "get_items",
+ "description": "Fetch the item list from the catalogue service.",
+ "input_schema": _verbose_params("catalogue"),
+ },
+ {
+ "name": f"{deferred_prefix}create_issue",
+ "description": "Create a GitHub issue in the given repository.",
+ "input_schema": _verbose_params("issue"),
+ },
+ {
+ "name": f"{deferred_prefix}query_db",
+ "description": "Run a read-only SQL query against Postgres.",
+ "input_schema": _verbose_params("sql"),
+ },
+ ]
+
+
+def tool_names(tools: Any) -> list[str]:
+ """Names of every tool in either provider shape (order preserved)."""
+ out: list[str] = []
+ for t in tools or []:
+ if not isinstance(t, dict):
+ continue
+ fn = t.get("function")
+ if isinstance(fn, dict) and fn.get("name"):
+ out.append(str(fn["name"]))
+ elif t.get("name"):
+ out.append(str(t["name"]))
+ return out
+
+
+def canonical(value: Any) -> str:
+ """The byte-stability yardstick: sorted-key JSON."""
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
+
+
+SYSTEM_PROMPT = "You are a terse assistant. Answer in one sentence."
diff --git a/tests/gateway/test_compress_turn_seam.py b/tests/gateway/test_compress_turn_seam.py
new file mode 100644
index 000000000..95f98fc9b
--- /dev/null
+++ b/tests/gateway/test_compress_turn_seam.py
@@ -0,0 +1,219 @@
+"""The compress-turn seam: a contract on ``/v1/compress`` that is not the
+built-in gateway contract, installed exactly as a third party would.
+
+* I-CLAIM - ``begin`` sees every body; a claimed body gets ``prepare`` ->
+ ``transform`` (executor side, once) -> ``finish`` -> ``commit``.
+* I-FIELDS - ``finish``'s fields and transform labels reach the answer and
+ the outcome; a replaced message list is what the answer carries.
+* I-OWN - a turn that returns ``True`` from ``commit`` owns the outcome:
+ the proxy does not record it.
+* I-400 - ``CompressTurnError`` from ``begin`` is a 400 ``invalid_request``.
+* I-FAILOPEN- bypass header, empty messages and a compression timeout carry
+ the turn's ``fail_open_fields``.
+* I-FIRST - the first registered claimant wins; the built-in gateway
+ contract still claims ``gateway`` bodies on the same app.
+* I-OFF - ``HEADROOM_GATEWAY_CONTRACT=0`` builds an app with no gateway
+ contract: a ``gateway`` block is ignored, the response route is
+ absent, and the seam is empty.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+import pytest
+
+from headroom.proxy.compress_turn import (
+ CompressTurnError,
+ FinishedTurn,
+ register_compress_turn_extension,
+ registered_compress_turn_extensions,
+ unregister_compress_turn_extension,
+)
+from tests.gateway.conftest import compress
+from tests.gateway.samples import anthropic_tool_history
+
+
+@dataclass
+class EchoTurn:
+ model_name: str = ""
+ transform_calls: int = 0
+ prepared: bool = False
+ committed: list[Any] = field(default_factory=list)
+ replace_messages: bool = False
+
+ def fail_open_fields(self, messages: list[dict[str, Any]]) -> dict[str, Any]:
+ return {"echo": {"fail_open": True, "n": len(messages)}}
+
+ def prepare(self, *, model_name: str, tags: dict[str, Any], config: Any) -> None:
+ self.prepared = True
+ self.model_name = model_name
+ tags["echo_prepared"] = True
+
+ def transform(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ self.transform_calls += 1
+ return messages # pure
+
+ @property
+ def folded_messages(self) -> bool:
+ return False
+
+ def count_messages(self, messages: list[dict[str, Any]], fallback: int) -> int:
+ return fallback
+
+ def finish(
+ self,
+ *,
+ messages: list[dict[str, Any]],
+ tokens_before: int,
+ transforms_applied: list[str],
+ mode: str | None,
+ ccr_hashes: list[str],
+ ) -> FinishedTurn:
+ out = None
+ if self.replace_messages:
+ out = [{"role": "user", "content": "replaced by echo"}]
+ return FinishedTurn(
+ fields={"echo": {"model": self.model_name, "tokens_before": tokens_before}},
+ transforms=list(transforms_applied) + ["echo:seen"],
+ messages=out,
+ )
+
+ def commit(self, outcome: Any, *, session_key: str | None, session_id: str | None) -> bool:
+ self.committed.append(outcome)
+ return True # we own it
+
+
+@dataclass
+class EchoContract:
+ name: str = "echo_contract"
+ turns: list[EchoTurn] = field(default_factory=list)
+ replace_messages: bool = False
+
+ def begin(self, *, proxy: Any, request: Any, body: dict[str, Any], client: str | None):
+ if body.get("contract") != "echo":
+ return None
+ if not isinstance(body.get("contract_opts", {}), dict):
+ raise CompressTurnError("contract_opts must be an object.")
+ turn = EchoTurn(replace_messages=self.replace_messages)
+ self.turns.append(turn)
+ return turn
+
+
+def echo(headroom_client):
+ proxy = headroom_client.app.state.proxy
+ ext = EchoContract()
+ register_compress_turn_extension(proxy, ext)
+ yield ext
+ unregister_compress_turn_extension(proxy, ext)
+
+
+def _body(**extra: Any) -> dict[str, Any]:
+ out = {"model": "claude-sonnet-4-5", "messages": anthropic_tool_history(), "max_tokens": 32}
+ out.update(extra)
+ return out
+
+
+def test_built_in_gateway_contract_is_registered_through_the_seam(headroom_client) -> None:
+ proxy = headroom_client.app.state.proxy
+ names = [getattr(e, "name", None) for e in registered_compress_turn_extensions(proxy)]
+ assert names == ["gateway_turn_contract"]
+ assert proxy.gateway_turns is not None
+
+
+def test_claimed_body_runs_every_moment_and_owns_the_outcome(
+ headroom_client, outcome_spy, echo
+) -> None:
+ outcomes = outcome_spy(headroom_client)
+ resp = compress(headroom_client, _body(contract="echo"))
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["echo"]["model"] == "claude-sonnet-4-5"
+ assert data["echo"]["tokens_before"] == data["tokens_before"]
+ assert data["transforms_applied"][-1] == "echo:seen"
+ assert len(echo.turns) == 1
+ turn = echo.turns[0]
+ assert turn.prepared and turn.transform_calls == 1
+ # I-OWN: the turn took the outcome; the proxy recorded nothing.
+ assert outcomes == []
+ assert len(turn.committed) == 1
+ assert "echo:seen" in turn.committed[0].transforms_applied
+ assert turn.committed[0].tags.get("echo_prepared") is True
+
+
+def test_claimed_session_body_transforms_once_after_replay(headroom_client, echo) -> None:
+ body = _body(contract="echo", config={"session_id": "echo-session"})
+ first = compress(headroom_client, body).json()
+ grown = dict(body)
+ grown["messages"] = list(body["messages"]) + [
+ {"role": "assistant", "content": "answer 0"},
+ {"role": "user", "content": "follow-up 0"},
+ ]
+ second = compress(headroom_client, grown).json()
+ assert first["session"]["id"] == second["session"]["id"] == "echo-session"
+ assert [t.transform_calls for t in echo.turns] == [1, 1]
+ assert second["echo"]["model"] == "claude-sonnet-4-5"
+
+
+def test_finish_can_replace_the_returned_messages(headroom_client, echo) -> None:
+ echo.replace_messages = True
+ data = compress(headroom_client, _body(contract="echo")).json()
+ assert data["messages"] == [{"role": "user", "content": "replaced by echo"}]
+
+
+def test_unclaimed_body_is_legacy(headroom_client, outcome_spy, echo) -> None:
+ outcomes = outcome_spy(headroom_client)
+ data = compress(headroom_client, _body()).json()
+ assert "echo" not in data and "body" not in data
+ assert echo.turns == []
+ assert len(outcomes) == 1
+
+
+def test_begin_error_is_400(headroom_client, echo) -> None:
+ resp = compress(headroom_client, _body(contract="echo", contract_opts="nope"))
+ assert resp.status_code == 400
+ assert resp.json()["error"] == {
+ "type": "invalid_request",
+ "message": "contract_opts must be an object.",
+ }
+
+
+def test_fail_open_answers_carry_the_turns_fields(headroom_client, echo, monkeypatch) -> None:
+ bypass = compress(
+ headroom_client, _body(contract="echo"), headers={"x-headroom-bypass": "true"}
+ ).json()
+ assert bypass["echo"] == {"fail_open": True, "n": len(anthropic_tool_history())}
+
+ empty = compress(headroom_client, _body(contract="echo", messages=[])).json()
+ assert empty["echo"] == {"fail_open": True, "n": 0}
+
+ from unittest.mock import AsyncMock
+
+ proxy = headroom_client.app.state.proxy
+ monkeypatch.setattr(proxy, "_run_compression_in_executor", AsyncMock(side_effect=TimeoutError))
+ timed_out = compress(headroom_client, _body(contract="echo")).json()
+ assert timed_out["compression_skipped"] is True
+ assert timed_out["echo"]["fail_open"] is True
+
+
+def test_first_claimant_wins_and_gateway_still_claims_its_bodies(headroom_client, echo) -> None:
+ # The built-in contract was registered first (at create_app), so a body
+ # carrying BOTH markers goes to it and the echo contract never sees it.
+ data = compress(headroom_client, _body(contract="echo", gateway={})).json()
+ assert "body" in data and "turn_id" in data
+ assert "echo" not in data
+ assert echo.turns == []
+
+
+def test_contract_disabled_by_env(make_headroom_client, monkeypatch) -> None:
+ monkeypatch.setenv("HEADROOM_GATEWAY_CONTRACT", "0")
+ client = make_headroom_client()
+ proxy = client.app.state.proxy
+ assert registered_compress_turn_extensions(proxy) == []
+ assert proxy.gateway_turns is None
+ data = compress(client, _body(gateway={"can_relay_response": True})).json()
+ assert "body" not in data and "turn_id" not in data and "obligations" not in data
+ resp = client.post("/v1/compress/response", json={"turn_id": "x", "status": 200})
+ assert resp.status_code in (404, 405)
diff --git a/tests/gateway/test_contract_request_half.py b/tests/gateway/test_contract_request_half.py
new file mode 100644
index 000000000..4e155ee0f
--- /dev/null
+++ b/tests/gateway/test_contract_request_half.py
@@ -0,0 +1,469 @@
+"""Request half of the gateway turn contract: ``POST /v1/compress`` (spec section 1).
+
+Invariants protected here:
+
+* I-LEGACY - a body WITHOUT a top-level ``gateway`` object behaves exactly as
+ today: same response keys, no hooks run, no pending turn.
+* I-KEYS - gateway mode adds ``body``/``turn_id``/``route``/``obligations``/
+ ``gateway`` on EVERY answer, including fail-open ones.
+* I-BODY - ``body`` is the complete provider request: pass-through fields
+ echoed untouched, ``config``/``gateway``/``token_budget`` stripped,
+ ``body.messages`` is the top-level ``messages``.
+* I-VALID - malformed ``gateway`` blocks are 400 ``invalid_request``.
+* I-OBLIG - obligations follow the capability matrix: ``redrive`` only when a
+ re-driving hook ran under ``can_redrive`` + ``session_affinity``;
+ ``relay_usage`` iff ``can_relay_response``.
+* I-NOSHRINK - a re-driving hook never shrinks when nothing can re-drive.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+import pytest
+
+from headroom.proxy.turn_hooks import register_turn_hook
+from tests.gateway import fold_only_hook, redrive_hook_ext
+from tests.gateway.conftest import compress, registry_of
+from tests.gateway.samples import (
+ SYSTEM_PROMPT,
+ anthropic_tool_history,
+ anthropic_tools,
+ big_tool_history,
+ canonical,
+ openai_tools,
+ tool_names,
+)
+
+LEGACY_STATELESS_KEYS = {
+ "messages",
+ "tokens_before",
+ "tokens_after",
+ "tokens_saved",
+ "compression_ratio",
+ "transforms_applied",
+ "transforms_summary",
+ "ccr_hashes",
+}
+GATEWAY_EXTRA_KEYS = {"body", "turn_id", "route", "obligations", "gateway"}
+ROUTE_KEYS = {"model", "provider", "service_tier", "reason"}
+GATEWAY_ECHO_KEYS = {"can_redrive", "can_relay_response", "session_affinity"}
+HEX32 = re.compile(r"^[0-9a-f]{32}$")
+
+
+class _RecordingHook:
+ """A hook that records whether it ran; never changes anything."""
+
+ name = "recording"
+ stream_safe = True
+
+ def __init__(self) -> None:
+ self.requests = 0
+
+ def on_request(self, ctx: Any) -> None:
+ self.requests += 1
+
+
+def _body(messages: list[dict[str, Any]] | None = None, **extra: Any) -> dict[str, Any]:
+ out: dict[str, Any] = {"model": "gpt-4o", "messages": messages or big_tool_history()}
+ out.update(extra)
+ return out
+
+
+# --------------------------------------------------------------------------- #
+# I-LEGACY (these pass on the current tree and must keep passing) #
+# --------------------------------------------------------------------------- #
+
+
+def test_legacy_mode_keys_unchanged_stateless(headroom_client) -> None:
+ """I-LEGACY: no ``gateway`` key -> exactly today's stateless key set."""
+ resp = compress(headroom_client, _body())
+ assert resp.status_code == 200, resp.text
+ assert set(resp.json()) == LEGACY_STATELESS_KEYS
+
+
+def test_legacy_mode_keys_unchanged_session(headroom_client) -> None:
+ """I-LEGACY: session mode adds only ``session``."""
+ resp = compress(headroom_client, _body(config={"session_id": "legacy-s"}))
+ assert resp.status_code == 200, resp.text
+ assert set(resp.json()) == LEGACY_STATELESS_KEYS | {"session"}
+
+
+def test_legacy_mode_ignores_pass_through_fields(headroom_client) -> None:
+ """I-LEGACY: extra provider fields are neither echoed nor rejected."""
+ resp = compress(
+ headroom_client, _body(tools=openai_tools(), system=SYSTEM_PROMPT, temperature=0.2)
+ )
+ assert resp.status_code == 200, resp.text
+ assert set(resp.json()) == LEGACY_STATELESS_KEYS
+
+
+def test_legacy_mode_runs_no_hooks(headroom_client) -> None:
+ """I-LEGACY: turn hooks are a gateway-mode feature; legacy callers never see them."""
+ hook = _RecordingHook()
+ register_turn_hook(hook)
+ fold = fold_only_hook.register(max_chars=100)
+ resp = compress(headroom_client, _body())
+ assert resp.status_code == 200
+ assert hook.requests == 0
+ assert fold.request_calls == 0
+ # And the payload is untouched by the fold hook.
+ assert len(resp.json()["messages"][2]["content"]) > 100
+
+
+def test_legacy_mode_registers_no_pending_turn(headroom_client) -> None:
+ """I-LEGACY: nothing to wait for, nothing registered."""
+ compress(headroom_client, _body(config={"session_id": "legacy-p"}))
+ registry = registry_of(headroom_client)
+ assert registry is None or len(registry) == 0
+
+
+# --------------------------------------------------------------------------- #
+# I-KEYS / I-BODY #
+# --------------------------------------------------------------------------- #
+
+
+def _assert_contract_shape(data: dict[str, Any], sent: dict[str, Any]) -> None:
+ assert GATEWAY_EXTRA_KEYS <= set(data), sorted(data)
+ assert HEX32.match(data["turn_id"]), data["turn_id"]
+ assert set(data["route"]) == ROUTE_KEYS
+ assert isinstance(data["obligations"], list)
+ assert set(data["gateway"]) == GATEWAY_ECHO_KEYS
+ body = data["body"]
+ assert isinstance(body, dict)
+ for forbidden in ("config", "gateway", "token_budget"):
+ assert forbidden not in body, forbidden
+ assert body["model"] == sent["model"]
+ assert body["messages"] == data["messages"]
+
+
+def test_gateway_mode_adds_contract_keys(headroom_client) -> None:
+ """I-KEYS: ``gateway: {}`` is gateway mode; the legacy keys are all still there."""
+ sent = _body(gateway={})
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert LEGACY_STATELESS_KEYS <= set(data)
+ _assert_contract_shape(data, sent)
+ assert data["obligations"] == []
+ assert data["gateway"] == {
+ "can_redrive": False,
+ "can_relay_response": False,
+ "session_affinity": True,
+ }
+ assert data["route"]["model"] == "gpt-4o"
+ assert data["route"]["provider"] == "openai"
+ assert data["route"]["service_tier"] is None
+ assert data["route"]["reason"] == ""
+ # Compression still happened in gateway mode.
+ assert data["tokens_saved"] > 0
+ assert data["body"]["messages"][2]["content"] != sent["messages"][2]["content"]
+
+
+def test_gateway_mode_with_session(headroom_client) -> None:
+ """I-KEYS: session mode + gateway mode -> both key sets."""
+ sent = _body(config={"session_id": "gw-s1"}, gateway={"can_relay_response": True})
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ _assert_contract_shape(data, sent)
+ assert data["session"]["id"] == "gw-s1"
+ assert data["gateway"]["can_relay_response"] is True
+
+
+def test_pass_through_fields_echoed_untouched(headroom_client) -> None:
+ """I-BODY: unknown provider fields come back byte-identical inside ``body``."""
+ metadata = {"user_id": "u-1", "nested": {"k": [1, 2, {"z": None}]}}
+ sent = _body(
+ gateway={},
+ temperature=0.25,
+ top_p=0.9,
+ service_tier="flex",
+ metadata=metadata,
+ stream=False,
+ response_format={"type": "json_object"},
+ token_budget=50_000,
+ )
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ body = resp.json()["body"]
+ for key in ("temperature", "top_p", "service_tier", "metadata", "stream", "response_format"):
+ assert canonical(body[key]) == canonical(sent[key]), key
+ assert "token_budget" not in body
+ assert resp.json()["route"]["service_tier"] == "flex"
+
+
+def test_tools_and_system_echoed(headroom_client) -> None:
+ """I-BODY: ``system`` passes through as sent; ``tools`` come back (possibly
+ compacted) with every tool name preserved and in order."""
+ sent = _body(gateway={}, tools=openai_tools(), system=SYSTEM_PROMPT)
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ body = resp.json()["body"]
+ assert body["system"] == SYSTEM_PROMPT
+ assert tool_names(body["tools"]) == tool_names(sent["tools"])
+
+
+def test_no_tools_means_no_tools_key(headroom_client) -> None:
+ """I-BODY: a request without ``tools`` never grows one (an empty ``tools``
+ list is a provider 400 on Anthropic)."""
+ resp = compress(headroom_client, _body(gateway={}))
+ assert resp.status_code == 200
+ assert "tools" not in resp.json()["body"]
+
+
+def test_tool_schema_compaction_is_deterministic(headroom_client) -> None:
+ """I-BODY / prefix stability: identical tools in -> identical tool bytes out,
+ on every call, and the transform is named when it changed anything."""
+ sent = _body(gateway={}, tools=openai_tools())
+ first = compress(headroom_client, sent).json()
+ second = compress(headroom_client, sent).json()
+ assert canonical(first["body"]["tools"]) == canonical(second["body"]["tools"])
+ changed = canonical(first["body"]["tools"]) != canonical(sent["tools"])
+ assert ("tool_schema_compaction" in first["transforms_applied"]) == changed
+
+
+def test_route_provider_inferred_from_model(headroom_client) -> None:
+ """I-BODY: ``route.provider`` follows the tracker-provider rule (claude/anthropic
+ in the model name -> anthropic, else openai) and ``route.model`` is the body model."""
+ sent = {
+ "model": "claude-sonnet-4-5",
+ "messages": anthropic_tool_history(),
+ "system": SYSTEM_PROMPT,
+ "tools": anthropic_tools(),
+ "max_tokens": 64,
+ "gateway": {},
+ }
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["route"]["provider"] == "anthropic"
+ assert data["route"]["model"] == "claude-sonnet-4-5"
+ assert data["body"]["max_tokens"] == 64
+ assert data["body"]["system"] == SYSTEM_PROMPT
+
+
+# --------------------------------------------------------------------------- #
+# I-VALID #
+# --------------------------------------------------------------------------- #
+
+
+ "gateway",
+ [
+ [],
+ "yes",
+ 1,
+ True,
+ {"can_redrive": "true"},
+ {"can_relay_response": 1},
+ {"session_affinity": "no"},
+ {"can_redrive": None},
+ ],
+ ids=[
+ "list",
+ "string",
+ "int",
+ "bool",
+ "redrive-str",
+ "relay-int",
+ "affinity-str",
+ "redrive-null",
+ ],
+)
+def test_invalid_gateway_block_is_400(headroom_client, gateway: Any) -> None:
+ """I-VALID: ``gateway`` must be an object whose flags are real booleans."""
+ resp = compress(headroom_client, _body(gateway=gateway))
+ assert resp.status_code == 400, resp.text
+ assert resp.json()["error"]["type"] == "invalid_request"
+
+
+def test_unknown_gateway_keys_are_ignored(headroom_client) -> None:
+ """I-VALID: forward-compatible - unknown keys inside ``gateway`` are dropped."""
+ resp = compress(
+ headroom_client,
+ _body(gateway={"plugin_version": "kong-headroom/0.1.0", "future_flag": {"x": 1}}),
+ )
+ assert resp.status_code == 200, resp.text
+ assert set(resp.json()["gateway"]) == GATEWAY_ECHO_KEYS
+
+
+def test_legacy_validation_still_applies_in_gateway_mode(headroom_client) -> None:
+ """I-VALID: the pre-existing 400s (missing model/messages) are unchanged."""
+ resp = compress(
+ headroom_client, {"messages": [{"role": "user", "content": "x"}], "gateway": {}}
+ )
+ assert resp.status_code == 400
+ assert "model" in resp.json()["error"]["message"]
+
+
+# --------------------------------------------------------------------------- #
+# I-KEYS on fail-open answers #
+# --------------------------------------------------------------------------- #
+
+
+def test_bypass_header_in_gateway_mode_still_returns_contract_keys(headroom_client) -> None:
+ """I-KEYS: the bypass short-circuit must still hand the gateway a ``body`` it can
+ forward, a ``turn_id`` and an empty obligation list."""
+ sent = _body(gateway={"can_relay_response": True}, tools=openai_tools(), temperature=0.1)
+ resp = compress(headroom_client, sent, headers={"x-headroom-bypass": "true"})
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["messages"] == sent["messages"]
+ assert data["tokens_before"] == 0 and data["tokens_saved"] == 0
+ assert GATEWAY_EXTRA_KEYS <= set(data)
+ assert data["obligations"] == []
+ assert HEX32.match(data["turn_id"])
+ body = data["body"]
+ assert body["messages"] == sent["messages"]
+ assert canonical(body["tools"]) == canonical(sent["tools"])
+ assert body["temperature"] == 0.1
+ assert "gateway" not in body and "config" not in body
+
+
+def test_empty_messages_in_gateway_mode_returns_contract_keys(headroom_client) -> None:
+ """I-KEYS: the empty-messages short-circuit is also a gateway answer."""
+ sent = _body(messages=[], gateway={})
+ sent["messages"] = []
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["messages"] == []
+ assert GATEWAY_EXTRA_KEYS <= set(data)
+ assert data["obligations"] == []
+ assert data["body"]["messages"] == []
+ assert data["route"]["model"] == "gpt-4o"
+
+
+def test_compression_timeout_fails_open_with_contract_keys(headroom_client, monkeypatch) -> None:
+ """I-KEYS: stateless timeout -> 200 + originals + ``compression_skipped`` AND the
+ contract keys, so the gateway can forward without a special case."""
+ from unittest.mock import AsyncMock
+
+ proxy = headroom_client.app.state.proxy
+ monkeypatch.setattr(proxy, "_run_compression_in_executor", AsyncMock(side_effect=TimeoutError))
+ sent = _body(gateway={}, tools=openai_tools(), temperature=0.3)
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["compression_skipped"] is True
+ assert data["skip_reason"] == "compression_timeout"
+ assert data["messages"] == sent["messages"]
+ assert GATEWAY_EXTRA_KEYS <= set(data)
+ assert data["obligations"] == []
+ assert data["body"]["messages"] == sent["messages"]
+ assert data["body"]["temperature"] == 0.3
+
+
+# --------------------------------------------------------------------------- #
+# I-OBLIG / I-NOSHRINK: the capability matrix #
+# --------------------------------------------------------------------------- #
+
+
+def _expected_obligations(
+ hook: str, can_redrive: bool, can_relay: bool, affinity: bool
+) -> list[str]:
+ out: list[str] = []
+ if hook == "redrive" and can_redrive and affinity:
+ out.append("redrive")
+ if can_relay:
+ out.append("relay_usage")
+ return out
+
+
[email protected]("hook", ["none", "fold", "redrive"])
[email protected]("can_redrive", [False, True])
[email protected]("can_relay", [False, True])
[email protected]("affinity", [False, True])
+def test_obligations_matrix(
+ headroom_client, hook: str, can_redrive: bool, can_relay: bool, affinity: bool
+) -> None:
+ """I-OBLIG + I-NOSHRINK over every capability combination and hook kind."""
+ fold = redrive = None
+ if hook == "fold":
+ fold = fold_only_hook.register(max_chars=100)
+ elif hook == "redrive":
+ redrive = redrive_hook_ext.register()
+ sent = _body(
+ gateway={
+ "can_redrive": can_redrive,
+ "can_relay_response": can_relay,
+ "session_affinity": affinity,
+ },
+ tools=openai_tools(),
+ )
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["obligations"] == _expected_obligations(hook, can_redrive, can_relay, affinity)
+ assert data["gateway"] == {
+ "can_redrive": can_redrive,
+ "can_relay_response": can_relay,
+ "session_affinity": affinity,
+ }
+ names = tool_names(data["body"]["tools"])
+ if "redrive" in data["obligations"]:
+ assert redrive is not None and redrive.shrink_calls == 1
+ assert "search_tools" in names
+ assert not any(n.startswith("deferred_") for n in names)
+ else:
+ # I-NOSHRINK: tools are a subset of what came in, in order.
+ assert "search_tools" not in names
+ assert names == tool_names(sent["tools"])
+ if redrive is not None:
+ assert redrive.shrink_calls == 0
+ if fold is not None:
+ # A stream-safe hook runs regardless of the redrive capability.
+ assert fold.request_calls == 1
+ assert data["body"]["messages"][2]["content"].endswith(fold_only_hook.FOLD_MARKER)
+ assert "turn_hook" in data["transforms_applied"]
+ # A pending turn exists iff there is something to wait for.
+ registry = registry_of(headroom_client)
+ assert registry is not None
+ if data["obligations"]:
+ assert registry.get(data["turn_id"]) is not None
+ else:
+ assert registry.get(data["turn_id"]) is None
+
+
+def test_redrive_hook_tools_delta_is_reported(headroom_client) -> None:
+ """I-OBLIG: a hook that shrinks tools is reported as ``turn_hook:tools:<n>tok``
+ (mirrors the chat path) so the savings are attributable."""
+ redrive_hook_ext.register()
+ sent = _body(gateway={"can_redrive": True}, tools=openai_tools())
+ data = compress(headroom_client, sent).json()
+ assert data["obligations"] == ["redrive"]
+ tags = [t for t in data["transforms_applied"] if t.startswith("turn_hook:tools:")]
+ assert len(tags) == 1, data["transforms_applied"]
+ assert re.match(r"^turn_hook:tools:\d+tok$", tags[0])
+
+
+def test_session_mode_replays_hook_output(headroom_client) -> None:
+ """I-BODY in session mode: the hook-rewritten messages are what the gateway
+ forwards, so they must be what turn 2 replays byte-for-byte."""
+ fold_only_hook.register(max_chars=120)
+ history = big_tool_history()
+ turn1 = compress(
+ headroom_client, _body(history, config={"session_id": "gw-fold"}, gateway={})
+ ).json()
+ folded = turn1["body"]["messages"][2]["content"]
+ assert folded.endswith(fold_only_hook.FOLD_MARKER)
+ turn2 = compress(
+ headroom_client,
+ _body(
+ history + [{"role": "assistant", "content": "ok"}, {"role": "user", "content": "more"}],
+ config={"session_id": "gw-fold"},
+ gateway={},
+ ),
+ ).json()
+ assert canonical(turn2["body"]["messages"][: len(turn1["body"]["messages"])]) == canonical(
+ turn1["body"]["messages"]
+ )
+ assert turn2["body"]["messages"][-1]["content"] == "more"
+
+
+def test_turn_ids_are_unique_per_request(headroom_client) -> None:
+ """I-KEYS: every request half mints a fresh id, registered or not."""
+ ids = {compress(headroom_client, _body(gateway={})).json()["turn_id"] for _ in range(5)}
+ assert len(ids) == 5
diff --git a/tests/gateway/test_contract_response_half.py b/tests/gateway/test_contract_response_half.py
new file mode 100644
index 000000000..5d5859c5d
--- /dev/null
+++ b/tests/gateway/test_contract_response_half.py
@@ -0,0 +1,444 @@
+"""Response half of the gateway turn contract: ``POST /v1/compress/response`` (spec section 2).
+
+Invariants protected here:
+
+* R-LOOKUP - unknown/expired turn -> 404 ``unknown_turn``; a completed turn is
+ gone (second post is 404).
+* R-VALID - 400 on missing/invalid ``turn_id``, non-object ``response``,
+ non-object/negative/bool usage, and a missing ``response`` on a
+ turn that carries ``redrive``.
+* R-DONE - shape of the ``done`` answer; ``response`` is null unless a hook
+ replaced it.
+* R-USAGE - Anthropic / OpenAI / Kong usage shapes feed the session tracker
+ exactly like ``/v1/usage`` (same ``frozen_message_count``); a
+ usage with no cache signal is accepted but not applied.
+* R-OUTCOME - with ``relay_usage`` the RequestOutcome is deferred and recorded
+ exactly once, completed with the provider's numbers; without it
+ the outcome is recorded at the request half as today; registry
+ expiry records the draft.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+import pytest
+
+from tests.gateway.conftest import compress, count_loop_tasks, registry_of
+from tests.gateway.samples import big_tool_history
+
+RESPONSE_HALF = "/v1/compress/response"
+DONE_KEYS = {"action", "turn_id", "response", "frozen_message_count", "usage_applied", "rounds"}
+
+
+def _open_turn(client, session_id: str | None = "resp-s", **gateway: Any) -> dict[str, Any]:
+ gateway.setdefault("can_relay_response", True)
+ body: dict[str, Any] = {"model": "gpt-4o", "messages": big_tool_history(), "gateway": gateway}
+ if session_id is not None:
+ body["config"] = {"session_id": session_id}
+ resp = compress(client, body)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert "relay_usage" in data["obligations"]
+ return data
+
+
+def _post(client, payload: dict[str, Any]):
+ return client.post(RESPONSE_HALF, json=payload)
+
+
+# --------------------------------------------------------------------------- #
+# R-LOOKUP / R-VALID #
+# --------------------------------------------------------------------------- #
+
+
+def test_unknown_turn_is_404(headroom_client) -> None:
+ """R-LOOKUP"""
+ resp = _post(headroom_client, {"turn_id": "0" * 32, "usage": {"prompt_tokens": 1}})
+ assert resp.status_code == 404, resp.text
+ assert resp.json()["error"]["type"] == "unknown_turn"
+
+
+def test_unknown_turn_leaves_no_footprint(headroom_client) -> None:
+ """R-LOOKUP: a flood of bogus ids must not grow the registry."""
+ registry = registry_of(headroom_client)
+ assert registry is not None
+ before = len(registry)
+ for i in range(10):
+ assert _post(headroom_client, {"turn_id": f"{i:032x}"}).status_code == 404
+ assert len(registry) == before
+
+
+ "payload",
+ [
+ {},
+ {"turn_id": None},
+ {"turn_id": 42},
+ {"turn_id": ""},
+ {"turn_id": "x" * 300},
+ ],
+ ids=["missing", "null", "int", "empty", "too-long"],
+)
+def test_invalid_turn_id_is_400(headroom_client, payload: dict[str, Any]) -> None:
+ """R-VALID"""
+ resp = _post(headroom_client, payload)
+ assert resp.status_code == 400, resp.text
+ assert resp.json()["error"]["type"] == "invalid_request"
+
+
+def test_invalid_json_is_400(headroom_client) -> None:
+ """R-VALID"""
+ resp = headroom_client.post(
+ RESPONSE_HALF, content=b"nope", headers={"content-type": "application/json"}
+ )
+ assert resp.status_code == 400
+
+
+ "extra",
+ [
+ {"response": "not-an-object"},
+ {"response": [1, 2]},
+ {"usage": "nope"},
+ {"usage": {"prompt_tokens": -1}},
+ {"usage": {"cache_read_input_tokens": True}},
+ {"usage": {"prompt_tokens_details": {"cached_tokens": -5}}},
+ ],
+ ids=[
+ "response-str",
+ "response-list",
+ "usage-str",
+ "usage-negative",
+ "usage-bool",
+ "cached-negative",
+ ],
+)
+def test_malformed_response_or_usage_is_400_and_keeps_turn(
+ headroom_client, extra: dict[str, Any]
+) -> None:
+ """R-VALID: a rejected relay must not consume the turn."""
+ turn = _open_turn(headroom_client)
+ resp = _post(headroom_client, {"turn_id": turn["turn_id"], **extra})
+ assert resp.status_code == 400, resp.text
+ assert resp.json()["error"]["type"] == "invalid_request"
+ assert registry_of(headroom_client).get(turn["turn_id"]) is not None
+
+
+# --------------------------------------------------------------------------- #
+# R-DONE #
+# --------------------------------------------------------------------------- #
+
+
+def test_done_with_null_response_and_turn_removed(headroom_client) -> None:
+ """R-DONE + R-LOOKUP: no hook ran, so ``response`` is null; the turn is consumed."""
+ turn = _open_turn(headroom_client)
+ resp = _post(
+ headroom_client,
+ {
+ "turn_id": turn["turn_id"],
+ "status": 200,
+ "latency_ms": 12.5,
+ "model": "gpt-4o-2024-08-06",
+ "usage": {"prompt_tokens": 100, "completion_tokens": 7},
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert set(data) == DONE_KEYS
+ assert data["action"] == "done"
+ assert data["turn_id"] == turn["turn_id"]
+ assert data["response"] is None
+ assert data["rounds"] == 0
+ assert data["usage_applied"] is False # no cache signal in that usage
+ assert isinstance(data["frozen_message_count"], int)
+ assert registry_of(headroom_client).get(turn["turn_id"]) is None
+ again = _post(headroom_client, {"turn_id": turn["turn_id"]})
+ assert again.status_code == 404
+ assert again.json()["error"]["type"] == "unknown_turn"
+
+
+def test_done_without_session_has_null_frozen_count(headroom_client) -> None:
+ """R-DONE: stateless turns carry no tracker, so ``frozen_message_count`` is null
+ and usage is never applied."""
+ turn = _open_turn(headroom_client, session_id=None)
+ resp = _post(
+ headroom_client,
+ {
+ "turn_id": turn["turn_id"],
+ "usage": {"input_tokens": 10, "output_tokens": 2, "cache_read_input_tokens": 5000},
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["action"] == "done"
+ assert data["frozen_message_count"] is None
+ assert data["usage_applied"] is False
+
+
+def test_done_with_minimal_payload(headroom_client) -> None:
+ """R-DONE: ``turn_id`` alone is a valid relay (status defaults to 200)."""
+ turn = _open_turn(headroom_client)
+ resp = _post(headroom_client, {"turn_id": turn["turn_id"]})
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["action"] == "done"
+ assert resp.json()["usage_applied"] is False
+
+
+def test_done_leaves_no_tasks_behind(headroom_client) -> None:
+ """R-DONE: a hook-less turn never starts a suspended runner, and after ``done``
+ the loop has exactly the tasks it had before."""
+ baseline = count_loop_tasks(headroom_client)
+ turn = _open_turn(headroom_client)
+ _post(headroom_client, {"turn_id": turn["turn_id"], "usage": {"prompt_tokens": 1}})
+ assert count_loop_tasks(headroom_client) <= baseline
+
+
+# --------------------------------------------------------------------------- #
+# R-USAGE #
+# --------------------------------------------------------------------------- #
+
+ANTHROPIC_WARM = {
+ "input_tokens": 200,
+ "output_tokens": 9,
+ "cache_read_input_tokens": 0,
+ "cache_creation_input_tokens": 50_000,
+}
+OPENAI_WARM = {
+ "prompt_tokens": 50_200,
+ "completion_tokens": 9,
+ "prompt_tokens_details": {"cached_tokens": 50_000},
+}
+OPENAI_TOPLEVEL_CACHED = {"prompt_tokens": 50_200, "completion_tokens": 9, "cached_tokens": 50_000}
+KONG_NESTED = {"usage": OPENAI_WARM} # Kong ai.proxy log statistics keep it nested
+
+
+def _frozen_after_legacy_usage(client, history, usage: dict[str, Any]) -> int:
+ """The yardstick: what ``/v1/usage`` does with the Anthropic-shaped equivalent."""
+ sid = f"legacy-{time.time_ns()}"
+ assert (
+ compress(
+ client, {"model": "gpt-4o", "messages": history, "config": {"session_id": sid}}
+ ).status_code
+ == 200
+ )
+ resp = client.post("/v1/usage", json={"session_id": sid, "usage": usage})
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["applied"] is True
+ return resp.json()["frozen_message_count"]
+
+
+ "usage",
+ [ANTHROPIC_WARM, OPENAI_WARM, OPENAI_TOPLEVEL_CACHED, KONG_NESTED],
+ ids=["anthropic", "openai", "openai-toplevel-cached", "kong-nested"],
+)
+def test_usage_shapes_apply_to_tracker_like_v1_usage(
+ headroom_client, usage: dict[str, Any]
+) -> None:
+ """R-USAGE: every accepted shape lands on the tracker and advances the frozen
+ count exactly as the equivalent ``/v1/usage`` relay does."""
+ history = big_tool_history()
+ expected = _frozen_after_legacy_usage(
+ headroom_client,
+ history,
+ {"cache_read_input_tokens": 0, "cache_creation_input_tokens": 50_000},
+ )
+ turn = _open_turn(headroom_client, session_id="usage-shape")
+ resp = _post(headroom_client, {"turn_id": turn["turn_id"], "usage": usage})
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["usage_applied"] is True
+ assert data["frozen_message_count"] == expected
+ assert data["frozen_message_count"] >= 1
+
+
+ "usage",
+ [
+ {"prompt_tokens": 120, "completion_tokens": 3},
+ {"input_tokens": 120, "output_tokens": 3},
+ {"prompt_tokens": 120, "prompt_tokens_details": {"cached_tokens": 0}},
+ {"input_tokens": 120, "output_tokens": 3, "cache_read_input_tokens": 0},
+ ],
+ ids=["openai-bare", "anthropic-bare", "openai-cached-zero", "anthropic-read-zero-only"],
+)
+def test_usage_without_cache_signal_is_accepted_but_not_applied(headroom_client, usage) -> None:
+ """R-USAGE: unlike ``/v1/usage`` a signal-free relay is not a 400 - the response
+ half still completes the outcome - but it must not touch the tracker (applying
+ it would assert a fully-cold prefix the provider never reported)."""
+ turn = _open_turn(headroom_client, session_id="usage-nosignal")
+ before = turn["session"]["frozen_message_count"]
+ resp = _post(headroom_client, {"turn_id": turn["turn_id"], "usage": usage})
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["action"] == "done"
+ assert data["usage_applied"] is False
+ tracker = headroom_client.app.state.proxy.session_tracker_store.peek(
+ "compress\x00usage-nosignal"
+ )
+ assert tracker is not None
+ assert tracker.get_frozen_message_count() == data["frozen_message_count"]
+ assert data["frozen_message_count"] <= max(before, len(big_tool_history()))
+
+
+def test_both_cache_fields_zero_is_a_confirmed_cold_turn(headroom_client) -> None:
+ """R-USAGE: both fields present and 0 is a genuine fully-cold signal (the same
+ rule ``/v1/usage`` applies) and IS applied."""
+ turn = _open_turn(headroom_client, session_id="usage-cold")
+ resp = _post(
+ headroom_client,
+ {
+ "turn_id": turn["turn_id"],
+ "usage": {
+ "input_tokens": 1,
+ "output_tokens": 1,
+ "cache_read_input_tokens": 0,
+ "cache_creation_input_tokens": 0,
+ },
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["usage_applied"] is True
+
+
+# --------------------------------------------------------------------------- #
+# R-OUTCOME #
+# --------------------------------------------------------------------------- #
+
+
+def test_outcome_deferred_then_recorded_once_with_provider_numbers(
+ headroom_client, outcome_spy
+) -> None:
+ """R-OUTCOME: with ``relay_usage`` nothing is recorded at the request half; the
+ response half records exactly one outcome carrying output/input/cache tokens
+ and the gateway-measured latency."""
+ outcomes = outcome_spy(headroom_client)
+ turn = _open_turn(headroom_client, session_id="outcome-defer")
+ assert outcomes == [], "outcome must be deferred while relay_usage is pending"
+ resp = _post(
+ headroom_client,
+ {
+ "turn_id": turn["turn_id"],
+ "status": 200,
+ "latency_ms": 250.0,
+ "usage": {
+ "prompt_tokens": 1234,
+ "completion_tokens": 56,
+ "prompt_tokens_details": {"cached_tokens": 1000},
+ },
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ assert len(outcomes) == 1
+ o = outcomes[0]
+ assert o.provider == "compress"
+ assert o.model == "gpt-4o"
+ assert o.output_tokens == 56
+ assert o.provider_input_tokens == 1234
+ assert o.cache_read_tokens == 1000
+ assert o.total_latency_ms >= 250.0
+ assert o.original_tokens == turn["tokens_before"]
+ assert o.optimized_tokens == turn["tokens_after"]
+ assert o.tokens_saved == turn["tokens_saved"]
+ assert o.status_code == 200
+
+
+def test_outcome_anthropic_cache_fields(headroom_client, outcome_spy) -> None:
+ """R-OUTCOME: Anthropic read + write buckets land on the outcome's cache fields."""
+ outcomes = outcome_spy(headroom_client)
+ turn = _open_turn(headroom_client, session_id="outcome-anthropic")
+ _post(
+ headroom_client,
+ {
+ "turn_id": turn["turn_id"],
+ "usage": {
+ "input_tokens": 300,
+ "output_tokens": 12,
+ "cache_read_input_tokens": 2000,
+ "cache_creation_input_tokens": 500,
+ },
+ },
+ )
+ assert len(outcomes) == 1
+ o = outcomes[0]
+ assert o.output_tokens == 12
+ assert o.cache_read_tokens == 2000
+ assert o.cache_write_tokens == 500
+ assert o.provider_input_tokens == 300
+
+
+def test_outcome_recorded_immediately_without_relay(headroom_client, outcome_spy) -> None:
+ """R-OUTCOME: no ``relay_usage`` -> recorded at the request half, as today."""
+ outcomes = outcome_spy(headroom_client)
+ body = {
+ "model": "gpt-4o",
+ "messages": big_tool_history(),
+ "gateway": {"can_relay_response": False},
+ }
+ data = compress(headroom_client, body).json()
+ assert data["obligations"] == []
+ assert len(outcomes) == 1
+ assert outcomes[0].output_tokens == 0
+
+
+def test_outcome_status_from_provider(headroom_client, outcome_spy) -> None:
+ """R-OUTCOME: a provider 5xx relayed through the response half is recorded with
+ that status so it cannot inflate save-rate (same rule as the proxy path)."""
+ outcomes = outcome_spy(headroom_client)
+ turn = _open_turn(headroom_client, session_id="outcome-5xx")
+ resp = _post(headroom_client, {"turn_id": turn["turn_id"], "status": 529, "latency_ms": 5})
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["action"] == "done"
+ assert len(outcomes) == 1
+ assert outcomes[0].status_code == 529
+
+
+def test_expiry_records_draft_and_then_404(headroom_client, outcome_spy) -> None:
+ """R-OUTCOME: a turn the gateway never completes is recorded as-is (output 0)
+ when the registry sweeps it, and a late relay is a 404."""
+ outcomes = outcome_spy(headroom_client)
+ turn = _open_turn(headroom_client, session_id="outcome-expire")
+ registry = registry_of(headroom_client)
+ assert registry is not None and registry.get(turn["turn_id"]) is not None
+ assert outcomes == []
+ # In production the sweep runs inside an HTTP handler, i.e. on the server
+ # loop, where the draft can be handed to the async outcome funnel. Run it
+ # there (the TestClient portal) rather than from the test thread, which has
+ # no loop and would only park the draft as an orphan.
+ deadline = time.time() + 10_000
+ headroom_client.portal.call(lambda: registry.sweep(deadline))
+ assert registry.get(turn["turn_id"]) is None
+ late = _post(headroom_client, {"turn_id": turn["turn_id"], "usage": {"prompt_tokens": 1}})
+ assert late.status_code == 404
+ assert late.json()["error"]["type"] == "unknown_turn"
+ # The record is scheduled as a task; the request above let the loop run it.
+ assert len(outcomes) == 1
+ assert outcomes[0].output_tokens == 0
+ assert outcomes[0].original_tokens == turn["tokens_before"]
+
+
+def test_ttl_env_is_honoured(make_headroom_client, monkeypatch, outcome_spy) -> None:
+ """R-OUTCOME: ``HEADROOM_GATEWAY_TURN_TTL_SECONDS`` bounds how long a pending
+ turn lives; a lazy sweep on the next lookup reclaims it."""
+ monkeypatch.setenv("HEADROOM_GATEWAY_TURN_TTL_SECONDS", "0")
+ client = make_headroom_client()
+ outcomes = outcome_spy(client)
+ turn = _open_turn(client, session_id="ttl-zero")
+ time.sleep(0.05)
+ late = _post(client, {"turn_id": turn["turn_id"], "usage": {"prompt_tokens": 1}})
+ assert late.status_code == 404, late.text
+ assert len(outcomes) == 1
+
+
+def test_registry_stats_shape(headroom_client) -> None:
+ """R-LOOKUP: ``stats()`` exposes at least the pending count for /stats and debugging."""
+ registry = registry_of(headroom_client)
+ assert registry is not None
+ turn = _open_turn(headroom_client, session_id="stats")
+ stats = registry.stats()
+ assert isinstance(stats, dict)
+ assert stats.get("pending") == len(registry) >= 1
+ _post(headroom_client, {"turn_id": turn["turn_id"]})
+ assert registry.stats().get("pending") == len(registry)
diff --git a/tests/gateway/test_invariants.py b/tests/gateway/test_invariants.py
new file mode 100644
index 000000000..432d142a6
--- /dev/null
+++ b/tests/gateway/test_invariants.py
@@ -0,0 +1,569 @@
+"""Cross-cutting invariants of the gateway turn contract (spec section 6, ``test_invariants``).
+
+1. NO-SHRINK-WITHOUT-RELOAD - a transform whose reload needs the response only
+ runs when the gateway declared it can re-drive (property over every
+ capability combination, hook kind and stream flag).
+2. BYTE-STABILITY - across 3 session turns the whole provider-bound body prefix
+ (messages, tools, system) is byte-identical, hooks or not.
+3. FAIL-OPEN - a broken pipeline never blocks the client: the gateway forwards
+ the original body.
+4. ISOLATION - sessions and turns never share state.
+5. CONCURRENCY - 20 sessions x 3 turns from threads stay isolated; the only
+ allowed 5xx is the lock-busy 503 on deliberate same-session parallelism.
+6. USAGE NORMALIZATION - ``normalize_usage`` never raises on a valid shape and
+ never invents a cache signal (parametrized; ``hypothesis`` is not installed).
+"""
+
+from __future__ import annotations
+
+import itertools
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from typing import Any
+from unittest.mock import AsyncMock
+
+import pytest
+
+from tests.gateway import fold_only_hook, redrive_hook_ext
+from tests.gateway.conftest import compress
+from tests.gateway.fake_provider import openai_text_response, openai_usage
+from tests.gateway.samples import (
+ SYSTEM_PROMPT,
+ big_tool_history,
+ canonical,
+ openai_tools,
+ tool_names,
+)
+
+SEARCH = redrive_hook_ext.SEARCH_TOOL_NAME
+
+
+def _body(messages=None, **extra: Any) -> dict[str, Any]:
+ return {"model": "gpt-4o", "messages": messages or big_tool_history(), **extra}
+
+
+# --------------------------------------------------------------------------- #
+# 1. No shrink without reload #
+# --------------------------------------------------------------------------- #
+
+_CAPS = list(itertools.product([False, True], repeat=3)) # can_redrive, can_relay, affinity
+
+
[email protected]("hooks", ["redrive", "fold+redrive"])
[email protected]("stream", [False, True])
[email protected]("can_redrive,can_relay,affinity", _CAPS)
+def test_no_shrink_without_reload(
+ headroom_client, hooks, stream, can_redrive, can_relay, affinity
+) -> None:
+ """Invariant 1: ``search_tools`` present in the provider body <=> ``"redrive"``
+ in obligations; and without ``redrive`` the tools are exactly the input tools."""
+ if hooks == "fold+redrive":
+ fold_only_hook.register(max_chars=100)
+ redrive = redrive_hook_ext.register()
+ sent = _body(
+ tools=openai_tools(),
+ stream=stream,
+ gateway={
+ "can_redrive": can_redrive,
+ "can_relay_response": can_relay,
+ "session_affinity": affinity,
+ },
+ )
+ # A real gateway clears can_redrive for streamed turns; headroom itself sees
+ # only the flag, so the property is stated on the flag headroom received.
+ data = compress(headroom_client, sent).json()
+ names = tool_names(data["body"]["tools"])
+ shrunk = SEARCH in names
+ assert shrunk == ("redrive" in data["obligations"])
+ assert shrunk == (can_redrive and affinity)
+ if not shrunk:
+ assert names == tool_names(sent["tools"])
+ assert redrive.shrink_calls == 0
+ assert data["body"]["stream"] is stream
+
+
+# --------------------------------------------------------------------------- #
+# 2. Whole-body byte stability #
+# --------------------------------------------------------------------------- #
+
+
+def _three_turns(client, session_id: str, gateway: dict[str, Any]) -> list[dict[str, Any]]:
+ history = big_tool_history()
+ turns = [history]
+ turns.append(
+ history
+ + [
+ {"role": "assistant", "content": "Listed."},
+ {"role": "user", "content": "Sort by score."},
+ ]
+ )
+ turns.append(
+ turns[1]
+ + [{"role": "assistant", "content": "Sorted."}, {"role": "user", "content": "Top 3?"}]
+ )
+ out = []
+ for messages in turns:
+ resp = compress(
+ client,
+ _body(
+ messages,
+ tools=openai_tools(),
+ system=SYSTEM_PROMPT,
+ temperature=0.0,
+ config={"session_id": session_id},
+ gateway=gateway,
+ ),
+ )
+ assert resp.status_code == 200, resp.text
+ out.append(resp.json())
+ return out
+
+
[email protected]("hooks", ["none", "fold", "redrive", "fold+redrive"])
+def test_whole_body_byte_stable_across_three_turns(headroom_client, hooks) -> None:
+ """Invariant 2: every previously returned message, the compacted tools and the
+ system prompt come back byte-for-byte on later turns."""
+ if "fold" in hooks:
+ fold_only_hook.register(max_chars=150)
+ if "redrive" in hooks:
+ redrive_hook_ext.register()
+ gateway = {"can_redrive": "redrive" in hooks, "can_relay_response": False}
+ t1, t2, t3 = _three_turns(headroom_client, f"stable-{hooks}", gateway)
+ # Something was actually compressed, otherwise stability is vacuous.
+ assert t1["body"]["messages"][2]["content"] != big_tool_history()[2]["content"]
+ for prev, nxt in ((t1, t2), (t2, t3)):
+ p, n = prev["body"], nxt["body"]
+ assert canonical(n["messages"][: len(p["messages"])]) == canonical(p["messages"])
+ assert canonical(n["tools"]) == canonical(p["tools"])
+ assert n["system"] == p["system"] == SYSTEM_PROMPT
+ assert n["temperature"] == 0.0
+ # The whole body minus the growing tail is stable too.
+ p_head = {k: v for k, v in p.items() if k != "messages"}
+ n_head = {k: v for k, v in n.items() if k != "messages"}
+ assert canonical(n_head) == canonical(p_head)
+ assert t3["body"]["messages"][-1]["content"] == "Top 3?"
+ if "redrive" in hooks:
+ assert tool_names(t1["body"]["tools"]) == ["get_items", SEARCH]
+
+
+def test_tool_compaction_bytes_stable_across_sessions(headroom_client) -> None:
+ """Invariant 2 (cross-session): the compaction cache is keyed by tool bytes, so
+ two sessions sending the same tools get the same bytes (shared provider cache)."""
+ a = compress(
+ headroom_client, _body(tools=openai_tools(), config={"session_id": "tc-a"}, gateway={})
+ ).json()
+ b = compress(
+ headroom_client, _body(tools=openai_tools(), config={"session_id": "tc-b"}, gateway={})
+ ).json()
+ assert canonical(a["body"]["tools"]) == canonical(b["body"]["tools"])
+
+
+# --------------------------------------------------------------------------- #
+# 3. Fail-open #
+# --------------------------------------------------------------------------- #
+
+
+def test_fail_open_stateless_timeout_forwards_original_body(
+ headroom_client, fake_provider, make_gateway, monkeypatch
+) -> None:
+ """Invariant 3: stateless timeout -> 200 + originals; the gateway forwards them."""
+ proxy = headroom_client.app.state.proxy
+ monkeypatch.setattr(proxy, "_run_compression_in_executor", AsyncMock(side_effect=TimeoutError))
+ fake_provider.script([openai_text_response("still answered")])
+ body = _body(tools=openai_tools(), temperature=0.5)
+ result = make_gateway(can_redrive=True, can_relay_response=True).turn(body, None)
+ assert result.path == "proxy"
+ assert result.compress_response["compression_skipped"] is True
+ assert result.compress_response["obligations"] == []
+ sent = fake_provider.calls[0].body
+ assert sent["messages"] == body["messages"]
+ assert canonical(sent["tools"]) == canonical(body["tools"])
+ assert sent["temperature"] == 0.5
+ assert result.final_response["choices"][0]["message"]["content"] == "still answered"
+ # The plugin relays whenever a turn_id came back (it does not read
+ # obligations for that decision); nothing was registered, so headroom
+ # answers 404 and the plugin's fire-and-forget relay drops it silently.
+ assert all(x.status == 404 for x in result.response_half_calls)
+
+
+def test_fail_open_session_timeout_is_503_and_gateway_forwards_original(
+ headroom_client, fake_provider, make_gateway, monkeypatch
+) -> None:
+ """Invariant 3: session mode cannot fail open with originals (replay desync),
+ so headroom answers 503 and the GATEWAY fails open."""
+ proxy = headroom_client.app.state.proxy
+ monkeypatch.setattr(proxy, "_run_compression_in_executor", AsyncMock(side_effect=TimeoutError))
+ fake_provider.script([openai_text_response("still answered")])
+ body = _body(tools=openai_tools())
+ result = make_gateway(can_redrive=True, can_relay_response=True).turn(body, "fo-session")
+ assert result.path == "fail_open"
+ assert result.compress_status == 503
+ assert fake_provider.calls[0].body["messages"] == body["messages"]
+ assert result.final_status == 200
+ assert result.response_half_calls == []
+
+
+def test_fail_open_pipeline_exception(
+ headroom_client, fake_provider, make_gateway, monkeypatch
+) -> None:
+ """Invariant 3: a hard pipeline error is a 503 the gateway absorbs."""
+ proxy = headroom_client.app.state.proxy
+ monkeypatch.setattr(
+ proxy, "_run_compression_in_executor", AsyncMock(side_effect=RuntimeError("boom"))
+ )
+ result = make_gateway(can_redrive=True, can_relay_response=True).turn(_body(), "fo-boom")
+ assert result.path == "fail_open"
+ assert result.compress_status == 503
+ assert result.final_status == 200
+ assert len(fake_provider.calls) == 1
+
+
+def test_fail_open_headroom_unreachable(fake_provider, provider_client) -> None:
+ """Invariant 3: headroom down -> the client still gets the provider's answer."""
+ from tests.gateway.fake_gateway import FakeGateway
+
+ class _Down:
+ def post(self, *a: Any, **k: Any) -> Any:
+ raise ConnectionError("connection refused")
+
+ fake_provider.script([openai_text_response("answered without headroom")])
+ result = FakeGateway(_Down(), provider_client, can_redrive=True, can_relay_response=True).turn(
+ _body(), "down"
+ )
+ assert result.path == "fail_open"
+ assert result.compress_status is None
+ assert result.final_response["choices"][0]["message"]["content"] == "answered without headroom"
+
+
+def test_hook_exception_never_breaks_the_turn(headroom_client, fake_provider, make_gateway) -> None:
+ """Invariant 3 (hooks): a hook that raises in ``on_request`` or ``on_response``
+ is skipped; the turn completes and the client gets the provider's answer."""
+ from headroom.proxy.turn_hooks import register_turn_hook
+
+ class _Broken:
+ name = "broken"
+ stream_safe = False
+
+ def on_request(self, ctx: Any) -> None:
+ raise RuntimeError("request boom")
+
+ async def on_response(self, ctx: Any, response: Any, call_model: Any) -> Any:
+ raise RuntimeError("response boom")
+
+ register_turn_hook(_Broken())
+ fake_provider.script([openai_text_response("fine", response_id="chatcmpl-fine")])
+ result = make_gateway(can_redrive=True, can_relay_response=True).turn(
+ _body(tools=openai_tools()), "hook-boom"
+ )
+ assert result.compress_status == 200
+ assert result.final_response["id"] == "chatcmpl-fine"
+ assert tool_names(fake_provider.calls[0].tools) == tool_names(openai_tools())
+ if result.path == "loop":
+ assert result.done is not None and result.done["response"] is None
+ from tests.gateway.conftest import registry_of
+
+ assert registry_of(headroom_client).get(result.turn_id) is None
+
+
+# --------------------------------------------------------------------------- #
+# 4. Isolation #
+# --------------------------------------------------------------------------- #
+
+
+def test_cross_session_isolation(headroom_client) -> None:
+ """Invariant 4: two sessions with identical content keep separate replay state
+ and separate pending turns."""
+ from tests.gateway.conftest import registry_of
+
+ history = big_tool_history()
+ gw = {"can_relay_response": True}
+ a1 = compress(
+ headroom_client, _body(history, config={"session_id": "iso-a"}, gateway=gw)
+ ).json()
+ b1 = compress(
+ headroom_client, _body(history, config={"session_id": "iso-b"}, gateway=gw)
+ ).json()
+ assert a1["turn_id"] != b1["turn_id"]
+ registry = registry_of(headroom_client)
+ assert registry.get(a1["turn_id"]) is not None and registry.get(b1["turn_id"]) is not None
+ # Completing A's turn leaves B pending and untouched.
+ done_a = headroom_client.post(
+ "/v1/compress/response",
+ json={"turn_id": a1["turn_id"], "usage": openai_usage(500, 5, 400)},
+ )
+ assert done_a.status_code == 200 and done_a.json()["usage_applied"] is True
+ assert registry.get(a1["turn_id"]) is None
+ assert registry.get(b1["turn_id"]) is not None
+ a2 = compress(
+ headroom_client,
+ _body(
+ history + [{"role": "user", "content": "a next"}],
+ config={"session_id": "iso-a"},
+ gateway=gw,
+ ),
+ ).json()
+ b2 = compress(
+ headroom_client,
+ _body(
+ history + [{"role": "user", "content": "b next"}],
+ config={"session_id": "iso-b"},
+ gateway=gw,
+ ),
+ ).json()
+ assert canonical(a2["body"]["messages"][:3]) == canonical(a1["body"]["messages"])
+ assert canonical(b2["body"]["messages"][:3]) == canonical(b1["body"]["messages"])
+ assert a2["body"]["messages"][-1]["content"] == "a next"
+ assert b2["body"]["messages"][-1]["content"] == "b next"
+ # B's tracker never saw A's usage.
+ store = headroom_client.app.state.proxy.session_tracker_store
+ assert (
+ store.peek("compress\x00iso-b").get_frozen_message_count()
+ <= store.peek("compress\x00iso-a").get_frozen_message_count()
+ )
+
+
+def test_cross_turn_isolation_same_session(headroom_client) -> None:
+ """Invariant 4: two pending turns of ONE session are distinct; completing the
+ older one does not complete the newer one."""
+ from tests.gateway.conftest import registry_of
+
+ gw = {"can_relay_response": True}
+ t1 = compress(headroom_client, _body(config={"session_id": "iso-turns"}, gateway=gw)).json()
+ t2 = compress(
+ headroom_client,
+ _body(
+ big_tool_history() + [{"role": "user", "content": "2"}],
+ config={"session_id": "iso-turns"},
+ gateway=gw,
+ ),
+ ).json()
+ assert t1["turn_id"] != t2["turn_id"]
+ registry = registry_of(headroom_client)
+ assert (
+ headroom_client.post("/v1/compress/response", json={"turn_id": t1["turn_id"]}).status_code
+ == 200
+ )
+ assert registry.get(t1["turn_id"]) is None
+ assert registry.get(t2["turn_id"]) is not None
+ assert (
+ headroom_client.post("/v1/compress/response", json={"turn_id": t2["turn_id"]}).status_code
+ == 200
+ )
+ assert registry.get(t2["turn_id"]) is None
+
+
+# --------------------------------------------------------------------------- #
+# 5. Concurrency #
+# --------------------------------------------------------------------------- #
+
+
+def test_twenty_sessions_three_turns_concurrently(headroom_client) -> None:
+ """Invariant 5: distinct sessions in parallel are all 200 and each one's prefix
+ is byte-stable; no pending turn leaks."""
+ from tests.gateway.conftest import registry_of
+
+ history = big_tool_history()
+ gw = {"can_relay_response": True}
+ errors: list[str] = []
+
+ def _session(i: int) -> None:
+ sid = f"conc-{i}"
+ try:
+ prev: list[dict[str, Any]] | None = None
+ msgs = list(history)
+ for turn in range(3):
+ resp = compress(
+ headroom_client,
+ _body(msgs, tools=openai_tools(), config={"session_id": sid}, gateway=gw),
+ )
+ if resp.status_code != 200:
+ errors.append(f"{sid} turn {turn}: {resp.status_code} {resp.text[:200]}")
+ return
+ data = resp.json()
+ got = data["body"]["messages"]
+ if prev is not None and canonical(got[: len(prev)]) != canonical(prev):
+ errors.append(f"{sid} turn {turn}: prefix drifted")
+ prev = got
+ done = headroom_client.post(
+ "/v1/compress/response",
+ json={
+ "turn_id": data["turn_id"],
+ "usage": openai_usage(400, 5, 300 if turn else 0),
+ },
+ )
+ if done.status_code != 200:
+ errors.append(
+ f"{sid} turn {turn}: response half {done.status_code} {done.text[:200]}"
+ )
+ msgs = msgs + [
+ {"role": "assistant", "content": f"a{turn}"},
+ {"role": "user", "content": f"u{turn}"},
+ ]
+ except Exception as exc: # pragma: no cover - surfaced via errors
+ errors.append(f"{sid}: {exc!r}")
+
+ with ThreadPoolExecutor(max_workers=20) as pool:
+ list(pool.map(_session, range(20)))
+ assert errors == []
+ assert len(registry_of(headroom_client)) == 0
+
+
+def test_same_session_parallel_turns_only_503_on_lock_busy(headroom_client) -> None:
+ """Invariant 5: deliberate same-session parallelism may yield the lock-busy 503
+ (``compression_timeout``) and nothing else above 4xx."""
+ history = big_tool_history(400)
+ statuses: list[int] = []
+ bodies: list[dict[str, Any]] = []
+ lock = threading.Lock()
+
+ def _turn(i: int) -> None:
+ resp = compress(
+ headroom_client,
+ _body(
+ history + [{"role": "user", "content": f"p{i}"}],
+ config={"session_id": "conc-same"},
+ gateway={},
+ ),
+ )
+ with lock:
+ statuses.append(resp.status_code)
+ bodies.append(resp.json())
+
+ with ThreadPoolExecutor(max_workers=6) as pool:
+ list(pool.map(_turn, range(6)))
+ assert set(statuses) <= {200, 503}, statuses
+ assert 200 in statuses
+ for status, body in zip(statuses, bodies):
+ if status == 503:
+ assert body["error"]["type"] == "compression_timeout"
+ else:
+ assert "turn_id" in body and body["obligations"] == []
+
+
+# --------------------------------------------------------------------------- #
+# 6. normalize_usage #
+# --------------------------------------------------------------------------- #
+
+_VALID_USAGES: list[tuple[str, dict[str, Any], tuple[Any, Any, Any, Any], bool]] = [
+ # (id, usage, (input, output, cache_read, cache_write), has_cache_signal)
+ (
+ "anthropic-full",
+ {
+ "input_tokens": 10,
+ "output_tokens": 2,
+ "cache_read_input_tokens": 5,
+ "cache_creation_input_tokens": 3,
+ },
+ (10, 2, 5, 3),
+ True,
+ ),
+ (
+ "anthropic-read-only",
+ {"input_tokens": 10, "output_tokens": 2, "cache_read_input_tokens": 0},
+ (10, 2, 0, None),
+ True,
+ ),
+ ("anthropic-bare", {"input_tokens": 10, "output_tokens": 2}, (10, 2, None, None), False),
+ (
+ "openai-details",
+ {
+ "prompt_tokens": 10,
+ "completion_tokens": 2,
+ "prompt_tokens_details": {"cached_tokens": 4},
+ },
+ (10, 2, 4, None),
+ True,
+ ),
+ (
+ "openai-toplevel",
+ {"prompt_tokens": 10, "completion_tokens": 2, "cached_tokens": 4},
+ (10, 2, 4, None),
+ True,
+ ),
+ ("openai-bare", {"prompt_tokens": 10, "completion_tokens": 2}, (10, 2, None, None), False),
+ (
+ "openai-details-empty",
+ {"prompt_tokens": 10, "prompt_tokens_details": {}},
+ (10, None, None, None),
+ False,
+ ),
+ (
+ "kong-nested",
+ {
+ "usage": {
+ "prompt_tokens": 10,
+ "completion_tokens": 2,
+ "prompt_tokens_details": {"cached_tokens": 4},
+ }
+ },
+ (10, 2, 4, None),
+ True,
+ ),
+ ("empty", {}, (None, None, None, None), False),
+ ("unrelated-keys", {"total_tokens": 12, "foo": "bar"}, (None, None, None, None), False),
+ (
+ "zero-everything",
+ {"prompt_tokens": 0, "completion_tokens": 0, "cached_tokens": 0},
+ (0, 0, 0, None),
+ True,
+ ),
+ (
+ "nested-twice-only-descends-once",
+ {"usage": {"usage": {"prompt_tokens": 10}}},
+ (None, None, None, None),
+ False,
+ ),
+]
+
+
[email protected]("case", _VALID_USAGES, ids=[c[0] for c in _VALID_USAGES])
+def test_normalize_usage_valid_shapes(case) -> None:
+ """Invariant 6: valid shapes never raise, fields map as specified, and a cache
+ signal is reported only when a cache field is present."""
+ from headroom.proxy.gateway_turn import normalize_usage
+
+ _, usage, expected, has_signal = case
+ n = normalize_usage(usage)
+ assert (n.input_tokens, n.output_tokens, n.cache_read, n.cache_write) == expected
+ assert n.has_cache_signal is has_signal
+ assert n.has_cache_signal == (n.cache_read is not None or n.cache_write is not None)
+
+
+ "usage",
+ [
+ {"prompt_tokens": -1},
+ {"input_tokens": True},
+ {"cache_read_input_tokens": -7},
+ {"prompt_tokens_details": {"cached_tokens": False}},
+ {"cached_tokens": -1},
+ {"completion_tokens": -2},
+ ],
+ ids=["neg-prompt", "bool-input", "neg-read", "bool-cached", "neg-cached", "neg-completion"],
+)
+def test_normalize_usage_rejects_bools_and_negatives(usage) -> None:
+ """Invariant 6: bools and negatives are a ValueError (the handler maps to 400)."""
+ from headroom.proxy.gateway_turn import normalize_usage
+
+ with pytest.raises(ValueError):
+ normalize_usage(usage)
+
+
[email protected]("value", ["12", 12.5, [1], {"n": 1}])
+def test_normalize_usage_rejects_non_integers(value) -> None:
+ """Invariant 6: a counter that is not an integer (a string, a float, a nested
+ object) is a ValueError - the same strictness ``/v1/usage`` applies - so a
+ malformed relay is a visible 400 rather than a silently dropped signal."""
+ from headroom.proxy.gateway_turn import normalize_usage
+
+ with pytest.raises(ValueError):
+ normalize_usage({"prompt_tokens": value})
+
+
+def test_normalize_usage_null_field_is_absent() -> None:
+ """Invariant 6: JSON ``null`` means the provider omitted the counter."""
+ from headroom.proxy.gateway_turn import normalize_usage
+
+ n = normalize_usage({"prompt_tokens": None, "cached_tokens": None})
+ assert n.input_tokens is None
+ assert n.has_cache_signal is False
diff --git a/tests/gateway/test_kong_integration.py b/tests/gateway/test_kong_integration.py
new file mode 100644
index 000000000..64ae60c81
--- /dev/null
+++ b/tests/gateway/test_kong_integration.py
@@ -0,0 +1,542 @@
+"""End-to-end: Kong 3.9 + the `headroom` Lua plugin against a live Headroom.
+
+Skipped unless ``HEADROOM_KONG_E2E=1``. Needs Docker Desktop (the container
+reaches the host as ``host.docker.internal``). Runs Headroom in-process on a
+uvicorn thread (``HEADROOM_COMPRESS_ALLOW_REMOTE=1``) and the scripted fake
+provider on another, brings up the kong-plugin-headroom repo's ``docker/`` compose with
+``docker compose up -d --wait``, and sends requests through Kong's ``/openai``
+route.
+
+Four checks, mirroring the spec (section 5):
+
+a. proxy path: the provider receives a compressed body and the usage relay
+ completes the pending turn (registry drained, outcome recorded);
+b. loop path: a re-driving hook makes Headroom ask for a redrive; the client
+ sees only the final answer and the provider saw two calls;
+c. fail-open: with Headroom stopped the request still reaches the provider;
+d. header contract: an Anthropic request through ``/anthropic`` with a large
+ tool set is natively deferred, and the ``anthropic-beta`` header Headroom
+ returns (client betas + ``advanced-tool-use``) reaches the provider.
+
+Ports (env, defaults): ``HEADROOM_PORT=18787``, ``PROVIDER_PORT=18081``,
+``KONG_PROXY_PORT=18000``, ``KONG_ADMIN_PORT=18001``.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import socket
+import subprocess
+import threading
+import time
+from collections.abc import Iterator
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+
+from headroom.proxy.models import ProxyConfig
+from headroom.proxy.turn_hooks import clear_turn_hooks
+from tests.gateway.fake_provider import (
+ FakeProvider,
+ anthropic_text_response,
+ openai_text_response,
+ openai_tool_call_response,
+ openai_usage,
+)
+from tests.gateway.samples import big_tool_history, openai_tools, tool_names
+
+try: # owned by the harness; may land after this file
+ from tests.gateway.redrive_hook_ext import register as register_redrive_hook
+except ImportError: # pragma: no cover - harness not present yet
+ register_redrive_hook = None
+
+pytestmark = pytest.mark.skipif(
+ os.environ.get("HEADROOM_KONG_E2E") != "1",
+ reason="set HEADROOM_KONG_E2E=1 to run the Kong docker integration",
+)
+
+REPO = Path(__file__).resolve().parents[2]
+# The Kong plugin lives in its own repo (kong-plugin-headroom); by default a
+# sibling checkout of this one. Point HEADROOM_KONG_PLUGIN_DIR elsewhere if not.
+PLUGIN_DIR = Path(
+ os.environ.get("HEADROOM_KONG_PLUGIN_DIR") or str(REPO.parent / "kong-plugin-headroom")
+).resolve()
+COMPOSE_FILE = PLUGIN_DIR / "docker" / "docker-compose.yml"
+COMPOSE_PROJECT = "headroom-kong-e2e"
+
+HEADROOM_PORT = int(os.environ.get("HEADROOM_PORT", "18787"))
+PROVIDER_PORT = int(os.environ.get("PROVIDER_PORT", "18081"))
+KONG_PROXY_PORT = int(os.environ.get("KONG_PROXY_PORT", "18000"))
+KONG_ADMIN_PORT = int(os.environ.get("KONG_ADMIN_PORT", "18001"))
+SESSION_HEADER = "x-headroom-session-id"
+
+
+# --------------------------------------------------------------------------- #
+# Headroom on a uvicorn thread #
+# --------------------------------------------------------------------------- #
+
+
+class HeadroomServer:
+ """Headroom's FastAPI app served on ``0.0.0.0:<port>`` from a daemon thread."""
+
+ def __init__(self, port: int) -> None:
+ self.port = port
+ self.app: Any = None
+ self.proxy: Any = None
+ self._server: Any = None
+ self._thread: threading.Thread | None = None
+ self.recorded_outcomes: list[Any] = []
+
+ def start(self) -> str:
+ import uvicorn
+
+ from headroom.proxy.server import create_app
+
+ # The loopback guard on /v1/compress is decided when the app is built.
+ os.environ["HEADROOM_COMPRESS_ALLOW_REMOTE"] = "1"
+ self.app = create_app(
+ ProxyConfig(
+ host="0.0.0.0",
+ port=self.port,
+ optimize=True,
+ cache_enabled=False,
+ rate_limit_enabled=False,
+ cost_tracking_enabled=False,
+ log_requests=False,
+ image_optimize=False,
+ )
+ )
+ self.proxy = self.app.state.proxy
+ self._capture_outcomes()
+ config = uvicorn.Config(self.app, host="0.0.0.0", port=self.port, log_level="warning")
+ self._server = uvicorn.Server(config)
+ self._thread = threading.Thread(target=self._server.run, name="headroom-e2e", daemon=True)
+ self._thread.start()
+ deadline = time.time() + 20
+ while not self._server.started:
+ if time.time() > deadline or not self._thread.is_alive():
+ raise RuntimeError("headroom did not start")
+ time.sleep(0.05)
+ return f"http://127.0.0.1:{self.port}"
+
+ def _capture_outcomes(self) -> None:
+ """Wrap the proxy's outcome recorder so the relay's effect is observable."""
+ original = getattr(self.proxy, "_record_request_outcome", None)
+ if original is None:
+ return
+
+ def recording(outcome: Any, *args: Any, **kwargs: Any) -> Any:
+ self.recorded_outcomes.append(outcome)
+ return original(outcome, *args, **kwargs)
+
+ self.proxy._record_request_outcome = recording
+
+ def stop(self) -> None:
+ if self._server is None:
+ return
+ self._server.should_exit = True
+ if self._thread is not None:
+ self._thread.join(10)
+ self._server = None
+ self._thread = None
+
+ def pending_turns(self) -> int | None:
+ registry = getattr(self.proxy, "gateway_turns", None)
+ return None if registry is None else len(registry)
+
+
+def _wait_port_closed(port: int, timeout: float = 10.0) -> None:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ with socket.socket() as s:
+ s.settimeout(0.2)
+ if s.connect_ex(("127.0.0.1", port)) != 0:
+ return
+ time.sleep(0.1)
+
+
+# --------------------------------------------------------------------------- #
+# docker compose #
+# --------------------------------------------------------------------------- #
+
+
+def _compose(*args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
+ env = dict(
+ os.environ,
+ HEADROOM_PORT=str(HEADROOM_PORT),
+ PROVIDER_PORT=str(PROVIDER_PORT),
+ KONG_PROXY_PORT=str(KONG_PROXY_PORT),
+ KONG_ADMIN_PORT=str(KONG_ADMIN_PORT),
+ )
+ return subprocess.run(
+ ["docker", "compose", "-f", str(COMPOSE_FILE), "-p", COMPOSE_PROJECT, *args],
+ env=env,
+ capture_output=True,
+ text=True,
+ check=check,
+ timeout=300,
+ )
+
+
+def kong_logs(tail: int = 80) -> str:
+ result = _compose("logs", "--no-color", "--tail", str(tail), "kong", check=False)
+ return result.stdout + result.stderr
+
+
+@dataclass
+class Stack:
+ provider: FakeProvider
+ headroom: HeadroomServer
+ kong_url: str
+
+ def chat(
+ self, body: dict[str, Any], session: str | None, timeout: float = 90
+ ) -> httpx.Response:
+ headers = {"content-type": "application/json", "authorization": "Bearer sk-test"}
+ if session:
+ headers[SESSION_HEADER] = session
+ return httpx.post(
+ f"{self.kong_url}/openai/v1/chat/completions",
+ content=json.dumps(body),
+ headers=headers,
+ timeout=timeout,
+ )
+
+ def messages(
+ self,
+ body: dict[str, Any],
+ session: str | None,
+ extra_headers: dict[str, str] | None = None,
+ timeout: float = 90,
+ ) -> httpx.Response:
+ """POST an Anthropic Messages body through Kong's ``/anthropic`` route."""
+ headers = {
+ "content-type": "application/json",
+ "x-api-key": "sk-ant-test",
+ "anthropic-version": "2023-06-01",
+ }
+ if session:
+ headers[SESSION_HEADER] = session
+ headers.update(extra_headers or {})
+ return httpx.post(
+ f"{self.kong_url}/anthropic/v1/messages",
+ content=json.dumps(body),
+ headers=headers,
+ timeout=timeout,
+ )
+
+
[email protected](scope="module")
+def stack() -> Iterator[Stack]:
+ if not COMPOSE_FILE.exists():
+ pytest.skip(f"missing {COMPOSE_FILE}")
+ provider = FakeProvider()
+ provider.start(PROVIDER_PORT, host="0.0.0.0")
+ stack_obj = Stack(
+ provider=provider,
+ headroom=HeadroomServer(HEADROOM_PORT),
+ kong_url=f"http://127.0.0.1:{KONG_PROXY_PORT}",
+ )
+ try:
+ stack_obj.headroom.start()
+ try:
+ _compose("up", "-d", "--wait", "--force-recreate")
+ except subprocess.CalledProcessError as exc:
+ pytest.fail(f"compose failed: {exc.stderr}\n--- kong logs ---\n{kong_logs()}")
+ yield stack_obj
+ finally:
+ # `down` even after a failed `up`: it may have created the container.
+ _compose("down", "-v", "--remove-orphans", check=False)
+ stack_obj.headroom.stop() # the fail-open test may have swapped this
+ provider.stop()
+ os.environ.pop("HEADROOM_COMPRESS_ALLOW_REMOTE", None)
+
+
[email protected](autouse=True)
+def _arm_redrive_hook() -> Iterator[None]:
+ """Register the re-driving hook for every test in this module.
+
+ Function-scoped on purpose: ``tests/gateway/conftest.py`` clears turn hooks
+ around each test, and module fixtures run before that clear. Hooks are
+ process-global, so the uvicorn thread sees this registration.
+ """
+ if register_redrive_hook is not None:
+ register_redrive_hook()
+ yield
+ clear_turn_hooks()
+
+
+def _poll(predicate: Any, timeout: float = 10.0, interval: float = 0.1) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if predicate():
+ return True
+ time.sleep(interval)
+ return bool(predicate())
+
+
+def _sse_frames(text: str) -> list[dict[str, Any]]:
+ frames = []
+ for line in text.splitlines():
+ if line.startswith("data:"):
+ data = line[5:].strip()
+ if data and data != "[DONE]":
+ frames.append(json.loads(data))
+ return frames
+
+
+# --------------------------------------------------------------------------- #
+# (a) proxy path #
+# --------------------------------------------------------------------------- #
+
+
+def test_proxy_path_compresses_and_relays_usage(stack: Stack) -> None:
+ """Streaming turn: Kong proxies, provider sees the compressed body, and the
+ body_filter/log relay closes the turn on Headroom's side."""
+ stack.provider.reset()
+ stack.headroom.recorded_outcomes.clear()
+ stack.provider.script(
+ [openai_text_response("streamed answer", usage=openai_usage(120, 7, cached=64))]
+ )
+ body = {
+ "model": "gpt-4o",
+ "messages": big_tool_history(),
+ "stream": True,
+ "stream_options": {"include_usage": True},
+ }
+ sent_bytes = len(json.dumps(body["messages"]))
+
+ resp = stack.chat(body, session="kong-e2e-proxy")
+ assert resp.status_code == 200, f"{resp.text}\n{kong_logs()}"
+ assert resp.headers["content-type"].startswith("text/event-stream")
+ frames = _sse_frames(resp.text)
+ assert any(f.get("usage") for f in frames), "provider's final SSE chunk should carry usage"
+
+ assert len(stack.provider.calls) == 1, kong_logs()
+ received = stack.provider.calls[0]
+ assert received.stream is True
+ received_bytes = len(json.dumps(received.messages))
+ assert received_bytes < sent_bytes, (
+ f"provider got {received_bytes}B, client sent {sent_bytes}B: not compressed\n{kong_logs()}"
+ )
+ # The relay carries the plugin version; the body must not leak Headroom-only keys.
+ assert "gateway" not in received.body and "config" not in received.body
+
+ # Response half: the log-phase timer posts usage; Headroom drains the turn
+ # and records one outcome. Requires the server side of the contract.
+ pending = stack.headroom.pending_turns
+ if pending() is None:
+ pytest.fail(
+ "TODO(gateway-turn-contract): proxy has no `gateway_turns` registry yet; "
+ "the usage relay cannot be asserted until the server side lands"
+ )
+ assert _poll(lambda: pending() == 0 and len(stack.headroom.recorded_outcomes) >= 1), (
+ f"relay did not land: pending={pending()} outcomes={len(stack.headroom.recorded_outcomes)}\n"
+ f"{kong_logs()}"
+ )
+ outcome = stack.headroom.recorded_outcomes[-1]
+ assert getattr(outcome, "output_tokens", None) == 7
+
+
+# --------------------------------------------------------------------------- #
+# (b) loop path #
+# --------------------------------------------------------------------------- #
+
+
+def test_loop_path_redrives_and_hides_search_tools(stack: Stack) -> None:
+ """Non-streaming turn with deferrable tools: Headroom asks for a redrive,
+ the plugin runs it in `access`, the client sees only the final answer."""
+ if register_redrive_hook is None:
+ pytest.skip("tests/gateway/redrive_hook_ext.py not present; no re-driving hook to arm")
+ stack.provider.reset()
+ stack.provider.script(
+ [
+ openai_tool_call_response("search_tools", {"query": "deferred"}),
+ openai_text_response("final answer", usage=openai_usage(30, 5, cached=0)),
+ ]
+ )
+ tools = openai_tools()
+ body = {
+ "model": "gpt-4o",
+ "messages": [{"role": "user", "content": "use a deferred tool please"}],
+ "tools": tools,
+ }
+ resp = stack.chat(body, session="kong-e2e-loop")
+ assert resp.status_code == 200, f"{resp.text}\n{kong_logs()}"
+ final = resp.json()
+ assert "search_tools" not in resp.text, f"client saw the search_tools call:\n{resp.text}"
+ assert final["choices"][0]["message"]["content"] == "final answer"
+
+ calls = stack.provider.calls
+ assert len(calls) == 2, f"provider saw {len(calls)} calls\n{kong_logs()}"
+ first_names = tool_names(calls[0].tools)
+ assert "search_tools" in first_names
+ assert not any(n.startswith("deferred_") for n in first_names)
+ second_names = tool_names(calls[1].tools)
+ assert any(n.startswith("deferred_") for n in second_names), second_names
+ # Both provider calls carried the client's auth on the loop path.
+ assert all(c.headers.get("authorization") == "Bearer sk-test" for c in calls)
+ assert _poll(lambda: stack.headroom.pending_turns() in (0, None)), "turn not drained"
+
+
+# --------------------------------------------------------------------------- #
+# (c) fail-open #
+# --------------------------------------------------------------------------- #
+
+
+def test_fail_open_when_headroom_is_down(stack: Stack) -> None:
+ stack.provider.reset()
+ stack.provider.script([openai_text_response("still here")])
+ body = {"model": "gpt-4o", "messages": big_tool_history(n_items=20)}
+
+ stack.headroom.stop()
+ _wait_port_closed(HEADROOM_PORT)
+ try:
+ resp = stack.chat(body, session="kong-e2e-down")
+ finally:
+ # Order-independent: leave the stack as we found it.
+ stack.headroom = HeadroomServer(HEADROOM_PORT)
+ stack.headroom.start()
+
+ assert resp.status_code == 200, f"{resp.text}\n{kong_logs()}"
+ assert resp.json()["choices"][0]["message"]["content"] == "still here"
+ assert len(stack.provider.calls) == 1
+ # Original body, untouched.
+ assert stack.provider.calls[0].messages == body["messages"]
+ assert "gateway" not in stack.provider.calls[0].body
+
+
+# --------------------------------------------------------------------------- #
+# (d) header contract: native tool-search deferral + merged anthropic-beta #
+# --------------------------------------------------------------------------- #
+
+ADVANCED_TOOL_USE_TOKEN = "advanced-tool-use"
+CLIENT_BETA = "some-other-beta"
+
+
+def anthropic_tool_set() -> list[dict[str, Any]]:
+ """Thirteen Anthropic-shaped tools: three core coding tools that must stay
+ resident plus ten integration tools Headroom is expected to defer."""
+ schema = {
+ "type": "object",
+ "properties": {"query": {"type": "string", "description": "What to do. " * 8}},
+ "required": ["query"],
+ }
+ names = [
+ "Bash",
+ "Read",
+ "Edit",
+ "jira_create_issue",
+ "jira_search_issues",
+ "slack_post_message",
+ "slack_list_channels",
+ "linear_create_ticket",
+ "sentry_list_events",
+ "notion_search_pages",
+ "snowflake_run_query",
+ "github_open_pull_request",
+ "pagerduty_trigger_incident",
+ ]
+ return [{"name": n, "description": f"{n} tool.", "input_schema": schema} for n in names]
+
+
+def _compress_contract_probe(body: dict[str, Any]) -> dict[str, Any]:
+ """Ask Headroom directly what its /v1/compress answer looks like for this
+ body, offering no capabilities so no pending turn is registered. Used only
+ to tell "core not landed" apart from "plugin broke"."""
+ payload = {
+ **body,
+ "config": {"session_id": "kong-e2e-anthropic-probe"},
+ "gateway": {
+ "can_redrive": False,
+ "can_relay_response": False,
+ "session_affinity": True,
+ "plugin_version": "e2e-probe",
+ "request_headers": {"anthropic-beta": CLIENT_BETA},
+ },
+ }
+ resp = httpx.post(f"http://127.0.0.1:{HEADROOM_PORT}/v1/compress", json=payload, timeout=60)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert isinstance(data, dict)
+ return data
+
+
+def test_anthropic_native_deferral_sets_merged_beta_header(stack: Stack) -> None:
+ """Anthropic-shaped request with 13 tools and a client ``anthropic-beta``:
+ the provider must see the non-core tools deferred behind a regex tool-search
+ tool, and an ``anthropic-beta`` header carrying both the client's beta and
+ Anthropic's ``advanced-tool-use`` token (the plugin sets what Headroom
+ returned in ``headers``)."""
+ stack.provider.reset()
+ stack.headroom.recorded_outcomes.clear()
+ stack.provider.script([anthropic_text_response("deferred answer")])
+ # Deferral is a turn hook's job on this path: the tool-search extension's
+ # native tier when it is importable here, else the reference hook. Headroom
+ # runs in-process, so registering here is what an installed extension does.
+ from headroom.proxy.turn_hooks import register_turn_hook
+
+ try:
+ from headroom_tool_search.native import NativeDeferralHook
+
+ register_turn_hook(NativeDeferralHook(None))
+ except Exception:
+ from tests.gateway.deferral_hook import DeferralHook
+
+ register_turn_hook(DeferralHook())
+ body = {
+ "model": "claude-sonnet-4-5",
+ "max_tokens": 64,
+ "messages": [{"role": "user", "content": "open a jira ticket for the flaky build"}],
+ "tools": anthropic_tool_set(),
+ }
+
+ resp = stack.messages(
+ body, session="kong-e2e-anthropic", extra_headers={"anthropic-beta": CLIENT_BETA}
+ )
+ assert resp.status_code == 200, f"{resp.text}\n{kong_logs()}"
+ assert resp.json()["content"][0]["text"] == "deferred answer"
+
+ calls = stack.provider.calls
+ assert len(calls) == 1, f"provider saw {len(calls)} calls\n{kong_logs()}"
+ received = calls[0]
+ assert received.path.endswith("/v1/messages")
+ assert "gateway" not in received.body and "config" not in received.body
+ # The plugin's own header handling, independent of the contract addition:
+ # the client's auth passthrough must not be disturbed by header merging.
+ assert received.headers.get("x-api-key") == "sk-ant-test"
+
+ probe = _compress_contract_probe(body)
+ if "headers" not in probe:
+ pytest.xfail(
+ "core pending: /v1/compress answered without `headers` "
+ f"(keys: {sorted(probe)}); native deferral + anthropic-beta merge not landed"
+ )
+
+ # (a) native tool-search deferral reached the provider.
+ tools = received.tools
+ names = tool_names(tools)
+ assert any(n.startswith("tool_search_tool_regex") for n in names), names
+ deferred = {t["name"] for t in tools if isinstance(t, dict) and t.get("defer_loading") is True}
+ resident = {
+ t["name"]
+ for t in tools
+ if isinstance(t, dict) and t.get("name") and not t.get("defer_loading")
+ }
+ assert "jira_create_issue" in deferred and "slack_post_message" in deferred, tools
+ assert {"Bash", "Read", "Edit"} <= resident, tools
+ assert not any(n.startswith("tool_search_tool_regex") for n in deferred)
+
+ # (b) the merged anthropic-beta header: client beta kept, Anthropic's token added.
+ beta = received.headers.get("anthropic-beta", "")
+ tokens = [t.strip() for t in beta.split(",") if t.strip()]
+ assert CLIENT_BETA in tokens, f"client beta dropped: {beta!r}\n{kong_logs()}"
+ assert any(t.startswith(ADVANCED_TOOL_USE_TOKEN) for t in tokens), (
+ f"advanced-tool-use missing from {beta!r}; headroom returned {probe.get('headers')!r}\n"
+ f"{kong_logs()}"
+ )
+ assert _poll(lambda: stack.headroom.pending_turns() in (0, None)), "turn not drained"
diff --git a/tests/gateway/test_native_deferral.py b/tests/gateway/test_native_deferral.py
new file mode 100644
index 000000000..6f1b453ca
--- /dev/null
+++ b/tests/gateway/test_native_deferral.py
@@ -0,0 +1,726 @@
+"""Tool-search deferral on the gateway contract is a turn hook's job.
+
+OSS core does not defer tool schemas on ``POST /v1/compress``; the licensed
+tool-search extension's native tier does, through the turn-hook contract. These
+tests use the reference hook in ``tests/gateway/deferral_hook.py`` (the same
+primitives, tags and header seam the extension uses) and protect what CORE
+promises to such a hook:
+
+* I-PLAIN - with no hook registered, 12+ Anthropic tools pass through
+ compacted, ``headers`` is ``{}`` and no deferral is named.
+* I-CARRY - a hook's deferral reaches ``body.tools``; the hook's
+ ``provider_headers`` become the response's ``headers`` with the
+ client's ``anthropic-beta`` tokens first and Headroom's
+ appended; the ``tool_search_deferred_*`` tags name the
+ ``tool_search:native_deferral:<n>tools:<n>tok`` transform and
+ reach the outcome, the ledger and ``metrics.record_request``.
+* I-SEAM - only allow-listed header names are honoured; a hook that is not
+ stream-safe is skipped when the gateway cannot re-drive; hooks
+ run by ``priority`` so a router that changes the model runs
+ before the deferral gate.
+* I-GATES - the OSS gate helpers the hook applies: fewer than 12 tools, a
+ client already searching, ``HEADROOM_TOOL_SEARCH=0``,
+ Bedrock/Vertex ids, OpenAI models, OpenAI-shaped tools.
+* I-STABLE - identical bytes and header across three session turns.
+* I-LEGACY / I-FAILOPEN - no ``gateway`` block -> no ``headers`` key; fail-open
+ answers carry ``headers: {}`` even with the hook registered.
+* I-REPAIR - tool-search history repair stays in core (in-place placeholder,
+ chat-path parity).
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+import pytest
+
+from headroom.proxy.savings_attribution import from_tags
+from tests.gateway.conftest import compress
+from tests.gateway.deferral_hook import (
+ BETA_TOKEN,
+ BufferedDeferralHook,
+ DeferralHook,
+ ModelRouterHook,
+ register,
+)
+from tests.gateway.fake_provider import anthropic_usage
+from tests.gateway.samples import (
+ SYSTEM_PROMPT,
+ anthropic_tool_history,
+ anthropic_tools,
+ big_tool_history,
+ canonical,
+ openai_tools,
+ tool_names,
+)
+
+CLAUDE = "claude-sonnet-4-5"
+SEARCH_TYPE_PREFIX = "tool_search_tool_regex"
+CLIENT_BETA = "context-1m-2025-08-07"
+DEFERRAL_LABEL = re.compile(r"^tool_search:native_deferral:(\d+)tools:(\d+)tok$")
+OLD_CORE_LABEL = "router:tool_search_deferral"
+CORE_NAMES = ("Bash", "Read")
+
+
+def deferral_hook() -> DeferralHook:
+ return register()
+
+
+def _schema(prefix: str) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": f"The {prefix} query."},
+ },
+ "required": ["query"],
+ }
+
+
+def _many_anthropic_tools(n_non_core: int = 12) -> list[dict[str, Any]]:
+ """Two core (resident) tools plus ``n_non_core`` deferrable MCP-style ones."""
+ tools: list[dict[str, Any]] = [
+ {"name": name, "description": f"{name} tool.", "input_schema": _schema(name)}
+ for name in CORE_NAMES
+ ]
+ tools.extend(
+ {
+ "name": f"mcp__srv__tool_{i:02d}",
+ "description": f"MCP tool number {i} with a description long enough to count.",
+ "input_schema": _schema(f"tool_{i}"),
+ }
+ for i in range(n_non_core)
+ )
+ return tools
+
+
+def _many_openai_tools(n: int = 14) -> list[dict[str, Any]]:
+ return [
+ {
+ "type": "function",
+ "function": {
+ "name": f"fn_{i:02d}",
+ "description": f"Function number {i}.",
+ "parameters": _schema(f"fn_{i}"),
+ },
+ }
+ for i in range(n)
+ ]
+
+
+def _body(
+ *,
+ model: str = CLAUDE,
+ tools: Any = None,
+ messages: list[dict[str, Any]] | None = None,
+ gateway: dict[str, Any] | None = None,
+ **extra: Any,
+) -> dict[str, Any]:
+ out: dict[str, Any] = {
+ "model": model,
+ "messages": messages if messages is not None else anthropic_tool_history(),
+ "system": SYSTEM_PROMPT,
+ "max_tokens": 64,
+ }
+ if tools is not None:
+ out["tools"] = tools
+ if gateway is not None:
+ out["gateway"] = gateway
+ out.update(extra)
+ return out
+
+
+def _search_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ return [t for t in tools if str(t.get("type", "")).startswith(SEARCH_TYPE_PREFIX)]
+
+
+def _deferred(tools: list[dict[str, Any]]) -> list[str]:
+ return [str(t["name"]) for t in tools if t.get("defer_loading")]
+
+
+def _deferral_labels(data: dict[str, Any]) -> list[str]:
+ return [t for t in data["transforms_applied"] if DEFERRAL_LABEL.match(t)]
+
+
+def _assert_untouched(data: dict[str, Any], sent_tools: list[dict[str, Any]]) -> None:
+ assert canonical(tool_names(data["body"]["tools"])) == canonical(tool_names(sent_tools))
+ assert not _search_tools(data["body"]["tools"])
+ assert not _deferred(data["body"]["tools"])
+ assert data["headers"] == {}
+ assert _deferral_labels(data) == []
+ assert not any(t.startswith(OLD_CORE_LABEL) for t in data["transforms_applied"])
+
+
+def _assert_deferred(data: dict[str, Any], sent_tools: list[dict[str, Any]]) -> int:
+ tools = data["body"]["tools"]
+ search = _search_tools(tools)
+ assert len(search) == 1
+ assert search[0]["name"] == "tool_search_tool_regex"
+ assert not search[0].get("defer_loading")
+ assert set(_deferred(tools)) == {t["name"] for t in sent_tools if t["name"] not in CORE_NAMES}
+ resident = [t for t in tools if not t.get("type") and not t.get("defer_loading")]
+ assert [t["name"] for t in resident] == list(CORE_NAMES)
+ assert set(tool_names(tools)) == set(tool_names(sent_tools)) | {"tool_search_tool_regex"}
+ labels = _deferral_labels(data)
+ assert len(labels) == 1, data["transforms_applied"]
+ n_tools, n_tok = (int(x) for x in DEFERRAL_LABEL.match(labels[0]).groups())
+ assert n_tools == len(_deferred(tools))
+ assert n_tok > 0
+ return n_tok
+
+
+# --------------------------------------------------------------------------- #
+# I-PLAIN: OSS core alone never defers on this path #
+# --------------------------------------------------------------------------- #
+
+
+def test_no_hook_leaves_tools_untouched_and_headers_empty(headroom_client, outcome_spy) -> None:
+ outcomes = outcome_spy(headroom_client)
+ sent = _body(
+ tools=_many_anthropic_tools(),
+ gateway={"request_headers": {"anthropic-beta": CLIENT_BETA}},
+ )
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ _assert_untouched(data, sent["tools"])
+ # The client's beta is not echoed back either: nothing asked for a header.
+ assert data["headers"] == {}
+ assert "tool_search_deferred_tokens" not in outcomes[0].tags
+
+
+def test_no_hook_with_client_already_searching_is_passed_through(headroom_client) -> None:
+ tools = [{"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}]
+ tools += _many_anthropic_tools()
+ sent = _body(tools=tools, gateway={})
+ data = compress(headroom_client, sent).json()
+ assert canonical(data["body"]["tools"]) == canonical(sent["tools"])
+ assert data["headers"] == {}
+
+
+# --------------------------------------------------------------------------- #
+# I-CARRY: a hook's deferral, header and savings reach the gateway #
+# --------------------------------------------------------------------------- #
+
+
+def test_hook_deferral_reaches_body_headers_and_outcome(
+ headroom_client, outcome_spy, deferral_hook
+) -> None:
+ outcomes = outcome_spy(headroom_client)
+ sent = _body(
+ tools=_many_anthropic_tools(),
+ gateway={"request_headers": {"anthropic-beta": CLIENT_BETA}},
+ )
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ n_tok = _assert_deferred(data, sent["tools"])
+ assert deferral_hook.applied == 1
+
+ # Client tokens first, then the hook's, deduplicated.
+ assert data["headers"] == {"anthropic-beta": f"{CLIENT_BETA},{BETA_TOKEN}"}
+
+ assert len(outcomes) == 1
+ tags = outcomes[0].tags
+ assert tags["tool_search_deferred_tools"] == 12
+ assert tags["tool_search_deferred_tokens"] == n_tok
+ ledger = [item for item in from_tags(tags) if item["source"] == "tool_search"]
+ assert ledger and ledger[0]["tokens"] == n_tok
+ assert _deferral_labels(data)[0] in outcomes[0].transforms_applied
+ # Deferral does not shrink the tools array, so the runner's own fold must
+ # not double-count it.
+ assert "turn_hook_tools_saved_tokens" not in tags
+
+
+def test_hook_header_without_client_value_is_just_the_hooks(headroom_client, deferral_hook) -> None:
+ data = compress(headroom_client, _body(tools=_many_anthropic_tools(), gateway={})).json()
+ assert data["headers"] == {"anthropic-beta": BETA_TOKEN}
+
+
+def test_client_beta_already_carrying_token_is_not_duplicated(
+ headroom_client, deferral_hook
+) -> None:
+ sent = _body(
+ tools=_many_anthropic_tools(),
+ gateway={"request_headers": {"Anthropic-Beta": f"{BETA_TOKEN},{CLIENT_BETA}"}},
+ )
+ data = compress(headroom_client, sent).json()
+ assert data["headers"] == {"anthropic-beta": f"{BETA_TOKEN},{CLIENT_BETA}"}
+
+
+def test_deferral_composes_with_compaction_and_ccr_tool(headroom_client, deferral_hook) -> None:
+ """The hook runs after compaction and before CCR tool injection
+ (``headroom_retrieve`` stays resident so the model can call it)."""
+ sent = _body(
+ tools=_many_anthropic_tools(),
+ config={"mode": "ccr"},
+ gateway={"can_redrive": True, "session_affinity": True},
+ )
+ data = compress(headroom_client, sent).json()
+ tools = data["body"]["tools"]
+ assert _search_tools(tools)
+ retrieve = [t for t in tools if t.get("name") == "headroom_retrieve"]
+ if retrieve: # only injected when markers were inserted
+ assert not retrieve[0].get("defer_loading")
+ assert "ccr_tool_injected" in data["transforms_applied"]
+ assert data["headers"]["anthropic-beta"] == BETA_TOKEN
+
+
+# --------------------------------------------------------------------------- #
+# I-SEAM: allowlist, stream-safety, priority #
+# --------------------------------------------------------------------------- #
+
+
+def test_hook_requesting_disallowed_headers_gets_only_the_allowlisted_one(headroom_client) -> None:
+ register(extra_headers={"Authorization": "Bearer hook-secret", "x-api-key": "sk-hook", "": "x"})
+ sent = _body(tools=_many_anthropic_tools(), gateway={})
+ data = compress(headroom_client, sent).json()
+ assert data["headers"] == {"anthropic-beta": BETA_TOKEN}
+ assert "hook-secret" not in canonical(data)
+
+
+def test_buffered_hook_is_skipped_when_the_gateway_cannot_redrive(headroom_client) -> None:
+ """A hook that is not stream-safe never runs on a turn the gateway cannot
+ re-drive — which is every streamed Claude Code turn. The native tier must
+ therefore be stream-safe; this pins the rule that makes that necessary."""
+ hook = register(BufferedDeferralHook())
+ sent = _body(tools=_many_anthropic_tools(), gateway={"can_redrive": False})
+ data = compress(headroom_client, sent).json()
+ _assert_untouched(data, sent["tools"])
+ assert hook.request_calls == 0
+
+ sent = _body(
+ tools=_many_anthropic_tools(),
+ config={"session_id": "buffered-ok"},
+ gateway={"can_redrive": True, "session_affinity": True},
+ )
+ data = compress(headroom_client, sent).json()
+ _assert_deferred(data, sent["tools"])
+ assert hook.request_calls == 1
+
+
+def test_router_with_lower_priority_runs_before_the_deferral_gate(headroom_client) -> None:
+ """Registered AFTER the deferral hook, a priority-10 router still runs
+ first, so the first-party gate sees the routed Bedrock id and declines."""
+ register()
+ register(ModelRouterHook("anthropic.claude-sonnet-4-5-v1:0", priority=10))
+ sent = _body(tools=_many_anthropic_tools(), gateway={})
+ data = compress(headroom_client, sent).json()
+ _assert_untouched(data, sent["tools"])
+
+
+def test_router_with_higher_priority_runs_after_and_the_deferral_stands(headroom_client) -> None:
+ register()
+ register(ModelRouterHook("anthropic.claude-sonnet-4-5-v1:0", priority=300))
+ sent = _body(tools=_many_anthropic_tools(), gateway={})
+ data = compress(headroom_client, sent).json()
+ _assert_deferred(data, sent["tools"])
+
+
+# --------------------------------------------------------------------------- #
+# I-GATES: the OSS gate helpers, as the hook applies them #
+# --------------------------------------------------------------------------- #
+
+
+def test_fewer_than_twelve_tools_untouched(headroom_client, deferral_hook) -> None:
+ sent = _body(tools=_many_anthropic_tools(9), gateway={}) # 11 in total
+ data = compress(headroom_client, sent).json()
+ _assert_untouched(data, sent["tools"])
+
+
+def test_three_sample_tools_untouched(headroom_client, deferral_hook) -> None:
+ sent = _body(tools=anthropic_tools(), gateway={})
+ data = compress(headroom_client, sent).json()
+ _assert_untouched(data, sent["tools"])
+
+
+def test_client_already_using_tool_search_untouched(headroom_client, deferral_hook) -> None:
+ tools = [{"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}]
+ tools += _many_anthropic_tools()
+ sent = _body(tools=tools, gateway={"request_headers": {"anthropic-beta": CLIENT_BETA}})
+ data = compress(headroom_client, sent).json()
+ assert canonical(data["body"]["tools"]) == canonical(sent["tools"])
+ assert data["headers"] == {}
+ assert _deferral_labels(data) == []
+
+
+def test_env_flag_off_untouched(headroom_client, deferral_hook, monkeypatch) -> None:
+ monkeypatch.setenv("HEADROOM_TOOL_SEARCH", "0")
+ sent = _body(tools=_many_anthropic_tools(), gateway={})
+ data = compress(headroom_client, sent).json()
+ _assert_untouched(data, sent["tools"])
+
+
+ "model",
+ [
+ "bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
+ "anthropic.claude-3-5-sonnet-20241022-v2:0",
+ "us.anthropic.claude-sonnet-4-20250514-v1:0",
+ "vertex_ai/claude-sonnet-4@20250514",
+ "claude-sonnet-4@20250514",
+ ],
+)
+def test_bedrock_and_vertex_model_ids_untouched(headroom_client, deferral_hook, model: str) -> None:
+ sent = _body(model=model, tools=_many_anthropic_tools(), gateway={})
+ data = compress(headroom_client, sent).json()
+ assert data["route"]["provider"] == "anthropic"
+ _assert_untouched(data, sent["tools"])
+
+
+def test_litellm_anthropic_prefix_is_first_party(headroom_client, deferral_hook) -> None:
+ sent = _body(model="anthropic/claude-sonnet-4-5", tools=_many_anthropic_tools(), gateway={})
+ data = compress(headroom_client, sent).json()
+ assert _search_tools(data["body"]["tools"])
+ assert data["headers"]["anthropic-beta"] == BETA_TOKEN
+
+
+def test_openai_model_untouched(headroom_client, deferral_hook) -> None:
+ sent = {
+ "model": "gpt-4o",
+ "messages": big_tool_history(),
+ "tools": _many_openai_tools(),
+ "gateway": {"request_headers": {"anthropic-beta": CLIENT_BETA}},
+ }
+ data = compress(headroom_client, sent).json()
+ _assert_untouched(data, sent["tools"])
+
+
+def test_openai_shaped_tools_on_claude_model_untouched(headroom_client, deferral_hook) -> None:
+ sent = _body(tools=_many_openai_tools(), messages=big_tool_history(), gateway={})
+ data = compress(headroom_client, sent).json()
+ assert data["route"]["provider"] == "anthropic"
+ _assert_untouched(data, sent["tools"])
+
+
+def test_mixed_shape_tools_untouched(headroom_client, deferral_hook) -> None:
+ tools = _many_anthropic_tools() + openai_tools()[:1]
+ sent = _body(tools=tools, gateway={})
+ data = compress(headroom_client, sent).json()
+ assert not _search_tools(data["body"]["tools"])
+ assert data["headers"] == {}
+
+
+# --------------------------------------------------------------------------- #
+# gateway.request_headers validation #
+# --------------------------------------------------------------------------- #
+
+
+ "request_headers",
+ [[], "anthropic-beta: x", 1, {"anthropic-beta": 1}, {"anthropic-beta": ["a"]}],
+ ids=["list", "string", "int", "int-value", "list-value"],
+)
+def test_invalid_request_headers_is_400(headroom_client, request_headers: Any) -> None:
+ sent = _body(tools=_many_anthropic_tools(), gateway={"request_headers": request_headers})
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 400, resp.text
+ assert resp.json()["error"]["type"] == "invalid_request"
+
+
+def test_other_request_headers_are_ignored(headroom_client, deferral_hook) -> None:
+ sent = _body(
+ tools=_many_anthropic_tools(),
+ gateway={
+ "request_headers": {
+ "authorization": "Bearer secret",
+ "x-api-key": "sk-ant-secret",
+ "anthropic-beta": None,
+ }
+ },
+ )
+ data = compress(headroom_client, sent).json()
+ assert data["headers"] == {"anthropic-beta": BETA_TOKEN}
+ assert "authorization" not in canonical(data["headers"])
+ assert "secret" not in canonical(data)
+
+
+# --------------------------------------------------------------------------- #
+# I-STABLE / I-LEGACY / I-FAILOPEN #
+# --------------------------------------------------------------------------- #
+
+
+def test_byte_stable_over_three_session_turns(headroom_client, deferral_hook) -> None:
+ history = anthropic_tool_history()
+ tools = _many_anthropic_tools()
+ seen_tools: list[str] = []
+ seen_headers: list[str] = []
+ seen_labels: list[list[str]] = []
+ for turn in range(3):
+ messages = history + [
+ m
+ for i in range(turn)
+ for m in (
+ {"role": "assistant", "content": f"answer {i}"},
+ {"role": "user", "content": f"follow-up {i}"},
+ )
+ ]
+ sent = _body(
+ tools=tools,
+ messages=messages,
+ config={"session_id": "gw-defer-stable"},
+ gateway={
+ "can_relay_response": True,
+ "request_headers": {"anthropic-beta": CLIENT_BETA},
+ },
+ )
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ seen_tools.append(canonical(data["body"]["tools"]))
+ seen_headers.append(canonical(data["headers"]))
+ seen_labels.append(_deferral_labels(data))
+ assert len(set(seen_tools)) == 1
+ assert len(set(seen_headers)) == 1
+ assert seen_labels[0] and seen_labels.count(seen_labels[0]) == 3
+
+
+def test_stateless_calls_are_byte_stable(headroom_client, deferral_hook) -> None:
+ sent = _body(tools=_many_anthropic_tools(), gateway={})
+ first = compress(headroom_client, sent).json()
+ second = compress(headroom_client, sent).json()
+ assert canonical(first["body"]["tools"]) == canonical(second["body"]["tools"])
+ assert first["headers"] == second["headers"]
+
+
+def test_legacy_mode_untouched(headroom_client, outcome_spy, deferral_hook) -> None:
+ outcomes = outcome_spy(headroom_client)
+ sent = _body(tools=_many_anthropic_tools())
+ resp = compress(headroom_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert "headers" not in data and "body" not in data
+ assert _deferral_labels(data) == []
+ assert "tool_search_deferred_tokens" not in outcomes[0].tags
+
+
+def test_bypass_header_fails_open_with_empty_headers(headroom_client, deferral_hook) -> None:
+ sent = _body(tools=_many_anthropic_tools(), gateway={})
+ data = compress(headroom_client, sent, headers={"x-headroom-bypass": "true"}).json()
+ assert data["headers"] == {}
+ assert canonical(data["body"]["tools"]) == canonical(sent["tools"])
+
+
+def test_timeout_fails_open_with_empty_headers(headroom_client, deferral_hook, monkeypatch) -> None:
+ from unittest.mock import AsyncMock
+
+ proxy = headroom_client.app.state.proxy
+ monkeypatch.setattr(proxy, "_run_compression_in_executor", AsyncMock(side_effect=TimeoutError))
+ sent = _body(tools=_many_anthropic_tools(), gateway={})
+ data = compress(headroom_client, sent).json()
+ assert data["compression_skipped"] is True
+ assert data["headers"] == {}
+ assert canonical(data["body"]["tools"]) == canonical(sent["tools"])
+
+
+def test_empty_messages_fails_open_with_empty_headers(headroom_client, deferral_hook) -> None:
+ sent = _body(tools=_many_anthropic_tools(), messages=[], gateway={})
+ data = compress(headroom_client, sent).json()
+ assert data["headers"] == {}
+
+
+# --------------------------------------------------------------------------- #
+# I-REPAIR: history repair stays in core #
+# --------------------------------------------------------------------------- #
+
+
+def _history_with_search_blocks(referenced: str) -> list[dict[str, Any]]:
+ return anthropic_tool_history() + [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "server_tool_use",
+ "id": "srvtoolu_1",
+ "name": "tool_search_tool_regex",
+ "input": {"pattern": "tool_03"},
+ },
+ {
+ "type": "tool_search_tool_result",
+ "tool_use_id": "srvtoolu_1",
+ "content": {
+ "tool_references": [{"type": "tool_reference", "tool_name": referenced}]
+ },
+ },
+ {"type": "text", "text": "Found it."},
+ ],
+ },
+ {"role": "user", "content": "Go on."},
+ ]
+
+
+def test_history_repair_neutralises_unsupportable_search_blocks_in_place(headroom_client) -> None:
+ """No hook, three tools, a transcript with last turn's tool-search blocks:
+ core repairs them exactly as the chat path does (#3457): each unsupported
+ ``server_tool_use`` / ``tool_search_tool_result`` block is replaced IN
+ PLACE by the constant, inert placeholder text block, so block coordinates
+ (signed thinking blocks) survive and the repaired prefix is byte-stable.
+ No search block reaches the provider, the client's own text is untouched,
+ and the repair is named. A client that defers on its own gets this without
+ any extension."""
+ from headroom.proxy.helpers import strip_unsupported_tool_search_blocks
+
+ history = _history_with_search_blocks("mcp__srv__tool_03")
+ sent = _body(tools=anthropic_tools(), messages=history, gateway={})
+ data = compress(headroom_client, sent).json()
+ assistant = data["body"]["messages"][-2]
+
+ # Chat-path parity: the gateway path emits the helper's own output.
+ expected, stripped = strip_unsupported_tool_search_blocks(
+ _history_with_search_blocks("mcp__srv__tool_03"), anthropic_tools()
+ )
+ assert stripped == 2
+ assert canonical(assistant) == canonical(expected[-2])
+
+ # The invariant the provider cares about: no tool-search block survives,
+ # and what replaced them is text that names nothing a validator could
+ # resolve (constant placeholder, not the original pattern or reference).
+ types = [b["type"] for b in assistant["content"]]
+ assert types == ["text", "text", "text"]
+ assert not any(t in ("server_tool_use", "tool_search_tool_result") for t in types)
+ placeholders = [b["text"] for b in assistant["content"][:2]]
+ assert len(set(placeholders)) == 1 and "tool search omitted" in placeholders[0]
+ assert "tool_03" not in placeholders[0] and "srvtoolu" not in canonical(assistant)
+ assert assistant["content"][2] == {"type": "text", "text": "Found it."}
+
+ assert "router:tool_search_repair:2blocks" in data["transforms_applied"]
+ assert data["messages"] == data["body"]["messages"]
+
+
+def test_history_repair_keeps_blocks_the_deferred_tools_support(
+ headroom_client, deferral_hook
+) -> None:
+ sent = _body(
+ tools=_many_anthropic_tools(),
+ messages=_history_with_search_blocks("mcp__srv__tool_03"),
+ gateway={},
+ )
+ data = compress(headroom_client, sent).json()
+ assistant = data["body"]["messages"][-2]
+ assert [b["type"] for b in assistant["content"]] == [
+ "server_tool_use",
+ "tool_search_tool_result",
+ "text",
+ ]
+ assert not any(t.startswith("router:tool_search_repair") for t in data["transforms_applied"])
+
+
+def test_history_repair_is_anthropic_only(headroom_client) -> None:
+ sent = {
+ "model": "gpt-4o",
+ "messages": _history_with_search_blocks("mcp__srv__tool_03"),
+ "tools": openai_tools(),
+ "gateway": {},
+ }
+ data = compress(headroom_client, sent).json()
+ assert [b["type"] for b in data["body"]["messages"][-2]["content"]] == [
+ "server_tool_use",
+ "tool_search_tool_result",
+ "text",
+ ]
+
+
+# --------------------------------------------------------------------------- #
+# I-CARRY, both halves: the Kong-shaped run #
+# --------------------------------------------------------------------------- #
+
+
+def test_kong_shaped_turn_credits_hook_deferral_through_the_response_half(
+ headroom_client, deferral_hook, monkeypatch
+) -> None:
+ """Request half (session + relay owed) -> response half with Anthropic
+ usage -> the deferred outcome reaches ``metrics.record_request`` with the
+ hook's deferred schema tokens on ``tool_search_saved`` (what ``/stats``
+ reports as ``tool_schema_tokens_saved``)."""
+ proxy = headroom_client.app.state.proxy
+ recorded: list[dict[str, Any]] = []
+ original = proxy.metrics.record_request
+
+ async def _spy(*args: Any, **kwargs: Any) -> Any:
+ recorded.append(kwargs)
+ return await original(*args, **kwargs)
+
+ monkeypatch.setattr(proxy.metrics, "record_request", _spy)
+
+ sent = _body(
+ tools=_many_anthropic_tools(),
+ config={"session_id": "kong-defer"},
+ gateway={
+ "can_redrive": False,
+ "can_relay_response": True,
+ "session_affinity": True,
+ "plugin_version": "kong-headroom/0.1.0",
+ "request_headers": {"anthropic-beta": CLIENT_BETA},
+ },
+ )
+ half1 = headroom_client.post("/v1/compress", json=sent)
+ assert half1.status_code == 200, half1.text
+ data = half1.json()
+ assert data["obligations"] == ["relay_usage"]
+ assert data["headers"]["anthropic-beta"] == f"{CLIENT_BETA},{BETA_TOKEN}"
+ n_tok = _assert_deferred(data, sent["tools"])
+ assert recorded == [] # outcome deferred until the response half
+
+ half2 = headroom_client.post(
+ "/v1/compress/response",
+ json={
+ "turn_id": data["turn_id"],
+ "status": 200,
+ "latency_ms": 12.5,
+ "usage": anthropic_usage(1200, 40, cache_read=1000, cache_write=0),
+ },
+ )
+ assert half2.status_code == 200, half2.text
+ assert half2.json()["action"] == "done"
+ assert len(recorded) == 1
+ assert recorded[0]["tool_search_saved"] == n_tok
+ assert recorded[0]["output_tokens"] == 40
+ assert proxy.metrics.tool_search_saved_total == n_tok
+
+
+# --------------------------------------------------------------------------- #
+# Parity with the extension's native tier, when it is installed #
+# --------------------------------------------------------------------------- #
+
+
+def test_extension_native_tier_matches_the_reference_hook(headroom_client) -> None:
+ """With headroom-tool-search installed, its native tier must produce the
+ same tools bytes and header as the reference hook on Claude Code's tool
+ list. Skipped where the extension is not importable."""
+ native = pytest.importorskip("headroom_tool_search.native")
+ try:
+ hook = native.NativeDeferralHook(None)
+ except Exception as exc: # pragma: no cover - extension-side construction
+ pytest.skip(f"NativeDeferralHook not constructible here: {exc}")
+ claude_code_tools = [
+ {"name": name, "description": f"{name} tool.", "input_schema": _schema(name)}
+ for name in (
+ "Task", "Bash", "Glob", "Grep", "ExitPlanMode", "Read", "Edit", "Write",
+ "NotebookEdit", "WebFetch", "TodoWrite", "WebSearch", "BashOutput",
+ "KillShell", "AskUserQuestion", "Skill", "SlashCommand", "EnterPlanMode",
+ "ToolSearch", "CronCreate", "CronDelete", "CronList",
+ )
+ ] # fmt: skip
+ sent = _body(
+ tools=claude_code_tools, gateway={"request_headers": {"anthropic-beta": CLIENT_BETA}}
+ )
+
+ register()
+ reference = compress(headroom_client, sent).json()
+ from headroom.proxy.turn_hooks import clear_turn_hooks
+
+ clear_turn_hooks()
+ register(hook)
+ extension = compress(headroom_client, sent).json()
+
+ assert canonical(extension["body"]["tools"]) == canonical(reference["body"]["tools"])
+ assert extension["headers"] == reference["headers"]
+ assert _deferral_labels(extension) == _deferral_labels(reference)
+ # Chat-path parity: the same tools bytes core's own deferral would send.
+ from headroom.proxy.helpers import inject_tool_search_deferral
+
+ expected = inject_tool_search_deferral(claude_code_tools)
+ assert _deferred(extension["body"]["tools"]) == _deferred(expected)
+ assert "ToolSearch" not in _deferred(extension["body"]["tools"])
+ assert "Bash" not in _deferred(extension["body"]["tools"])
diff --git a/tests/gateway/test_output_steering.py b/tests/gateway/test_output_steering.py
new file mode 100644
index 000000000..852a66365
--- /dev/null
+++ b/tests/gateway/test_output_steering.py
@@ -0,0 +1,383 @@
+"""Output shaping (verbosity steering) on the gateway contract (request-only).
+
+Mirrors the chat handlers: gated by the ``proxy_output_shaper`` rollout
+(``HEADROOM_OUTPUT_SHAPER``), ``steering_allowed_for`` (off in
+``mode="cache"``), the conversation-stable ``HEADROOM_OUTPUT_HOLDOUT`` arm and
+``resolve_verbosity_level``. Invariants protected here:
+
+* I-SHAPE - enabled -> the steering block is appended to the Anthropic
+ ``system`` / the OpenAI chat system message of the provider
+ body, the (arm, stratum) label and the verbosity label are in
+ ``transforms_applied``, and top-level ``messages`` is still
+ ``body.messages``.
+* I-GATES - disabled (default), ``mode="cache"`` (label only, no block),
+ control arm (label only, no block), legacy mode (nothing).
+* I-STABLE - the block is byte-stable across three session turns and never
+ double-appended.
+* I-MEASURE - the label rides the DEFERRED outcome: the response half's
+ relayed ``output_tokens`` reach the outcome funnel with the
+ label, ``record_from_labels`` sees them, and with a baseline
+ for the stratum ``metrics.record_request`` is fed
+ ``output_tokens_saved > 0``.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from headroom.proxy.output_savings import SavingsRecorder
+from headroom.proxy.output_savings_policy import parse_stratum_label
+from headroom.proxy.output_verbosity_policy import STEERING_SENTINEL
+from tests.gateway.conftest import compress
+from tests.gateway.fake_provider import anthropic_usage, openai_usage
+from tests.gateway.samples import (
+ SYSTEM_PROMPT,
+ anthropic_tool_history,
+ anthropic_tools,
+ big_tool_history,
+ canonical,
+ openai_tools,
+)
+
+CLAUDE = "claude-sonnet-4-5"
+STRATUM_PREFIX = "output_shaper:stratum:"
+CONTROL_PREFIX = "output_shaper:control:"
+VERBOSITY_PREFIX = "output_shaper:verbosity:L"
+
+
+def _anthropic_body(**extra: Any) -> dict[str, Any]:
+ out: dict[str, Any] = {
+ "model": CLAUDE,
+ "messages": anthropic_tool_history(),
+ "system": SYSTEM_PROMPT,
+ "tools": anthropic_tools(),
+ "max_tokens": 64,
+ }
+ out.update(extra)
+ return out
+
+
+def _openai_body(*, with_system: bool = True, **extra: Any) -> dict[str, Any]:
+ messages = big_tool_history()
+ if with_system:
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}] + messages
+ out: dict[str, Any] = {"model": "gpt-4o", "messages": messages, "tools": openai_tools()}
+ out.update(extra)
+ return out
+
+
+def _shaper_labels(data: dict[str, Any]) -> list[str]:
+ return [t for t in data["transforms_applied"] if str(t).startswith("output_shaper:")]
+
+
+def _stratum_label(data: dict[str, Any]) -> str:
+ labels = [t for t in data["transforms_applied"] if parse_stratum_label(str(t))]
+ assert len(labels) == 1, data["transforms_applied"]
+ return labels[0]
+
+
+def _anthropic_steering_blocks(body: dict[str, Any]) -> list[str]:
+ system = body.get("system")
+ if not isinstance(system, list):
+ return []
+ return [
+ b["text"]
+ for b in system
+ if isinstance(b, dict) and str(b.get("text", "")).startswith(STEERING_SENTINEL)
+ ]
+
+
+def _openai_system_messages(body: dict[str, Any]) -> list[dict[str, Any]]:
+ return [m for m in body["messages"] if m.get("role") in ("system", "developer")]
+
+
+def shaped_client(make_headroom_client, monkeypatch):
+ """A proxy built with the shaper enabled (the rollout snapshot is taken at
+ config creation, so the env must be set BEFORE the app exists)."""
+ monkeypatch.setenv("HEADROOM_OUTPUT_SHAPER", "1")
+ monkeypatch.delenv("HEADROOM_OUTPUT_HOLDOUT", raising=False)
+ monkeypatch.delenv("HEADROOM_VERBOSITY_LEVEL", raising=False)
+ return make_headroom_client()
+
+
+# --------------------------------------------------------------------------- #
+# I-SHAPE #
+# --------------------------------------------------------------------------- #
+
+
+def test_anthropic_system_gets_steering_block(shaped_client) -> None:
+ sent = _anthropic_body(gateway={})
+ resp = compress(shaped_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ body = data["body"]
+ assert isinstance(body["system"], list)
+ assert body["system"][0] == {"type": "text", "text": SYSTEM_PROMPT}
+ blocks = _anthropic_steering_blocks(body)
+ assert len(blocks) == 1
+ label = _stratum_label(data)
+ assert label.startswith(STRATUM_PREFIX)
+ arm, key = parse_stratum_label(label)
+ assert arm == "treatment"
+ assert key.startswith("sonnet|") and key.endswith("|tools")
+ assert any(t.startswith(VERBOSITY_PREFIX) for t in data["transforms_applied"])
+ assert data["messages"] == body["messages"]
+ # Messages themselves are not where Anthropic steering goes.
+ assert canonical(body["messages"]) == canonical(data["messages"])
+
+
+def test_anthropic_without_system_field_gets_one(shaped_client) -> None:
+ sent = _anthropic_body(gateway={})
+ del sent["system"]
+ data = compress(shaped_client, sent).json()
+ blocks = _anthropic_steering_blocks(data["body"])
+ assert len(blocks) == 1 and len(data["body"]["system"]) == 1
+
+
+def test_openai_system_message_gets_steering_block(shaped_client) -> None:
+ sent = _openai_body(gateway={})
+ resp = compress(shaped_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ body = data["body"]
+ system = _openai_system_messages(body)
+ assert len(system) == 1
+ assert system[0]["content"].startswith(SYSTEM_PROMPT)
+ assert system[0]["content"].count(STEERING_SENTINEL) == 1
+ assert len(body["messages"]) == len(sent["messages"])
+ assert data["messages"] == body["messages"]
+ label = _stratum_label(data)
+ assert label.startswith(STRATUM_PREFIX)
+ assert parse_stratum_label(label)[1].startswith("gpt|")
+ assert any(t.startswith(VERBOSITY_PREFIX) for t in data["transforms_applied"])
+
+
+def test_openai_without_system_message_gets_one_inserted(shaped_client) -> None:
+ sent = _openai_body(with_system=False, gateway={})
+ data = compress(shaped_client, sent).json()
+ body = data["body"]
+ assert body["messages"][0]["role"] == "system"
+ assert body["messages"][0]["content"].startswith(STEERING_SENTINEL)
+ assert len(body["messages"]) == len(sent["messages"]) + 1
+ assert data["messages"] == body["messages"]
+
+
+def test_shaped_system_does_not_leak_into_session_snapshot(shaped_client) -> None:
+ """The steering block is appended on the provider body only: a second
+ turn re-appends it once, never twice, and the pre-steering prefix the
+ session snapshot holds stays byte-identical."""
+ session = {"session_id": "gw-shape-snapshot"}
+ sent1 = _openai_body(config=session, gateway={})
+ turn1 = compress(shaped_client, sent1).json()
+ sent2 = _openai_body(config=session, gateway={})
+ sent2["messages"] += [
+ {"role": "assistant", "content": "ok"},
+ {"role": "user", "content": "more"},
+ ]
+ turn2 = compress(shaped_client, sent2).json()
+ assert canonical(turn2["body"]["messages"][: len(turn1["body"]["messages"])]) == canonical(
+ turn1["body"]["messages"]
+ )
+ assert turn2["body"]["messages"][0]["content"].count(STEERING_SENTINEL) == 1
+
+
+# --------------------------------------------------------------------------- #
+# I-GATES #
+# --------------------------------------------------------------------------- #
+
+
+def test_disabled_by_default_leaves_body_untouched(headroom_client) -> None:
+ for sent in (_anthropic_body(gateway={}), _openai_body(gateway={})):
+ data = compress(headroom_client, sent).json()
+ assert _shaper_labels(data) == []
+ body = data["body"]
+ if "system" in sent:
+ assert body["system"] == SYSTEM_PROMPT
+ else:
+ assert body["messages"][0] == sent["messages"][0]
+ assert STEERING_SENTINEL not in canonical(body)
+
+
+def test_env_off_wins(make_headroom_client, monkeypatch) -> None:
+ monkeypatch.setenv("HEADROOM_OUTPUT_SHAPER", "0")
+ client = make_headroom_client()
+ data = compress(client, _anthropic_body(gateway={})).json()
+ assert _shaper_labels(data) == []
+ assert data["body"]["system"] == SYSTEM_PROMPT
+
+
+def test_cache_mode_labels_but_never_steers(make_headroom_client, monkeypatch) -> None:
+ """``steering_allowed_for`` is false in ``mode="cache"``: the measurement
+ label still rides the outcome but the prefix-cache key is left alone."""
+ monkeypatch.setenv("HEADROOM_OUTPUT_SHAPER", "1")
+ client = make_headroom_client(mode="cache")
+ for sent in (_anthropic_body(gateway={}), _openai_body(gateway={})):
+ data = compress(client, sent).json()
+ assert _stratum_label(data).startswith(STRATUM_PREFIX)
+ assert not any(t.startswith(VERBOSITY_PREFIX) for t in data["transforms_applied"])
+ assert STEERING_SENTINEL not in canonical(data["body"])
+
+
+def test_control_arm_labels_but_never_steers(make_headroom_client, monkeypatch) -> None:
+ monkeypatch.setenv("HEADROOM_OUTPUT_SHAPER", "1")
+ monkeypatch.setenv("HEADROOM_OUTPUT_HOLDOUT", "1")
+ client = make_headroom_client()
+ data = compress(client, _anthropic_body(gateway={})).json()
+ label = _stratum_label(data)
+ assert label.startswith(CONTROL_PREFIX)
+ assert data["body"]["system"] == SYSTEM_PROMPT
+ assert not any(t.startswith(VERBOSITY_PREFIX) for t in data["transforms_applied"])
+
+
+def test_legacy_mode_is_never_shaped(shaped_client, outcome_spy) -> None:
+ outcomes = outcome_spy(shaped_client)
+ sent = _openai_body() # no gateway block
+ data = compress(shaped_client, sent).json()
+ assert "body" not in data
+ assert _shaper_labels(data) == []
+ assert data["messages"][0] == sent["messages"][0]
+ assert not any(str(t).startswith("output_shaper:") for t in outcomes[0].transforms_applied)
+
+
+def test_fail_open_answers_are_never_shaped(shaped_client, monkeypatch) -> None:
+ from unittest.mock import AsyncMock
+
+ proxy = shaped_client.app.state.proxy
+ monkeypatch.setattr(proxy, "_run_compression_in_executor", AsyncMock(side_effect=TimeoutError))
+ data = compress(shaped_client, _anthropic_body(gateway={})).json()
+ assert data["compression_skipped"] is True
+ assert data["body"]["system"] == SYSTEM_PROMPT
+ assert _shaper_labels(data) == []
+
+
+# --------------------------------------------------------------------------- #
+# I-STABLE #
+# --------------------------------------------------------------------------- #
+
+
[email protected]("provider", ["anthropic", "openai"])
+def test_steering_is_byte_stable_over_three_session_turns(shaped_client, provider: str) -> None:
+ session = {"session_id": f"gw-shape-stable-{provider}"}
+ prefixes: list[str] = []
+ labels: list[str] = []
+ prev: list[dict[str, Any]] | None = None
+ for turn in range(3):
+ sent = (
+ _anthropic_body(config=session, gateway={})
+ if provider == "anthropic"
+ else _openai_body(config=session, gateway={})
+ )
+ sent["messages"] = sent["messages"] + [
+ m
+ for i in range(turn)
+ for m in (
+ {"role": "assistant", "content": f"answer {i}"},
+ {"role": "user", "content": f"follow-up {i}"},
+ )
+ ]
+ resp = compress(shaped_client, sent)
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ body = data["body"]
+ if provider == "anthropic":
+ prefixes.append(canonical(body["system"]))
+ assert len(_anthropic_steering_blocks(body)) == 1
+ else:
+ prefixes.append(canonical(body["messages"][0]))
+ assert body["messages"][0]["content"].count(STEERING_SENTINEL) == 1
+ labels.append(_stratum_label(data))
+ if prev is not None:
+ assert canonical(body["messages"][: len(prev)]) == canonical(prev)
+ prev = body["messages"]
+ assert len(set(prefixes)) == 1
+ # The label is measurement, not prefix bytes: its turn-kind field follows
+ # the tail of the conversation (tool-result continuation vs new ask), so
+ # only the arm and the model/tools strata are expected to hold steady.
+ parsed = [parse_stratum_label(label) for label in labels]
+ assert {arm for arm, _ in parsed} == {"treatment"}
+ assert len({key.split("|")[0] for _, key in parsed}) == 1
+ assert {key.split("|")[-1] for _, key in parsed} == {"tools"}
+
+
+# --------------------------------------------------------------------------- #
+# I-MEASURE #
+# --------------------------------------------------------------------------- #
+
+
[email protected]("provider", ["anthropic", "openai"])
+def test_label_rides_the_deferred_outcome_and_yields_output_savings(
+ shaped_client, monkeypatch, tmp_path, provider: str
+) -> None:
+ """Kong-shaped run: request half with ``relay_usage`` owed, response half
+ with the provider's usage. The recorded outcome carries the stratum label
+ and the relayed output tokens; the recorder observes it; and with a
+ baseline for the stratum the outcome funnel hands the savings tracker a
+ positive ``output_tokens_saved``."""
+ proxy = shaped_client.app.state.proxy
+ recorded: list[dict[str, Any]] = []
+ original_record = proxy.metrics.record_request
+
+ async def _metrics_spy(*args: Any, **kwargs: Any) -> Any:
+ recorded.append(kwargs)
+ return await original_record(*args, **kwargs)
+
+ monkeypatch.setattr(proxy.metrics, "record_request", _metrics_spy)
+
+ outcomes: list[Any] = []
+ original_outcome = proxy._record_request_outcome
+
+ async def _outcome_spy(outcome: Any, *args: Any, **kwargs: Any) -> Any:
+ outcomes.append(outcome)
+ return await original_outcome(outcome, *args, **kwargs)
+
+ monkeypatch.setattr(proxy, "_record_request_outcome", _outcome_spy)
+
+ recorder = SavingsRecorder(tmp_path / "output_savings.json", flush_every=10_000)
+ monkeypatch.setattr("headroom.proxy.output_savings._RECORDER", recorder)
+
+ sent = (
+ _anthropic_body(config={"session_id": "kong-shape-a"})
+ if provider == "anthropic"
+ else _openai_body(config={"session_id": "kong-shape-o"})
+ )
+ sent["gateway"] = {"can_relay_response": True, "plugin_version": "kong-headroom/0.1.0"}
+ half1 = shaped_client.post("/v1/compress", json=sent)
+ assert half1.status_code == 200, half1.text
+ data = half1.json()
+ assert data["obligations"] == ["relay_usage"]
+ label = _stratum_label(data)
+ arm, key = parse_stratum_label(label)
+ assert arm == "treatment"
+ assert outcomes == [] and recorded == [] # deferred until the response half
+
+ # A synthetic-control baseline for exactly this stratum: 1000 output
+ # tokens unshaped; the shaped turn below reports 100.
+ for _ in range(5):
+ recorder._ledger.baseline.observe(key, 1000)
+
+ usage = (
+ anthropic_usage(900, 100, cache_read=0, cache_write=800)
+ if provider == "anthropic"
+ else openai_usage(900, 100, cached=0)
+ )
+ half2 = shaped_client.post(
+ "/v1/compress/response",
+ json={"turn_id": data["turn_id"], "status": 200, "latency_ms": 5, "usage": usage},
+ )
+ assert half2.status_code == 200, half2.text
+ assert half2.json()["action"] == "done"
+
+ assert len(outcomes) == 1
+ outcome = outcomes[0]
+ assert label in outcome.transforms_applied
+ assert outcome.output_tokens == 100
+ # The recorder saw the shaped observation under the treatment arm ...
+ treatment = recorder._ledger.treatment.get(key)
+ assert treatment is not None and treatment.n == 1
+ # ... and the savings tracker was handed the counterfactual delta.
+ assert len(recorded) == 1
+ assert recorded[0]["output_tokens"] == 100
+ assert recorded[0]["output_tokens_saved"] == 900
diff --git a/tests/gateway/test_parity_proxy_vs_gateway.py b/tests/gateway/test_parity_proxy_vs_gateway.py
new file mode 100644
index 000000000..5cf6185d4
--- /dev/null
+++ b/tests/gateway/test_parity_proxy_vs_gateway.py
@@ -0,0 +1,206 @@
+"""Parity: the proxy path and the gateway two-half path forward the same bytes.
+
+The same scripted 3-turn conversation (large tool result, tools, session) runs
+(a) through ``/v1/chat/completions`` with the proxy's upstream bridged into a
+:class:`FakeProvider`, and (b) through :class:`FakeGateway` + ``/v1/compress`` +
+``/v1/compress/response`` against a second :class:`FakeProvider`. Per turn the
+provider-bound ``messages`` and ``tools`` must be equal and the recorded outcome
+token totals must agree within a declared tolerance.
+
+Known / expected divergences (each named at the assertion it would break):
+
+* FREEZE POLICY - the proxy path freezes with ``FREEZE_POLICY_CONFIRMED_CLAMP``
+ (never past what the provider confirmed via ``cached_tokens``) while the
+ compress path uses ``FREEZE_POLICY_REPLAYABLE`` (everything it already
+ returned). Both then overlay the previously forwarded prefix, so the BYTES are
+ expected to match; what differs is how much the pipeline is allowed to re-touch
+ before the overlay. If bytes ever diverge, this stage is the first suspect.
+* TOKENIZER SCALE - the chat path counts with ``openai_pipeline``'s tokenizer,
+ the compress path with the per-model registry tokenizer. Both are tiktoken for
+ gpt-4o, so ``tokens_saved`` should match closely; the tolerance below absorbs
+ small estimator deltas, not structural ones.
+* OUTCOME PROVIDER - the proxy path records ``provider="openai"``; the gateway
+ path records ``provider="compress"``. Compared by position, not by name.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import httpx
+import pytest
+import respx
+
+from tests.gateway.conftest import proxy_config
+from tests.gateway.fake_gateway import FakeGateway
+from tests.gateway.fake_provider import FakeProvider, openai_text_response, openai_usage
+from tests.gateway.samples import big_tool_history, canonical, openai_tools
+
+pytest.importorskip("fastapi")
+
+from fastapi.testclient import TestClient # noqa: E402
+
+from headroom.proxy.server import create_app # noqa: E402
+
+OPENAI_UPSTREAM = "https://api.openai.com/v1/chat/completions"
+SAVED_TOLERANCE_ABS = 32
+SAVED_TOLERANCE_REL = 0.10
+
+# The provider's answers are identical on both paths, turn for turn. Turn 1 is
+# cold; turns 2 and 3 report a warm prefix so the trackers on both sides see the
+# same confirmation signal.
+_SCRIPT = [
+ openai_text_response("Listed.", openai_usage(900, 3, 0), response_id="t1"),
+ openai_text_response("Sorted.", openai_usage(1000, 3, 896), response_id="t2"),
+ openai_text_response("Top 3 are 0, 30, 60.", openai_usage(1100, 5, 1000), response_id="t3"),
+]
+
+
+def _client_turns() -> list[list[dict[str, Any]]]:
+ h = big_tool_history()
+ t1 = h
+ t2 = t1 + [
+ {"role": "assistant", "content": "Listed."},
+ {"role": "user", "content": "Sort by score."},
+ ]
+ t3 = t2 + [{"role": "assistant", "content": "Sorted."}, {"role": "user", "content": "Top 3?"}]
+ return [t1, t2, t3]
+
+
+def _body(messages: list[dict[str, Any]]) -> dict[str, Any]:
+ return {"model": "gpt-4o", "messages": messages, "tools": openai_tools(), "temperature": 0}
+
+
+def _make_app_client() -> TestClient:
+ # CCR off on the proxy path: the chat handler would otherwise inject the
+ # ``headroom_retrieve`` tool and CCR markers, which the compress path's
+ # default (marker-free) mode never does. Parity is measured with both paths
+ # in marker-free mode.
+ app = create_app(
+ proxy_config(
+ ccr_inject_tool=False,
+ ccr_inject_marker=False,
+ ccr_handle_responses=False,
+ ccr_context_tracking=False,
+ )
+ )
+ return TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345))
+
+
+def _bridge(provider: FakeProvider):
+ """respx side effect: hand the proxy's upstream request to the fake provider."""
+
+ def _side_effect(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content or b"{}")
+ reply = provider.handle("/v1/chat/completions", body, dict(request.headers))
+ return httpx.Response(reply.status, content=reply.content, headers=reply.headers)
+
+ return _side_effect
+
+
+def _run_proxy_path(client: TestClient, provider: FakeProvider) -> list[dict[str, Any]]:
+ provider.script(list(_SCRIPT))
+ finals = []
+ for messages in _client_turns():
+ resp = client.post(
+ "/v1/chat/completions",
+ json=_body(messages),
+ headers={"authorization": "Bearer sk-test", "x-headroom-session-id": "parity"},
+ )
+ assert resp.status_code == 200, resp.text
+ finals.append(resp.json())
+ assert [f["id"] for f in finals] == ["t1", "t2", "t3"]
+ return [c.body for c in provider.calls]
+
+
+def _run_gateway_path(client: TestClient, provider: FakeProvider) -> list[dict[str, Any]]:
+ provider.script(list(_SCRIPT))
+ with TestClient(provider.app) as provider_client:
+ gateway = FakeGateway(client, provider_client, can_redrive=True, can_relay_response=True)
+ for messages in _client_turns():
+ result = gateway.turn(_body(messages), "parity-gw")
+ assert result.path == "proxy", (result.path, result.fail_open_reason)
+ assert result.compress_status == 200
+ assert "body" in result.compress_response, "gateway contract keys missing"
+ relay = result.response_half_calls[-1]
+ assert relay.status == 200, relay.response
+ assert [t.final_response["id"] for t in gateway.turns] == ["t1", "t2", "t3"]
+ return [c.body for c in provider.calls]
+
+
+def test_provider_bound_bytes_and_outcomes_match(monkeypatch) -> None:
+ """Per turn: provider-bound ``messages`` and ``tools`` are identical on both
+ paths, and the outcomes agree on provider-reported tokens and (within
+ tolerance) on ``tokens_saved``."""
+ proxy_provider, gateway_provider = FakeProvider(), FakeProvider()
+ respx.post(OPENAI_UPSTREAM).mock(side_effect=_bridge(proxy_provider))
+
+ outcomes: list[Any] = []
+ with _make_app_client() as client:
+ proxy = client.app.state.proxy
+
+ async def _spy(outcome: Any, *a: Any, **k: Any) -> None:
+ outcomes.append(outcome)
+
+ monkeypatch.setattr(proxy, "_record_request_outcome", _spy)
+
+ proxy_calls = _run_proxy_path(client, proxy_provider)
+ gateway_calls = _run_gateway_path(client, gateway_provider)
+
+ assert len(proxy_calls) == 3 and len(gateway_calls) == 3
+
+ for i, (p, g) in enumerate(zip(proxy_calls, gateway_calls)):
+ # Stage: session freeze/overlay (FREEZE POLICY divergence would show here).
+ assert canonical(p["messages"]) == canonical(g["messages"]), (
+ f"turn {i + 1}: messages differ"
+ )
+ # Stage: tool schema compaction (shared cache keyed by tool bytes).
+ assert canonical(p["tools"]) == canonical(g["tools"]), f"turn {i + 1}: tools differ"
+ assert p["model"] == g["model"] == "gpt-4o"
+ assert p["temperature"] == g["temperature"] == 0
+
+ # Both paths compressed something, otherwise parity is vacuous.
+ raw = big_tool_history()[2]["content"]
+ assert proxy_calls[0]["messages"][2]["content"] != raw
+
+ proxy_outcomes = [o for o in outcomes if o.provider == "openai"]
+ gateway_outcomes = [o for o in outcomes if o.provider == "compress"]
+ assert len(proxy_outcomes) == 3, [o.provider for o in outcomes]
+ assert len(gateway_outcomes) == 3, [o.provider for o in outcomes]
+ for i, (po, go) in enumerate(zip(proxy_outcomes, gateway_outcomes)):
+ # Stage: response half outcome completion (provider numbers, exact).
+ assert po.output_tokens == go.output_tokens == _SCRIPT[i]["usage"]["completion_tokens"], (
+ f"turn {i + 1}"
+ )
+ assert (
+ po.provider_input_tokens
+ == go.provider_input_tokens
+ == _SCRIPT[i]["usage"]["prompt_tokens"]
+ ), f"turn {i + 1}"
+ assert po.cache_read_tokens == go.cache_read_tokens, f"turn {i + 1}"
+ # Stage: tokenizer scale (declared tolerance, see module docstring).
+ tolerance = max(
+ SAVED_TOLERANCE_ABS, int(SAVED_TOLERANCE_REL * max(po.tokens_saved, go.tokens_saved))
+ )
+ assert abs(po.tokens_saved - go.tokens_saved) <= tolerance, (
+ f"turn {i + 1}: tokens_saved proxy={po.tokens_saved} gateway={go.tokens_saved}"
+ )
+ assert abs(po.original_tokens - go.original_tokens) <= tolerance, (
+ f"turn {i + 1}: original_tokens"
+ )
+
+
+def test_proxy_path_alone_is_byte_stable_baseline() -> None:
+ """The proxy-path half of the parity fixture, checked on its own so a
+ gateway-side failure cannot hide a broken baseline (passes today)."""
+ provider = FakeProvider()
+ respx.post(OPENAI_UPSTREAM).mock(side_effect=_bridge(provider))
+ with _make_app_client() as client:
+ calls = _run_proxy_path(client, provider)
+ assert len(calls) == 3
+ for prev, nxt in zip(calls, calls[1:]):
+ assert canonical(nxt["messages"][: len(prev["messages"])]) == canonical(prev["messages"])
+ assert canonical(nxt["tools"]) == canonical(prev["tools"])
diff --git a/tests/gateway/test_redrive_loop.py b/tests/gateway/test_redrive_loop.py
new file mode 100644
index 000000000..f4e5a94c4
--- /dev/null
+++ b/tests/gateway/test_redrive_loop.py
@@ -0,0 +1,451 @@
+"""The redrive loop: a re-driving hook split across HTTP calls (spec sections 2.4, 3.2).
+
+Invariants protected here:
+
+* L-CLIENT - the client never sees the synthetic ``search_tools`` call; it sees
+ the provider's final answer.
+* L-PROVIDER - the provider sees exactly one call per round, the second carrying
+ the reloaded tool and the appended assistant-call + tool-result.
+* L-ROUNDS - ``rounds`` counts re-drives; the registry's cap and the hook's own
+ ``max_rounds`` both bound the loop.
+* L-CLEAN - after ``done`` the turn is gone from the registry and no suspended
+ task is left on the event loop.
+* L-GUARDS - wrong turn id 404; ``response`` missing on a redrive turn 400.
+* L-NOSHRINK - ``can_redrive=False``, ``session_affinity=False`` and streaming
+ requests never see the deferral (tools are a subset of the input).
+* L-SHAPES - the loop works for the Anthropic Messages shape too.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from tests.gateway import redrive_hook_ext
+from tests.gateway.conftest import count_loop_tasks, registry_of
+from tests.gateway.fake_provider import (
+ anthropic_text_response,
+ anthropic_tool_use_response,
+ anthropic_usage,
+ openai_text_response,
+ openai_tool_call_response,
+ openai_usage,
+)
+from tests.gateway.samples import (
+ SYSTEM_PROMPT,
+ anthropic_tool_history,
+ anthropic_tools,
+ big_tool_history,
+ openai_tools,
+ tool_names,
+)
+
+SEARCH = redrive_hook_ext.SEARCH_TOOL_NAME
+
+
+def _chat_body(**extra: Any) -> dict[str, Any]:
+ return {"model": "gpt-4o", "messages": big_tool_history(), "tools": openai_tools(), **extra}
+
+
+def _anthropic_body(**extra: Any) -> dict[str, Any]:
+ return {
+ "model": "claude-sonnet-4-5",
+ "max_tokens": 128,
+ "system": SYSTEM_PROMPT,
+ "messages": anthropic_tool_history(),
+ "tools": anthropic_tools(),
+ **extra,
+ }
+
+
+def _search_then_answer(fake_provider, query: str = "create issue") -> None:
+ fake_provider.script(
+ [
+ openai_tool_call_response(
+ SEARCH, {"query": query}, openai_usage(300, 8), call_id="call_s1"
+ ),
+ openai_text_response(
+ "Issue created.", openai_usage(420, 6, 300), response_id="chatcmpl-final"
+ ),
+ ]
+ )
+
+
+def _has_search_call(response: dict[str, Any]) -> bool:
+ return redrive_hook_ext.detect_search_call(response) is not None
+
+
+# --------------------------------------------------------------------------- #
+# Happy path #
+# --------------------------------------------------------------------------- #
+
+
+def test_one_redrive_round_end_to_end(headroom_client, fake_provider, make_gateway) -> None:
+ """L-CLIENT, L-PROVIDER, L-ROUNDS, L-CLEAN together."""
+ hook = redrive_hook_ext.register()
+ _search_then_answer(fake_provider)
+ baseline = count_loop_tasks(headroom_client)
+ gateway = make_gateway(can_redrive=True, can_relay_response=True)
+
+ result = gateway.turn(_chat_body(), "loop-1")
+
+ assert result.path == "loop", result.fail_open_reason
+ assert result.obligations == ["redrive", "relay_usage"]
+ # L-CLIENT
+ assert result.final_status == 200
+ assert result.final_response is not None
+ assert result.final_response["id"] == "chatcmpl-final"
+ assert not _has_search_call(result.final_response)
+ # L-PROVIDER
+ assert len(fake_provider.calls) == 2
+ first, second = fake_provider.calls
+ assert tool_names(first.tools) == ["get_items", SEARCH]
+ assert "deferred_create_issue" in tool_names(second.tools)
+ assert tool_names(second.tools)[:2] == ["get_items", SEARCH]
+ assert second.messages[: len(first.messages)] == first.messages
+ assert second.messages[-2]["role"] == "assistant"
+ assert second.messages[-2]["tool_calls"][0]["id"] == "call_s1"
+ assert second.messages[-1] == {
+ "role": "tool",
+ "tool_call_id": "call_s1",
+ "content": second.messages[-1]["content"],
+ }
+ assert second.messages[-1]["content"].startswith(redrive_hook_ext.LOADED_PREFIX)
+ # The redrive request is the FULL provider body, not just messages.
+ redrive_step = result.response_half_calls[0].response
+ assert redrive_step["action"] == "redrive"
+ assert redrive_step["round"] == 1
+ assert redrive_step["turn_id"] == result.turn_id
+ assert redrive_step["request"]["model"] == "gpt-4o"
+ assert redrive_step["request"]["messages"] == second.messages
+ assert redrive_step["request"]["tools"] == second.tools
+ assert "gateway" not in redrive_step["request"] and "config" not in redrive_step["request"]
+ # L-ROUNDS
+ done = result.done
+ assert done is not None
+ assert done["rounds"] == 1
+ # The hook's final answer IS the last provider response the gateway posted,
+ # so ``response`` may be null ("forward what you already have") or that same
+ # body; the client-visible invariant (asserted above) is what matters.
+ assert done["response"] is None or done["response"]["id"] == "chatcmpl-final"
+ assert done["usage_applied"] is True # cached_tokens=300 on the final answer
+ assert hook.rounds_driven == 1
+ assert hook.queries == ["create issue"]
+ # L-CLEAN
+ assert registry_of(headroom_client).get(result.turn_id) is None
+ assert count_loop_tasks(headroom_client) <= baseline
+
+
+def test_no_search_call_means_done_with_null_response(
+ headroom_client, fake_provider, make_gateway
+) -> None:
+ """L-CLIENT: the hook armed but the model answered directly -> ``done`` with
+ ``response: null`` and the gateway forwards what it already has."""
+ redrive_hook_ext.register()
+ fake_provider.script([openai_text_response("Direct answer.", response_id="chatcmpl-direct")])
+ gateway = make_gateway(can_redrive=True, can_relay_response=False)
+ result = gateway.turn(_chat_body(), "loop-direct")
+ assert result.path == "loop"
+ assert len(fake_provider.calls) == 1
+ done = result.done
+ assert done is not None
+ assert done["response"] is None
+ assert done["rounds"] == 0
+ assert result.final_response["id"] == "chatcmpl-direct"
+ assert registry_of(headroom_client).get(result.turn_id) is None
+
+
+def test_two_rounds(headroom_client, fake_provider, make_gateway) -> None:
+ """L-ROUNDS: two searches, three provider calls, ``rounds == 2``, and the
+ tools block accumulates (sorted) across rounds."""
+ redrive_hook_ext.register()
+ fake_provider.script(
+ [
+ openai_tool_call_response(SEARCH, {"query": "create issue"}, call_id="s1"),
+ openai_tool_call_response(SEARCH, {"query": "query db"}, call_id="s2"),
+ openai_text_response("Both done.", response_id="chatcmpl-final2"),
+ ]
+ )
+ result = make_gateway(can_redrive=True, can_relay_response=True).turn(_chat_body(), "loop-2")
+ assert len(fake_provider.calls) == 3
+ assert result.done["rounds"] == 2
+ assert result.final_response["id"] == "chatcmpl-final2"
+ third = fake_provider.calls[2]
+ assert tool_names(third.tools) == [
+ "get_items",
+ SEARCH,
+ "deferred_create_issue",
+ "deferred_query_db",
+ ]
+ assert [m["role"] for m in third.messages[-4:]] == ["assistant", "tool", "assistant", "tool"]
+
+
+# --------------------------------------------------------------------------- #
+# Bounds #
+# --------------------------------------------------------------------------- #
+
+
+def test_hook_max_rounds_caps_the_loop(headroom_client, fake_provider, make_gateway) -> None:
+ """L-ROUNDS: the hook's own cap stops the loop; the client gets the last
+ provider answer (still a search call - visible rather than silently wrong)."""
+ redrive_hook_ext.register(max_rounds=2)
+ fake_provider.script(
+ [openai_tool_call_response(SEARCH, {"query": "again"}, call_id=f"s{i}") for i in range(10)]
+ )
+ result = make_gateway(can_redrive=True, can_relay_response=False, max_redrives=20).turn(
+ _chat_body(), "loop-cap"
+ )
+ assert len(fake_provider.calls) == 3 # 1 + max_rounds
+ assert result.done is not None
+ assert result.done["rounds"] == 2
+ assert registry_of(headroom_client).get(result.turn_id) is None
+
+
+def test_registry_max_redrives_env_caps_the_loop(
+ make_headroom_client, monkeypatch, fake_provider, provider_client
+) -> None:
+ """L-ROUNDS: ``HEADROOM_GATEWAY_MAX_REDRIVES`` bounds a hook that would spin."""
+ from tests.gateway.fake_gateway import FakeGateway
+
+ monkeypatch.setenv("HEADROOM_GATEWAY_MAX_REDRIVES", "2")
+ client = make_headroom_client()
+ redrive_hook_ext.register(max_rounds=50)
+ fake_provider.script(
+ [openai_tool_call_response(SEARCH, {"query": "again"}, call_id=f"s{i}") for i in range(10)]
+ )
+ gateway = FakeGateway(
+ client, provider_client, can_redrive=True, can_relay_response=False, max_redrives=50
+ )
+ result = gateway.turn(_chat_body(), "loop-envcap")
+ assert result.done is not None
+ # Two re-drives are served (1 + 2 provider calls); the third request bumps
+ # ``rounds`` past the cap and is answered ``done`` instead of ``redrive``.
+ assert len(fake_provider.calls) == 3
+ assert result.done["rounds"] == 3
+ assert result.done["response"] is None
+ assert registry_of(client).get(result.turn_id) is None
+
+
+# --------------------------------------------------------------------------- #
+# Guards #
+# --------------------------------------------------------------------------- #
+
+
+def test_wrong_turn_id_is_404(headroom_client, fake_provider) -> None:
+ """L-GUARDS"""
+ redrive_hook_ext.register()
+ resp = headroom_client.post(
+ "/v1/compress/response",
+ json={"turn_id": "f" * 32, "response": openai_text_response("x")},
+ )
+ assert resp.status_code == 404
+ assert resp.json()["error"]["type"] == "unknown_turn"
+
+
+def test_missing_response_on_redrive_turn_is_400(headroom_client) -> None:
+ """L-GUARDS: a turn that carries ``redrive`` cannot complete without the
+ provider response; the turn stays registered for a corrected relay."""
+ redrive_hook_ext.register()
+ data = headroom_client.post(
+ "/v1/compress",
+ json={**_chat_body(), "gateway": {"can_redrive": True}, "config": {"session_id": "guard"}},
+ ).json()
+ assert data["obligations"] == ["redrive"]
+ resp = headroom_client.post(
+ "/v1/compress/response", json={"turn_id": data["turn_id"], "usage": openai_usage(1, 1)}
+ )
+ assert resp.status_code == 400, resp.text
+ assert resp.json()["error"]["type"] == "missing_response"
+ assert registry_of(headroom_client).get(data["turn_id"]) is not None
+
+
+def test_non_200_provider_status_skips_hooks(headroom_client, fake_provider, make_gateway) -> None:
+ """L-GUARDS: a provider error is relayed, not re-driven; the turn completes."""
+ from tests.gateway.fake_provider import ScriptedResponse
+
+ hook = redrive_hook_ext.register()
+ fake_provider.script([ScriptedResponse(body={"error": {"message": "overloaded"}}, status=529)])
+ result = make_gateway(can_redrive=True, can_relay_response=True).turn(_chat_body(), "loop-529")
+ assert result.path == "loop"
+ assert result.final_status == 529
+ assert result.done is not None
+ assert result.done["response"] is None
+ assert hook.response_calls == 0
+ assert registry_of(headroom_client).get(result.turn_id) is None
+
+
+# --------------------------------------------------------------------------- #
+# No shrink without reload #
+# --------------------------------------------------------------------------- #
+
+
+def test_can_redrive_false_never_shrinks(headroom_client, fake_provider, make_gateway) -> None:
+ """L-NOSHRINK"""
+ hook = redrive_hook_ext.register()
+ result = make_gateway(can_redrive=False, can_relay_response=True).turn(
+ _chat_body(), "noshrink-1"
+ )
+ assert result.path == "proxy"
+ assert "redrive" not in result.obligations
+ assert len(fake_provider.calls) == 1
+ sent = fake_provider.calls[0]
+ assert SEARCH not in tool_names(sent.tools)
+ assert set(tool_names(sent.tools)) <= set(tool_names(openai_tools()))
+ assert hook.shrink_calls == 0
+
+
+def test_session_affinity_false_never_shrinks(headroom_client, fake_provider, make_gateway) -> None:
+ """L-NOSHRINK: without affinity the response half may land on another replica."""
+ hook = redrive_hook_ext.register()
+ result = make_gateway(can_redrive=True, can_relay_response=True, session_affinity=False).turn(
+ _chat_body(), "noshrink-2"
+ )
+ assert result.path == "proxy"
+ assert "redrive" not in result.obligations
+ assert SEARCH not in tool_names(fake_provider.calls[0].tools)
+ assert hook.shrink_calls == 0
+
+
+def test_streaming_request_never_shrinks(headroom_client, fake_provider, make_gateway) -> None:
+ """L-NOSHRINK: the plugin sets ``can_redrive=false`` for ``stream: true``; the
+ stream reaches the client with its usage frame and is relayed."""
+ hook = redrive_hook_ext.register()
+ fake_provider.script([openai_text_response("streamed", openai_usage(50, 4, 20))])
+ gateway = make_gateway(can_redrive=True, can_relay_response=True)
+ body = _chat_body(stream=True, stream_options={"include_usage": True})
+ result = gateway.turn(body, "noshrink-stream")
+ assert gateway.gateway_block(body)["can_redrive"] is False
+ assert result.path == "proxy"
+ assert hook.shrink_calls == 0
+ assert SEARCH not in tool_names(fake_provider.calls[0].tools)
+ assert result.final_headers["content-type"].startswith("text/event-stream")
+ relay = result.response_half_calls[-1]
+ assert relay.request["usage"] == openai_usage(50, 4, 20)
+ assert relay.status == 200
+ assert relay.response["usage_applied"] is True
+
+
+# --------------------------------------------------------------------------- #
+# Anthropic shape #
+# --------------------------------------------------------------------------- #
+
+
+def test_anthropic_shape_redrive(headroom_client, fake_provider, make_gateway) -> None:
+ """L-SHAPES: tool_use search -> tool_result reload -> final text."""
+ hook = redrive_hook_ext.register()
+ fake_provider.script(
+ [
+ anthropic_tool_use_response(
+ SEARCH,
+ {"query": "query db"},
+ anthropic_usage(200, 9, 0, 150),
+ tool_use_id="toolu_s1",
+ ),
+ anthropic_text_response(
+ "Rows fetched.", anthropic_usage(260, 7, 150, 0), response_id="msg_final"
+ ),
+ ]
+ )
+ result = make_gateway(can_redrive=True, can_relay_response=True).turn(
+ _anthropic_body(), "anthropic-loop"
+ )
+ assert result.path == "loop", result.fail_open_reason
+ assert result.compress_response["route"]["provider"] == "anthropic"
+ assert result.final_response["id"] == "msg_final"
+ assert not _has_search_call(result.final_response)
+ assert len(fake_provider.calls) == 2
+ first, second = fake_provider.calls
+ assert first.path.endswith("/v1/messages")
+ assert first.body["system"] == SYSTEM_PROMPT
+ assert first.body["max_tokens"] == 128
+ assert tool_names(first.tools) == ["get_items", SEARCH]
+ assert "input_schema" in first.tools[-1]
+ assert tool_names(second.tools) == ["get_items", SEARCH, "deferred_query_db"]
+ assert second.messages[-2]["role"] == "assistant"
+ assert second.messages[-2]["content"][0]["type"] == "tool_use"
+ assert second.messages[-1]["role"] == "user"
+ assert second.messages[-1]["content"][0] == {
+ "type": "tool_result",
+ "tool_use_id": "toolu_s1",
+ "content": second.messages[-1]["content"][0]["content"],
+ }
+ assert result.done["rounds"] == 1
+ assert hook.rounds_driven == 1
+ assert registry_of(headroom_client).get(result.turn_id) is None
+
+
+def test_stale_retry_replays_last_redrive_without_double_billing(
+ headroom_client, fake_provider, make_gateway
+) -> None:
+ """Invariant: the response half is idempotent on ``round``.
+
+ A gateway whose socket dropped after headroom answered ``redrive`` re-posts
+ round 0. Headroom must repeat the same ``redrive`` answer, not feed round
+ 0's response to the parked hook as the answer to the re-drive, and must not
+ bill round 0's usage twice.
+ """
+ from tests.gateway import redrive_hook_ext
+ from tests.gateway.fake_provider import openai_text_response, openai_tool_call_response
+ from tests.gateway.samples import big_tool_history, openai_tools
+
+ redrive_hook_ext.register()
+ search_call = openai_tool_call_response(
+ "search_tools", {"query": "deferred"}, usage={"prompt_tokens": 100, "completion_tokens": 5}
+ )
+ body = {"model": "gpt-4o", "messages": big_tool_history(), "tools": openai_tools()}
+ compress = headroom_client.post(
+ "/v1/compress",
+ json={**body, "gateway": {"can_redrive": True, "can_relay_response": True}},
+ ).json()
+ assert "redrive" in compress["obligations"]
+ turn_id = compress["turn_id"]
+
+ first = headroom_client.post(
+ "/v1/compress/response",
+ json={
+ "turn_id": turn_id,
+ "round": 0,
+ "usage": search_call["usage"],
+ "response": search_call,
+ },
+ ).json()
+ assert first["action"] == "redrive" and first["round"] == 1
+
+ # The retry of round 0 must replay, byte-for-byte, the answer above.
+ retry = headroom_client.post(
+ "/v1/compress/response",
+ json={
+ "turn_id": turn_id,
+ "round": 0,
+ "usage": search_call["usage"],
+ "response": search_call,
+ },
+ ).json()
+ assert retry == first
+
+ # A round from the future is refused; nothing is consumed.
+ future = headroom_client.post(
+ "/v1/compress/response",
+ json={"turn_id": turn_id, "round": 2, "response": search_call},
+ )
+ assert future.status_code == 400
+ assert future.json()["error"]["type"] == "round_out_of_sequence"
+
+ final = openai_text_response(
+ "final answer", usage={"prompt_tokens": 120, "completion_tokens": 7}
+ )
+ done = headroom_client.post(
+ "/v1/compress/response",
+ json={"turn_id": turn_id, "round": 1, "usage": final["usage"], "response": final},
+ ).json()
+ assert done["action"] == "done"
+ assert done["rounds"] == 1
+ # Round 0 billed once, round 1 once: 100+120 in, 5+7 out.
+ proxy = headroom_client.app.state.proxy
+ assert proxy.gateway_turns.get(turn_id) is None
+ # Also drive the whole thing through the FakeGateway once for the round plumbing.
+ fake_provider.script([search_call, final])
+ gw = make_gateway(can_redrive=True, can_relay_response=True)
+ result = gw.turn(body, session_id=None)
+ assert result.path == "loop"
+ assert [c.request["round"] for c in result.response_half_calls] == [0, 1]
+ assert result.final_response["choices"][0]["message"]["content"] == "final answer"
diff --git a/tests/gateway/test_usage_relay_openai_shape.py b/tests/gateway/test_usage_relay_openai_shape.py
new file mode 100644
index 000000000..00115ee83
--- /dev/null
+++ b/tests/gateway/test_usage_relay_openai_shape.py
@@ -0,0 +1,119 @@
+"""``/v1/usage`` accepts OpenAI-shaped usage (spec section 4).
+
+Invariant: a relay built from Kong's ``ai-proxy`` log statistics
+(``prompt_tokens_details.cached_tokens`` or top-level ``cached_tokens``) maps to
+``cache_read_input_tokens`` and is applied; the pre-existing behaviour for
+Anthropic-shaped usage and for a bare ``{"prompt_tokens": N}`` (400) is unchanged.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from tests.gateway.conftest import compress
+from tests.gateway.samples import big_tool_history
+
+
+def _open_session(client, session_id: str) -> None:
+ resp = compress(
+ client,
+ {"model": "gpt-4o", "messages": big_tool_history(), "config": {"session_id": session_id}},
+ )
+ assert resp.status_code == 200, resp.text
+
+
+def _usage(client, session_id: str, usage: dict[str, Any]):
+ return client.post("/v1/usage", json={"session_id": session_id, "usage": usage})
+
+
+def test_prompt_tokens_details_cached_tokens_is_applied(headroom_client) -> None:
+ _open_session(headroom_client, "oai-details")
+ resp = _usage(
+ headroom_client,
+ "oai-details",
+ {
+ "prompt_tokens": 60_000,
+ "completion_tokens": 9,
+ "prompt_tokens_details": {"cached_tokens": 50_000},
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["applied"] is True
+ assert data["frozen_message_count"] >= 1
+
+
+def test_top_level_cached_tokens_is_applied(headroom_client) -> None:
+ _open_session(headroom_client, "oai-top")
+ resp = _usage(headroom_client, "oai-top", {"prompt_tokens": 60_000, "cached_tokens": 50_000})
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["applied"] is True
+
+
+def test_openai_shape_matches_anthropic_shape_frozen_count(headroom_client) -> None:
+ """The mapping is exact: the OpenAI shape freezes what the equivalent
+ Anthropic read-only relay freezes."""
+ _open_session(headroom_client, "oai-eq-a")
+ _open_session(headroom_client, "oai-eq-b")
+ a = _usage(headroom_client, "oai-eq-a", {"cache_read_input_tokens": 50_000})
+ b = _usage(headroom_client, "oai-eq-b", {"prompt_tokens_details": {"cached_tokens": 50_000}})
+ assert a.status_code == b.status_code == 200
+ assert a.json()["frozen_message_count"] == b.json()["frozen_message_count"]
+
+
+def test_cached_tokens_zero_alone_is_no_cache_signal(headroom_client) -> None:
+ """OpenAI has no write signal, so ``cached_tokens: 0`` on its own must map to
+ the existing read-only-zero rule: accepted, not applied."""
+ _open_session(headroom_client, "oai-zero")
+ resp = _usage(
+ headroom_client,
+ "oai-zero",
+ {"prompt_tokens": 100, "prompt_tokens_details": {"cached_tokens": 0}},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["applied"] is False
+ assert resp.json()["reason"] == "no_cache_signal"
+
+
+ "usage",
+ [
+ {"prompt_tokens_details": {"cached_tokens": -1}},
+ {"cached_tokens": True},
+ {"prompt_tokens_details": {"cached_tokens": "5"}},
+ ],
+ ids=["negative", "bool", "string"],
+)
+def test_invalid_openai_cache_values_are_400(headroom_client, usage) -> None:
+ _open_session(headroom_client, "oai-bad")
+ resp = _usage(headroom_client, "oai-bad", usage)
+ assert resp.status_code == 400, resp.text
+
+
+# --- unchanged behaviour (passes today) --------------------------------------
+
+
+def test_bare_prompt_tokens_is_still_400(headroom_client) -> None:
+ _open_session(headroom_client, "oai-bare")
+ resp = _usage(headroom_client, "oai-bare", {"prompt_tokens": 12345})
+ assert resp.status_code == 400
+ assert "cache" in resp.json()["error"]["message"]
+
+
+def test_anthropic_shape_unchanged(headroom_client) -> None:
+ _open_session(headroom_client, "ant-ok")
+ resp = _usage(
+ headroom_client,
+ "ant-ok",
+ {"cache_read_input_tokens": 0, "cache_creation_input_tokens": 50_000},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["applied"] is True
+
+
+def test_unknown_session_still_404(headroom_client) -> None:
+ resp = _usage(headroom_client, "never-seen", {"prompt_tokens_details": {"cached_tokens": 10}})
+ assert resp.status_code == 404
+ assert resp.json()["error"]["type"] == "unknown_session"
diff --git a/tests/test_gateway_turn_unit.py b/tests/test_gateway_turn_unit.py
new file mode 100644
index 000000000..2e3f6e77b
--- /dev/null
+++ b/tests/test_gateway_turn_unit.py
@@ -0,0 +1,778 @@
+"""Unit tests for ``headroom.proxy.gateway_turn`` internals — no HTTP.
+
+Three things have to hold or the two-half contract is unsafe:
+
+* ``SuspendedHookRunner`` parks a hook coroutine between two HTTP requests
+ and never leaks a task, whatever the hook does (re-drives, finishes at
+ once, raises, or is cancelled mid-suspend);
+* ``PendingTurnRegistry`` expires and evicts without losing a deferred
+ outcome draft;
+* ``normalize_usage`` reads every provider shape a gateway can relay and
+ never reports a cache signal that was not there.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+from typing import Any
+
+import pytest
+
+from headroom.proxy import gateway_turn as gt
+from headroom.proxy.gateway_turn import (
+ GatewayCapabilities,
+ GatewayRequestError,
+ NormalizedUsage,
+ PendingTurn,
+ PendingTurnRegistry,
+ SuspendedHookRunner,
+ compact_gateway_tools,
+ compute_obligations,
+ normalize_usage,
+ parse_gateway_block,
+)
+from headroom.proxy.outcome import RequestOutcome
+from headroom.proxy.turn_hooks import TurnContext, clear_turn_hooks, register_turn_hook
+
+
[email protected](autouse=True)
+def _no_hooks():
+ clear_turn_hooks()
+ yield
+ clear_turn_hooks()
+
+
+def _ctx(tools: Any = None) -> TurnContext:
+ return TurnContext(
+ provider="openai",
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "hi"}],
+ tools=tools,
+ )
+
+
+# --------------------------------------------------------------------------- #
+# SuspendedHookRunner #
+# --------------------------------------------------------------------------- #
+
+
+class _RedriveN:
+ """Re-drive ``n`` times, then return the last provider response."""
+
+ name = "redrive_n"
+ stream_safe = False
+
+ def __init__(self, n: int) -> None:
+ self.n = n
+ self.seen: list[dict[str, Any]] = []
+
+ async def on_response(self, ctx: Any, response: Any, call_model: Any) -> Any:
+ current = response
+ for i in range(self.n):
+ ctx.tools = [{"name": f"reloaded_{i}"}]
+ current = await call_model(ctx.messages + [{"role": "assistant", "content": str(i)}])
+ self.seen.append(current)
+ return current
+
+
+class _NoRedrive:
+ name = "no_redrive"
+ stream_safe = False
+
+ async def on_response(self, ctx: Any, response: Any, call_model: Any) -> Any:
+ return None
+
+
+class _Replaces:
+ name = "replaces"
+ stream_safe = False
+
+ async def on_response(self, ctx: Any, response: Any, call_model: Any) -> Any:
+ return {"replaced": True, "from": response.get("id")}
+
+
+class _Raises:
+ name = "raises"
+ stream_safe = False
+
+ async def on_response(self, ctx: Any, response: Any, call_model: Any) -> Any:
+ raise RuntimeError("boom")
+
+
+async def _baseline() -> int:
+ await asyncio.sleep(0)
+ return len(asyncio.all_tasks())
+
+
+def test_runner_start_suspends_then_resume_completes() -> None:
+ async def scenario() -> None:
+ base = await _baseline()
+ hook = _RedriveN(1)
+ register_turn_hook(hook)
+ ctx = _ctx(tools=[{"name": "t"}])
+ runner = SuspendedHookRunner(ctx)
+
+ step = await runner.start({"id": "r1"})
+ assert step.is_redrive
+ assert step.messages is not None and step.messages[-1]["content"] == "0"
+ assert step.tools == [{"name": "reloaded_0"}]
+ assert runner.state == "awaiting_redrive"
+ # The hook task is parked — exactly one extra task while suspended.
+ assert len(asyncio.all_tasks()) == base + 1
+
+ final = {"id": "r2"}
+ step2 = await runner.resume(final)
+ assert step2.kind == "done"
+ # The hook returned the very object the gateway posted — nothing to
+ # send back, the gateway forwards what it already holds.
+ assert step2.response is None
+ assert runner.state == "done"
+ assert runner.rounds == 1
+ assert hook.seen == [final]
+ assert await _baseline() == base
+
+ asyncio.run(scenario())
+
+
+def test_runner_multiple_rounds() -> None:
+ async def scenario() -> None:
+ base = await _baseline()
+ register_turn_hook(_RedriveN(3))
+ runner = SuspendedHookRunner(_ctx())
+ step = await runner.start({"id": "r0"})
+ rounds = 0
+ while step.is_redrive:
+ rounds += 1
+ step = await runner.resume({"id": f"r{rounds}"})
+ assert rounds == 3
+ assert step.kind == "done" and step.response is None
+ assert await _baseline() == base
+
+ asyncio.run(scenario())
+
+
+def test_runner_cancel_mid_suspend_leaves_no_tasks() -> None:
+ async def scenario() -> None:
+ base = await _baseline()
+ register_turn_hook(_RedriveN(2))
+ runner = SuspendedHookRunner(_ctx())
+ step = await runner.start({"id": "r0"})
+ assert step.is_redrive
+ assert len(asyncio.all_tasks()) == base + 1
+ await runner.cancel()
+ assert runner.state == "done"
+ assert runner._task is not None and runner._task.done()
+ assert await _baseline() == base
+ # Resuming a cancelled runner is a programming error, not a hang.
+ with pytest.raises(RuntimeError):
+ await runner.resume({"id": "late"})
+
+ asyncio.run(scenario())
+
+
+def test_runner_hook_without_redrive_is_done_immediately() -> None:
+ async def scenario() -> None:
+ base = await _baseline()
+ register_turn_hook(_NoRedrive())
+ runner = SuspendedHookRunner(_ctx())
+ step = await runner.start({"id": "r0"})
+ assert step.kind == "done" and step.response is None
+ assert runner.rounds == 0
+ assert await _baseline() == base
+
+ asyncio.run(scenario())
+
+
+def test_runner_replacement_is_returned() -> None:
+ async def scenario() -> None:
+ register_turn_hook(_Replaces())
+ runner = SuspendedHookRunner(_ctx())
+ step = await runner.start({"id": "orig"})
+ assert step.kind == "done"
+ assert step.response == {"replaced": True, "from": "orig"}
+
+ asyncio.run(scenario())
+
+
+def test_runner_hook_that_raises_is_done_with_none() -> None:
+ async def scenario() -> None:
+ base = await _baseline()
+ register_turn_hook(_Raises())
+ runner = SuspendedHookRunner(_ctx())
+ step = await runner.start({"id": "r0"})
+ assert step.kind == "done" and step.response is None
+ assert await _baseline() == base
+
+ asyncio.run(scenario())
+
+
+def test_runner_broken_runner_function_is_done_with_none() -> None:
+ """``run_response_hooks`` swallows hook errors; a broken runner itself
+ must still resolve to a done step rather than an exception."""
+
+ async def broken(ctx: Any, response: Any, call_model: Any) -> Any:
+ raise ValueError("runner exploded")
+
+ async def scenario() -> None:
+ base = await _baseline()
+ runner = SuspendedHookRunner(_ctx(), run=broken)
+ step = await runner.start({"id": "r0"})
+ assert step.kind == "done" and step.response is None
+ assert await _baseline() == base
+
+ asyncio.run(scenario())
+
+
+def test_runner_no_hooks_registered_is_inert() -> None:
+ async def scenario() -> None:
+ runner = SuspendedHookRunner(_ctx())
+ step = await runner.start({"id": "r0"})
+ assert step.kind == "done" and step.response is None
+
+ asyncio.run(scenario())
+
+
+def test_runner_start_twice_is_an_error() -> None:
+ async def scenario() -> None:
+ register_turn_hook(_NoRedrive())
+ runner = SuspendedHookRunner(_ctx())
+ await runner.start({"id": "r0"})
+ with pytest.raises(RuntimeError):
+ await runner.start({"id": "r1"})
+
+ asyncio.run(scenario())
+
+
+# --------------------------------------------------------------------------- #
+# PendingTurnRegistry #
+# --------------------------------------------------------------------------- #
+
+
+def _outcome(request_id: str = "hr_test") -> RequestOutcome:
+ return RequestOutcome(
+ request_id=request_id,
+ provider="compress",
+ model="gpt-4o",
+ original_tokens=100,
+ optimized_tokens=50,
+ output_tokens=0,
+ tokens_saved=50,
+ attempted_input_tokens=100,
+ )
+
+
+def _turn(turn_id: str, now: float, ttl: float, draft: RequestOutcome | None = None) -> PendingTurn:
+ return PendingTurn(
+ turn_id=turn_id,
+ session_key=None,
+ session_id=None,
+ provider="openai",
+ model="gpt-4o",
+ body={"model": "gpt-4o", "messages": []},
+ ctx=None,
+ obligations=["relay_usage"],
+ outcome_draft=draft,
+ created_at=now,
+ deadline=now + ttl,
+ )
+
+
+def test_registry_ttl_expiry_calls_on_expire_with_draft() -> None:
+ clock = [1000.0]
+ expired: list[PendingTurn] = []
+ reg = PendingTurnRegistry(
+ ttl_seconds=10, max_entries=100, on_expire=expired.append, clock=lambda: clock[0]
+ )
+ reg.register(_turn("a", clock[0], 10, _outcome("a")))
+ reg.register(_turn("b", clock[0], 10))
+ assert len(reg) == 2
+ assert reg.get("a") is not None
+ clock[0] += 11
+ # Lazy sweep on lookup: the expired turn is gone and reported once.
+ assert reg.get("b") is None
+ assert len(reg) == 0
+ assert sorted(t.turn_id for t in expired) == ["a", "b"]
+ assert expired[0].outcome_draft is not None or expired[1].outcome_draft is not None
+ assert reg.stats()["expired"] == 2
+
+
+def test_registry_lru_eviction_at_capacity() -> None:
+ evicted: list[str] = []
+ reg = PendingTurnRegistry(
+ ttl_seconds=100,
+ max_entries=2,
+ on_expire=lambda t: evicted.append(t.turn_id),
+ clock=lambda: 0.0,
+ )
+ for tid in ("a", "b", "c"):
+ reg.register(_turn(tid, 0.0, 100))
+ assert len(reg) == 2
+ assert evicted == ["a"]
+ assert reg.get("a") is None and reg.get("c") is not None
+ assert reg.stats()["evicted"] == 1
+
+
+def test_registry_pop_and_in_flight_turns_survive_sweep() -> None:
+ clock = [0.0]
+ expired: list[str] = []
+ reg = PendingTurnRegistry(
+ ttl_seconds=5,
+ max_entries=10,
+ on_expire=lambda t: expired.append(t.turn_id),
+ clock=lambda: clock[0],
+ )
+ t = _turn("a", 0.0, 5)
+ reg.register(t)
+ t.in_flight = True
+ clock[0] = 100.0
+ assert reg.sweep() == [] # being driven right now: never yanked mid-step
+ t.in_flight = False
+ assert [x.turn_id for x in reg.sweep()] == ["a"]
+ assert reg.pop("a") is None
+ assert expired == ["a"]
+
+
+def test_registry_on_expire_exceptions_are_swallowed() -> None:
+ def bad(turn: PendingTurn) -> None:
+ raise RuntimeError("nope")
+
+ clock = [0.0]
+ reg = PendingTurnRegistry(ttl_seconds=1, max_entries=10, on_expire=bad, clock=lambda: clock[0])
+ reg.register(_turn("a", 0.0, 1))
+ clock[0] = 5.0
+ assert reg.sweep() # did not raise
+
+
+def test_registry_env_defaults(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("HEADROOM_GATEWAY_TURN_TTL_SECONDS", "7.5")
+ monkeypatch.setenv("HEADROOM_GATEWAY_MAX_PENDING_TURNS", "3")
+ reg = PendingTurnRegistry()
+ assert reg.ttl_seconds == 7.5 and reg.max_entries == 3
+ monkeypatch.setenv("HEADROOM_GATEWAY_TURN_TTL_SECONDS", "garbage")
+ assert PendingTurnRegistry().ttl_seconds == gt.DEFAULT_TURN_TTL_SECONDS
+
+
+def test_on_turn_expired_records_draft_on_the_loop_and_cancels_runner() -> None:
+ recorded: list[RequestOutcome] = []
+
+ class _Proxy:
+ gateway_turns = PendingTurnRegistry(ttl_seconds=1, max_entries=10)
+
+ async def _record_request_outcome(self, outcome: RequestOutcome) -> None:
+ recorded.append(outcome)
+
+ proxy = _Proxy()
+
+ async def scenario() -> None:
+ base = await _baseline()
+ register_turn_hook(_RedriveN(1))
+ runner = SuspendedHookRunner(_ctx())
+ await runner.start({"id": "r0"})
+ turn = _turn("a", 0.0, 1, _outcome("draft"))
+ turn.runner = runner
+ gt.on_turn_expired(proxy, turn)
+ # Both the record and the cancel are tasks; let them run.
+ for _ in range(5):
+ await asyncio.sleep(0)
+ assert [o.request_id for o in recorded] == ["draft"]
+ assert turn.outcome_draft is None
+ assert runner.state == "done"
+ assert await _baseline() == base
+
+ asyncio.run(scenario())
+
+
+def test_on_turn_expired_without_loop_parks_the_draft_then_flushes() -> None:
+ recorded: list[RequestOutcome] = []
+
+ class _Proxy:
+ gateway_turns = PendingTurnRegistry(ttl_seconds=1, max_entries=10)
+
+ async def _record_request_outcome(self, outcome: RequestOutcome) -> None:
+ recorded.append(outcome)
+
+ proxy = _Proxy()
+ # No running loop: the draft is parked, not lost.
+ gt.on_turn_expired(proxy, _turn("a", 0.0, 1, _outcome("orphan")))
+ assert [o.request_id for o in proxy.gateway_turns.orphaned_outcomes] == ["orphan"]
+ assert recorded == []
+
+ async def scenario() -> None:
+ gt.on_turn_expired(proxy, _turn("b", 0.0, 1, _outcome("fresh")))
+ for _ in range(5):
+ await asyncio.sleep(0)
+
+ asyncio.run(scenario())
+ assert sorted(o.request_id for o in recorded) == ["fresh", "orphan"]
+ assert proxy.gateway_turns.orphaned_outcomes == []
+
+
+# --------------------------------------------------------------------------- #
+# normalize_usage #
+# --------------------------------------------------------------------------- #
+
+
+def test_normalize_anthropic_shape() -> None:
+ u = normalize_usage(
+ {
+ "input_tokens": 100,
+ "output_tokens": 20,
+ "cache_read_input_tokens": 60,
+ "cache_creation_input_tokens": 10,
+ }
+ )
+ assert u == NormalizedUsage(100, 20, 60, 10)
+ assert u.has_cache_signal and u.should_apply
+
+
+def test_normalize_openai_chat_shape() -> None:
+ u = normalize_usage(
+ {
+ "prompt_tokens": 100,
+ "completion_tokens": 20,
+ "prompt_tokens_details": {"cached_tokens": 64},
+ }
+ )
+ assert u == NormalizedUsage(100, 20, 64, None)
+ assert u.has_cache_signal and u.should_apply
+
+
+def test_normalize_openai_responses_shape() -> None:
+ u = normalize_usage(
+ {"input_tokens": 10, "output_tokens": 2, "input_tokens_details": {"cached_tokens": 8}}
+ )
+ assert u == NormalizedUsage(10, 2, 8, None)
+
+
+def test_normalize_kong_flat_shape() -> None:
+ u = normalize_usage({"prompt_tokens": 50, "completion_tokens": 5, "cached_tokens": 40})
+ assert u == NormalizedUsage(50, 5, 40, None)
+
+
+def test_normalize_nested_usage_descends_once() -> None:
+ u = normalize_usage({"id": "x", "usage": {"prompt_tokens": 7, "completion_tokens": 3}})
+ assert u == NormalizedUsage(7, 3, None, None)
+ assert not u.has_cache_signal and not u.should_apply
+
+
+def test_normalize_no_cache_fields_is_accepted_but_not_applied() -> None:
+ u = normalize_usage({"prompt_tokens": 12345})
+ assert u.input_tokens == 12345
+ assert not u.has_cache_signal
+ assert not u.should_apply
+
+
+def test_normalize_zero_only_read_is_no_signal_but_both_zero_applies() -> None:
+ assert not normalize_usage({"prompt_tokens_details": {"cached_tokens": 0}}).should_apply
+ assert normalize_usage(
+ {"cache_read_input_tokens": 0, "cache_creation_input_tokens": 0}
+ ).should_apply
+
+
+ "usage",
+ [
+ {"input_tokens": True},
+ {"prompt_tokens": -1},
+ {"cache_read_input_tokens": False},
+ {"prompt_tokens_details": {"cached_tokens": -5}},
+ {"cached_tokens": "12"},
+ {"output_tokens": 1.5},
+ ],
+)
+def test_normalize_rejects_bools_negatives_and_non_ints(usage: dict[str, Any]) -> None:
+ with pytest.raises(ValueError):
+ normalize_usage(usage)
+
+
+def test_normalize_empty_and_odd_shapes_never_raise() -> None:
+ for usage in ({}, {"usage": None}, {"prompt_tokens_details": "nope"}, {"input_tokens": None}):
+ u = normalize_usage(usage)
+ assert not u.has_cache_signal
+
+
+def test_merged_with_sums_billed_and_keeps_latest_cache() -> None:
+ a = NormalizedUsage(100, 10, 60, None)
+ b = NormalizedUsage(150, 20, 90, None)
+ m = a.merged_with(b)
+ assert (m.input_tokens, m.output_tokens, m.cache_read) == (250, 30, 90)
+ c = a.merged_with(NormalizedUsage(1, 1, None, None))
+ assert c.cache_read == 60 # a signal-free round does not erase the last signal
+
+
+# --------------------------------------------------------------------------- #
+# Capabilities, obligations, outcome completion, compaction #
+# --------------------------------------------------------------------------- #
+
+
+def test_parse_gateway_block_modes() -> None:
+ assert parse_gateway_block({"messages": []}) is None
+ caps = parse_gateway_block({"gateway": {}})
+ assert caps == GatewayCapabilities(False, False, True, None)
+ caps = parse_gateway_block(
+ {
+ "gateway": {
+ "can_redrive": True,
+ "session_affinity": False,
+ "plugin_version": "0.1.0",
+ "x": 1,
+ }
+ }
+ )
+ assert caps is not None and caps.can_redrive and not caps.session_affinity
+ assert not caps.redrive_allowed
+ assert caps.plugin_version == "0.1.0"
+ assert caps.echo() == {
+ "can_redrive": True,
+ "can_relay_response": False,
+ "session_affinity": False,
+ }
+ for bad in ({"gateway": []}, {"gateway": None}, {"gateway": {"can_redrive": "yes"}}):
+ with pytest.raises(GatewayRequestError):
+ parse_gateway_block(bad)
+
+
+def test_compute_obligations() -> None:
+ both = GatewayCapabilities(can_redrive=True, can_relay_response=True)
+ assert compute_obligations(both, redrive_armed=True) == ["redrive", "relay_usage"]
+ assert compute_obligations(both, redrive_armed=False) == ["relay_usage"]
+ no_affinity = dataclasses.replace(both, session_affinity=False)
+ assert compute_obligations(no_affinity, redrive_armed=True) == ["relay_usage"]
+ assert compute_obligations(GatewayCapabilities(), redrive_armed=True) == []
+
+
+def test_complete_outcome_fills_only_existing_fields() -> None:
+ draft = dataclasses.replace(_outcome(), total_latency_ms=5.0)
+ done = gt.complete_outcome(draft, NormalizedUsage(120, 30, 80, 4), status=200, latency_ms=250)
+ assert done.output_tokens == 30
+ assert done.provider_input_tokens == 120
+ assert done.optimized_tokens == 50 # never overwritten by the provider count
+ assert (done.cache_read_tokens, done.cache_write_tokens) == (80, 4)
+ assert done.total_latency_ms == 255.0
+ assert done.status_code == 200
+ failed = gt.complete_outcome(draft, None, status=529, latency_ms=None)
+ assert failed.status_code == 529 and failed.output_tokens == 0
+
+
+def test_compact_gateway_tools_is_deterministic_and_isolated() -> None:
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "get",
+ "description": "Get things\n\n now.",
+ "parameters": {"$schema": "x", "title": "T", "type": "object", "properties": {}},
+ },
+ }
+ ]
+ a, ta = compact_gateway_tools(tools)
+ b, tb = compact_gateway_tools(tools)
+ assert a == b and ta == tb == ["tool_schema_compaction"]
+ assert a is not b # a hook mutating one turn's tools cannot touch the next
+ a[0]["function"]["name"] = "mutated"
+ c, _ = compact_gateway_tools(tools)
+ assert c[0]["function"]["name"] == "get"
+ assert compact_gateway_tools(None) == (None, [])
+ assert compact_gateway_tools([]) == ([], [])
+
+
+def test_request_transformer_runs_hooks_and_arms_redrive() -> None:
+ class _Fold:
+ name = "fold"
+ stream_safe = True
+
+ def on_request(self, ctx: Any) -> None:
+ ctx.messages[-1]["content"] = "x"
+
+ class _Redriver:
+ name = "redriver"
+ stream_safe = False
+
+ def on_request(self, ctx: Any) -> None:
+ ctx.tools = [t for t in ctx.tools if t["name"] != "big"]
+
+ async def on_response(self, ctx: Any, response: Any, call_model: Any) -> Any:
+ return None
+
+ register_turn_hook(_Fold())
+ register_turn_hook(_Redriver())
+ tools = [{"name": "big", "description": "b" * 500}, {"name": "small"}]
+ tags: dict[str, Any] = {}
+ tr = gt.RequestTransformer(
+ provider="openai",
+ model_name="gpt-4o",
+ tools=tools,
+ config=None,
+ tags=tags,
+ caps=GatewayCapabilities(can_redrive=True),
+ )
+ out = tr.run([{"role": "user", "content": "a much longer message than x"}])
+ assert out[-1]["content"] == "x"
+ assert tr.result is not None
+ assert tr.result.redrive_armed
+ assert [t["name"] for t in tr.result.tools] == ["small"]
+ assert "turn_hook" in tr.result.transforms
+ assert any(t.startswith("turn_hook:tools:") for t in tr.result.transforms)
+ assert tags["turn_hook_tools_saved_tokens"] > 0
+
+ # Without redrive the re-driving hook is skipped entirely: tools intact,
+ # nothing armed. No shrink without reload.
+ tr2 = gt.RequestTransformer(
+ provider="openai",
+ model_name="gpt-4o",
+ tools=tools,
+ config=None,
+ tags={},
+ caps=GatewayCapabilities(can_redrive=False),
+ )
+ tr2.run([{"role": "user", "content": "hello there"}])
+ assert tr2.result is not None
+ assert not tr2.result.redrive_armed
+ assert [t["name"] for t in tr2.result.tools] == ["big", "small"]
+
+
+def test_build_provider_body_strips_control_keys() -> None:
+ body = {
+ "model": "gpt-4o",
+ "messages": [1],
+ "config": {"session_id": "s"},
+ "gateway": {},
+ "token_budget": 10,
+ "temperature": 0.2,
+ "tools": None,
+ }
+ out = gt.build_provider_body(body, [2], None)
+ assert out == {"model": "gpt-4o", "messages": [2], "temperature": 0.2, "tools": None}
+ assert gt.build_provider_body(body, [2], [{"name": "t"}])["tools"] == [{"name": "t"}]
+
+
+# --------------------------------------------------------------------------- #
+# CCR redrive (config.mode="ccr") #
+# --------------------------------------------------------------------------- #
+
+
+def _transform_result(tools: Any = None) -> gt.RequestTransformResult:
+ ctx = _ctx(tools=tools)
+ return gt.RequestTransformResult(
+ messages=ctx.messages, tools=tools, ctx=ctx, transforms=[], redrive_armed=False
+ )
+
+
+def test_arm_ccr_redrive_gates_and_injects_once() -> None:
+ caps = GatewayCapabilities(can_redrive=True)
+ r = _transform_result(tools=[{"type": "function", "function": {"name": "get"}}])
+ assert not gt.arm_ccr_redrive(r, provider="openai", caps=caps, mode=None, ccr_hashes=["a"])
+ assert not gt.arm_ccr_redrive(r, provider="openai", caps=caps, mode="ccr", ccr_hashes=[])
+ assert not gt.arm_ccr_redrive(
+ r, provider="openai", caps=GatewayCapabilities(), mode="ccr", ccr_hashes=["a"]
+ )
+ assert r.tools is not None and len(r.tools) == 1 and r.transforms == []
+
+ assert gt.arm_ccr_redrive(r, provider="openai", caps=caps, mode="ccr", ccr_hashes=["a"])
+ names = [t["function"]["name"] for t in r.tools]
+ assert names == ["get", "headroom_retrieve"]
+ assert r.ctx is not None and r.ctx.tools is r.tools # live tools for the re-drive
+ assert r.transforms == ["ccr_tool_injected"]
+ # Already present: no duplicate, no second transform marker.
+ assert gt.arm_ccr_redrive(r, provider="openai", caps=caps, mode="ccr", ccr_hashes=["a"])
+ assert [t["function"]["name"] for t in r.tools] == ["get", "headroom_retrieve"]
+ assert r.transforms == ["ccr_tool_injected"]
+
+ # No tools at all: the CCR tool becomes the whole list, Anthropic shape.
+ r2 = _transform_result(tools=None)
+ assert gt.arm_ccr_redrive(r2, provider="anthropic", caps=caps, mode="ccr", ccr_hashes=["a"])
+ from headroom.ccr.tool_injection import create_ccr_tool_definition
+
+ assert r2.tools == [create_ccr_tool_definition("anthropic")]
+
+
+class _FakeCCRHandler:
+ """Stands in for CCRResponseHandler: one retrieval round via api_call_fn."""
+
+ def __init__(self) -> None:
+ self.calls: list[tuple[list[dict[str, Any]], Any]] = []
+
+ def has_ccr_tool_calls(self, response: dict[str, Any], provider: str) -> bool:
+ return bool(response.get("ccr"))
+
+ async def handle_response(self, response, messages, tools, api_call_fn, provider="openai"):
+ msgs = list(messages) + [{"role": "tool", "content": "original bytes"}]
+ self.calls.append((msgs, tools))
+ return await api_call_fn(msgs, tools)
+
+
+def test_response_runner_drives_ccr_then_hooks_through_one_suspension() -> None:
+ class _Proxy:
+ ccr_response_handler = _FakeCCRHandler()
+
+ proxy = _Proxy()
+ seen: list[str] = []
+
+ class _Observer:
+ name = "observer"
+ stream_safe = False
+
+ async def on_response(self, ctx: Any, response: Any, call_model: Any) -> Any:
+ seen.append(response["id"])
+ return None
+
+ async def scenario() -> None:
+ base = await _baseline()
+ register_turn_hook(_Observer())
+ tools = [{"type": "function", "function": {"name": "headroom_retrieve"}}]
+ turn = _turn("t", 0.0, 10)
+ turn.ctx = _ctx(tools=tools)
+ turn.obligations = ["redrive"]
+ turn.ccr_armed = True
+ runner = SuspendedHookRunner(turn.ctx, run=gt.make_response_runner(proxy, turn))
+
+ step = await runner.start({"id": "r0", "ccr": True})
+ assert step.is_redrive
+ assert step.messages is not None and step.messages[-1]["content"] == "original bytes"
+ assert step.tools == tools
+ final = {"id": "r1"}
+ step2 = await runner.resume(final)
+ assert step2.kind == "done" and step2.response is None
+ # CCR ran first, then the hook saw the CCR-resolved response only.
+ assert seen == ["r1"]
+ assert proxy.ccr_response_handler.calls[0][1] == tools
+ assert await _baseline() == base
+
+ asyncio.run(scenario())
+
+
+def test_response_runner_without_ccr_calls_is_hooks_only() -> None:
+ class _Proxy:
+ ccr_response_handler = _FakeCCRHandler()
+
+ async def scenario() -> None:
+ turn = _turn("t", 0.0, 10)
+ turn.ctx = _ctx()
+ turn.ccr_armed = True
+ runner = SuspendedHookRunner(turn.ctx, run=gt.make_response_runner(_Proxy(), turn))
+ step = await runner.start({"id": "plain"})
+ assert step.kind == "done" and step.response is None
+
+ asyncio.run(scenario())
+
+
+def test_response_runner_ccr_failure_falls_back_to_the_response() -> None:
+ class _Broken(_FakeCCRHandler):
+ async def handle_response(self, *a, **kw):
+ raise RuntimeError("store down")
+
+ class _Proxy:
+ ccr_response_handler = _Broken()
+
+ async def scenario() -> None:
+ base = await _baseline()
+ turn = _turn("t", 0.0, 10)
+ turn.ctx = _ctx()
+ turn.ccr_armed = True
+ runner = SuspendedHookRunner(turn.ctx, run=gt.make_response_runner(_Proxy(), turn))
+ step = await runner.start({"id": "r0", "ccr": True})
+ assert step.kind == "done" and step.response is None
+ assert await _baseline() == base
+
+ asyncio.run(scenario())
diff --git a/tests/test_turn_hook_seams.py b/tests/test_turn_hook_seams.py
new file mode 100644
index 000000000..bca61e226
--- /dev/null
+++ b/tests/test_turn_hook_seams.py
@@ -0,0 +1,174 @@
+"""The two turn-hook seams the gateway-path extensions rely on.
+
+* ``priority`` — hooks run lowest-first, registration order for ties, default
+ ``DEFAULT_HOOK_PRIORITY`` when absent or unparseable. Entry-point discovery
+ order is not something an operator controls, so a hook whose gate depends on
+ another hook's output (tool deferral after a model router) must be able to
+ say so.
+* ``TurnContext.provider_headers`` + ``merge_provider_headers`` — a hook may
+ ask for a provider header; the handler honours only allow-listed names and
+ merges ``anthropic-beta`` behind the client's own tokens.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from headroom.proxy.turn_hooks import (
+ DEFAULT_HOOK_PRIORITY,
+ PROVIDER_HEADER_ALLOWLIST,
+ TurnContext,
+ clear_turn_hooks,
+ merge_provider_headers,
+ register_turn_hook,
+ registered_turn_hooks,
+ run_request_hooks,
+ run_response_hooks,
+)
+
+
[email protected](autouse=True)
+def _clean_registry():
+ clear_turn_hooks()
+ yield
+ clear_turn_hooks()
+
+
+class _Hook:
+ stream_safe = True
+
+ def __init__(self, name: str, priority: Any = None, log: list[str] | None = None) -> None:
+ self.name = name
+ if priority is not None:
+ self.priority = priority
+ self._log = log if log is not None else []
+
+ def on_request(self, ctx: TurnContext) -> None:
+ self._log.append(f"req:{self.name}")
+
+ async def on_response(self, ctx: TurnContext, response: dict, call_model: Any) -> None:
+ self._log.append(f"resp:{self.name}")
+ return None
+
+
+def _ctx() -> TurnContext:
+ return TurnContext(provider="anthropic", model="claude-sonnet-4-5", messages=[], tools=[])
+
+
+# --------------------------------------------------------------------------- #
+# priority #
+# --------------------------------------------------------------------------- #
+
+
+def test_registered_hooks_sort_by_priority_with_stable_ties() -> None:
+ register_turn_hook(_Hook("late", 200))
+ register_turn_hook(_Hook("default-a"))
+ register_turn_hook(_Hook("router", 10))
+ register_turn_hook(_Hook("default-b"))
+ register_turn_hook(_Hook("bad", "not-a-number"))
+ assert [h.name for h in registered_turn_hooks()] == [
+ "router",
+ "default-a",
+ "default-b",
+ "bad",
+ "late",
+ ]
+
+
+def test_default_priority_is_one_hundred() -> None:
+ assert DEFAULT_HOOK_PRIORITY == 100
+
+
+async def test_request_and_response_hooks_run_in_priority_order() -> None:
+ log: list[str] = []
+ register_turn_hook(_Hook("shaping", 200, log))
+ register_turn_hook(_Hook("fold", 50, log))
+ register_turn_hook(_Hook("router", 10, log))
+ ctx = _ctx()
+ run_request_hooks(ctx)
+ assert log == ["req:router", "req:fold", "req:shaping"]
+ log.clear()
+
+ async def _call_model(messages: list) -> dict:
+ return {}
+
+ await run_response_hooks(ctx, {}, _call_model)
+ assert log == ["resp:router", "resp:fold", "resp:shaping"]
+
+
+def test_router_before_gate_changes_what_the_gate_sees() -> None:
+ """The reason the seam exists: a priority-10 router rewrites ``ctx.model``
+ and a priority-200 gate registered EARLIER still sees the routed id."""
+ seen: list[str] = []
+
+ class Gate:
+ name = "gate"
+ stream_safe = True
+ priority = 200
+
+ def on_request(self, ctx: TurnContext) -> None:
+ seen.append(ctx.model)
+
+ class Router:
+ name = "router"
+ stream_safe = True
+ priority = 10
+
+ def on_request(self, ctx: TurnContext) -> None:
+ ctx.model = "anthropic.claude-sonnet-4-5-v1:0"
+
+ register_turn_hook(Gate())
+ register_turn_hook(Router())
+ run_request_hooks(_ctx())
+ assert seen == ["anthropic.claude-sonnet-4-5-v1:0"]
+
+
+# --------------------------------------------------------------------------- #
+# provider_headers #
+# --------------------------------------------------------------------------- #
+
+
+def test_context_has_its_own_empty_provider_headers() -> None:
+ a, b = _ctx(), _ctx()
+ assert a.provider_headers == {} and b.provider_headers == {}
+ a.provider_headers["anthropic-beta"] = "x"
+ assert b.provider_headers == {}
+
+
+def test_allowlist_is_anthropic_beta_only_today() -> None:
+ assert PROVIDER_HEADER_ALLOWLIST == frozenset({"anthropic-beta"})
+
+
[email protected]("requested", [None, {}, {"anthropic-beta": ""}, {"anthropic-beta": " "}])
+def test_nothing_requested_merges_to_nothing(requested: Any) -> None:
+ assert merge_provider_headers({"anthropic-beta": "client-1"}, requested) == {}
+
+
+def test_disallowed_names_are_dropped() -> None:
+ out = merge_provider_headers(
+ None,
+ {"Authorization": "Bearer x", "x-api-key": "k", "anthropic-beta": "tok-a"},
+ )
+ assert out == {"anthropic-beta": "tok-a"}
+
+
+def test_beta_merges_client_first_and_deduplicates() -> None:
+ out = merge_provider_headers(
+ {"Anthropic-Beta": "client-1,tok-a"},
+ {"ANTHROPIC-BETA": "tok-a, tok-b ,tok-a"},
+ )
+ assert out == {"anthropic-beta": "client-1,tok-a,tok-b"}
+
+
+def test_beta_without_client_value_is_just_the_hooks() -> None:
+ assert merge_provider_headers({}, {"anthropic-beta": "tok-a"}) == {"anthropic-beta": "tok-a"}
+ assert merge_provider_headers({"anthropic-beta": ""}, {"anthropic-beta": "tok-a"}) == {
+ "anthropic-beta": "tok-a"
+ }
+
+
+def test_non_string_values_are_ignored() -> None:
+ assert merge_provider_headers({}, {"anthropic-beta": ["tok-a"]}) == {} # type: ignore[dict-item]
diff --git a/wiki/proxy.md b/wiki/proxy.md
index 845b0afbf..584f4b239 100644
--- a/wiki/proxy.md
+++ b/wiki/proxy.md
@@ -274,7 +274,7 @@ Compression-only endpoint. Compresses messages without ever making a **completio
**No format conversion.** `messages` may be OpenAI-shaped (`role: "tool"` + `tool_call_id`) or Anthropic-shaped (`tool_use` / `tool_result` content blocks); the same shape comes back. `model` selects the tokenizer and context limit — send the real name, including gateway-prefixed forms like `bedrock/anthropic.claude-3-5-sonnet`.
-**`system` and `tools` are ignored.** Anthropic sends both out of band. This endpoint accepts them without complaint (200, no warning) and returns neither, so neither is compressed — keep carrying them yourself. That means the Anthropic system prompt is not compressed here, and tool-schema compaction / tool-search deferral are not reachable through this route; run Headroom as the proxy if you need those.
+**`system` and `tools` are ignored outside gateway mode.** Anthropic sends both out of band. Without a `gateway` block this endpoint accepts them without complaint (200, no warning) and returns neither, so neither is compressed — keep carrying them yourself. That means the Anthropic system prompt is not compressed here, and tool-schema compaction / tool-search deferral are not reachable this way. Gateway mode (below) passes `tools` through and compacts them; in OSS, native tool-search deferral is still proxy-only — the headroom-tool-search extension adds it to gateway mode as a turn hook.
**Request:**
```json
@@ -285,6 +285,7 @@ Compression-only endpoint. Compresses messages without ever making a **completio
"config": { // optional
"mode": "lossy_inline", // ccr | lossy_inline | lossless_then_lossy
"frozen_message_count": 12, // pin an already-cached prefix
+ "session_id": "conv-8f1c", // session mode: Headroom keeps the replay state
"compress_user_messages": false,
"target_ratio": 0.5,
"protect_recent": 2,
@@ -303,18 +304,19 @@ Compression-only endpoint. Compresses messages without ever making a **completio
"compression_ratio": 0.23, // tokens_after / tokens_before — LOWER is better
"transforms_applied": ["router:smart_crusher:0.35"],
"transforms_summary": {"router:smart_crusher:0.35": 1},
- "ccr_hashes": [] // non-empty only with mode="ccr"
+ "ccr_hashes": [], // non-empty only with mode="ccr"
+ "session": {"id": "conv-8f1c", "frozen_message_count": 12, "cached_prefix_replayed": true} // session mode only
}
```
**Headers:**
- `x-headroom-bypass: true` — skip compression, return messages as-is with zeroed metrics
-**Error responses:** 400 (missing/invalid fields, bad `config.mode` or `config.frozen_message_count`), 401 (bad `HEADROOM_PROXY_TOKEN`), 404 (non-loopback without `HEADROOM_COMPRESS_ALLOW_REMOTE=1`), 503 (compression failed)
+**Error responses:** 400 (missing/invalid fields, bad `config.mode`, `config.frozen_message_count` or `config.session_id`, `session_id` with `compress_user_messages`, malformed `gateway` block), 401 (bad `HEADROOM_PROXY_TOKEN`), 404 (non-loopback without `HEADROOM_COMPRESS_ALLOW_REMOTE=1`), 503 (compression failed; in session mode also `compression_timeout` — retry the turn)
-**Fail-open:** on timeout you get 200 with the original messages plus `compression_skipped: true` and `skip_reason: "compression_timeout"`.
+**Fail-open:** without a session, on timeout you get 200 with the original messages plus `compression_skipped: true` and `skip_reason: "compression_timeout"`. In session mode a timeout or busy session lock is a 503 instead, because handing back originals would desync the replay state.
-**Multi-turn callers — don't lose the prefix cache.** This endpoint is stateless: unlike the proxy's own request path (which runs a CacheAligner and tracks provider cache hits across turns), it has no idea what the provider already cached.
+**Multi-turn callers — don't lose the prefix cache.** Without `config.session_id` this endpoint is stateless: unlike the proxy's own request path (which runs a CacheAligner and tracks provider cache hits across turns), it has no idea what the provider already cached. Either let Headroom keep the state (session mode, below) or keep it yourself with `frozen_message_count`.
The provider caches the bytes you *forwarded*, which compression already changed — so your originals and the cached prefix are no longer the same thing, and it is the forwarded version you must keep reproducing. Compression also varies with position: an older tool result can fall outside the recent-read protection window as the conversation grows and be compressed harder than last turn, so re-compression is not guaranteed to reproduce earlier output either. Two rules:
@@ -340,6 +342,16 @@ def next_turn(new_messages):
Note `protect_recent` is not a substitute — it guards the newest messages, while `frozen_message_count` guards the oldest, which is the cached end.
+**Session mode.** Pass `config.session_id` (non-empty, at most 256 chars) and Headroom keeps the conversation's replay state itself — the same per-session compression cache and prefix tracker the proxy uses — so a gateway that owns routing can resend the raw conversation every turn and get a byte-identical prefix back. Everything previously returned for the session comes back unchanged; only the new tail is compressed; an explicit `frozen_message_count` still wins when larger. Forward the returned messages verbatim. `compress_user_messages` is refused (400). State is in-process (replay cache: `HEADROOM_COMPRESSION_CACHE_TTL_SECONDS`, default 3900; tracker state: 10 idle minutes), so multi-process deployments must pin a session to one process. `HEADROOM_COMPRESS_SESSION_FROM_HEADER=1` lets the `x-headroom-session-id` header stand in for `config.session_id` (off by default).
+
+Optionally relay the provider's usage for attribution with `POST /v1/usage` `{"session_id": "...", "usage": {...}}`. Anthropic `cache_read_input_tokens` / `cache_creation_input_tokens` and OpenAI `prompt_tokens_details.cached_tokens` / flat `cached_tokens` are accepted; a block with none of them is a 400. Replies `{"session_id", "frozen_message_count", "applied"}` (`applied: false, reason: "no_cache_signal"` when the only present field is 0), 404 `unknown_session`, or 503 `session_busy` (retry). Telemetry only — it never raises the frozen count.
+
+**Gateway mode (two-half turn contract).** Add a top-level `gateway` object (`{}` is enough) and one model turn becomes two calls, so a gateway that never lets Headroom see the provider response can still run transforms whose reload step needs it — the proxy's "no shrink without reload" rule at the API boundary. `gateway` fields: `can_redrive` (default `false`: the gateway can call the provider again with a request Headroom hands it; send `false` when streaming), `can_relay_response` (default `false`: the gateway will post status/usage after each turn), `session_affinity` (default `true`; `false` disables re-driving because pending turns are in-process), `plugin_version` (diagnostics). Every other top-level field (`system`, `tools`, `temperature`, …) passes through; `tools` is compacted deterministically (`tool_schema_compaction`; `tool_desc_compaction` with `HEADROOM_TOOL_DESC_MAX_CHARS`); extension turn hooks run, stream-safe-only unless `can_redrive` and `session_affinity` both hold. The response adds `body` (the complete provider request — forward it as-is; never contains `config`, `gateway`, `token_budget`), `turn_id`, `route` (`{model, provider, service_tier, reason}`, advisory; a routing extension's model is also written into `body.model`), `obligations` (`redrive` and/or `relay_usage`) and a `gateway` echo. Fail-open answers carry the same keys with originals and `obligations: []`. A turn is registered only when `obligations` is non-empty; with `relay_usage` the `/stats` record waits for the response half. Knobs: `HEADROOM_GATEWAY_TURN_TTL_SECONDS` (120), `HEADROOM_GATEWAY_MAX_PENDING_TURNS` (10000), `HEADROOM_GATEWAY_MAX_REDRIVES` (8). With `config.mode: "ccr"` and re-drive allowed, `headroom_retrieve` is injected into `body.tools` (`ccr_tool_injected`) and the response half answers the model's retrieval calls itself.
+
+`POST /v1/compress/response` (same exposure rules as `/v1/compress`) is the response half: `{"turn_id", "status": 200, "latency_ms", "usage": {...}, "response": {...}}`. `usage` accepts Anthropic, OpenAI chat (`prompt_tokens_details.cached_tokens`), OpenAI Responses (`input_tokens_details.cached_tokens`) and Kong's flat `cached_tokens` shapes, or the whole provider body (a nested `usage` key is descended into once); billed counters are summed across re-drive rounds. `response` is required when the turn carries `redrive`. Answers: `{"action": "done", "turn_id", "response": <replacement or null — forward what you hold>, "frozen_message_count", "usage_applied", "rounds"}` or `{"action": "redrive", "turn_id", "request": <full provider body to send>, "round"}` — post the provider's JSON back under the same `turn_id`; past `HEADROOM_GATEWAY_MAX_REDRIVES` the turn ends with `done` and `response: null`. Errors: 400 `invalid_request` / `missing_response`, 404 `unknown_turn` (unregistered, finished, or expired), 409 `turn_busy`.
+
+**Kong plugin.** [kong-plugin-headroom](https://github.com/headroomlabs-ai/kong-plugin-headroom) (its own repo; `luarocks install kong-plugin-headroom`) implements both halves for Kong Gateway 3.9 (session id from a header, usage relay from the `log` phase, re-drive loop in `access`). The contract itself is installed in Headroom through the compress-turn seam (`headroom.proxy.compress_turn`, `HEADROOM_GATEWAY_CONTRACT`), the same seam a third-party contract would use.
+
## Using with Claude Code
```bash