mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
## Why On a proxy shared by several callers, the semantic response cache was keyed only by request content and upstream (#3349). A second caller who sent the identical request with a different provider key was served the completion generated for the first caller, under the first caller's key, and never reached the upstream. That discloses completions across tenants (finding 01-F15). ## What changes - `compute_cache_partition()` in `headroom/proxy/semantic_cache_key_policy.py`: an HMAC-SHA256 under a per-process random key over the caller's credential and account-selector headers plus the authenticated principal. Headers counted: every header the shared credential-header rule (`internal_header_policy.is_credential_header`) matches, which covers `authorization`, `proxy-authorization`, `cookie` and `x-api-key`, and any header whose name ends in `api-key`, `key`, `token`, `secret`, `account`, `account-id`, `organization` or `project` (so `x-api-key`, `api-key`, `x-goog-api-key`, `chatgpt-account-id`, `openai-organization`, `openai-project` and so on). Matching by name shape keeps new providers partitioned by default. Cookie is used as a whole value; it is only ever HMAC input. `x-headroom-*` headers (including the proxy's own token, which the security gate has already removed) and idempotency keys are excluded. A request with no credential and no principal gets the shared `anon` partition. - The partition is an HMAC, not a plain hash, so it cannot be used to confirm a guessed credential. - `identity.resolve_authenticated_principal()` returns a principal only when an identity resolver is installed (`set_identity_resolver`). The OSS default identity is the same for every network caller and can be chosen by header on loopback, so it is not treated as a principal. - If an installed identity resolver raises or returns no principal, the request fails closed (`resolve_authenticated_principal()` raises `UnresolvedPrincipalError` for an empty result): `compute_request_cache_partition()` logs a warning and returns `None`, and both handlers skip the response cache for that request (no lookup, no store). It never falls back to the credential-only partition, which tenants on one operator key would share. With no resolver installed, the credential-only partition is unchanged. - Both handlers compute the partition only when the response cache can be used (cache enabled and non-streaming), so streaming and cache-disabled requests do not call the identity resolver. - `partition` is a required keyword on `SemanticCache.get`, `set` and `_compute_key`, and on `compute_semantic_cache_key`. A future call site that forgets it fails immediately instead of silently sharing. - The `/v1/messages` and `/v1/chat/completions` handlers compute the partition once, next to the existing cache-key snapshot, and reuse it at store time so lookup and store agree. Other caches in the request path are not changed. The OpenAI Responses unit cache and the CCR retrieval store are content-addressed, so a hit requires already holding the content. CCR entries are not bound to a caller; that is a separate issue. The `/v1/compress` pipeline cache holds no user content, and the SDK `SemanticCache` is in-process for one caller. ## Behaviour change The proxy response cache no longer shares entries between callers that present different provider credentials or, with an identity resolver installed, different principals. - One developer with one key: same hit rate. - Deployments where callers send no provider credential and the proxy supplies the operator's key: same hit rate; they share the `anon` partition. - Shared proxy with per-caller keys: entries are no longer shared between keys. That is the fix. - Compatible upstream gateways that authenticate by `Cookie` or `Proxy-Authorization`: entries are no longer shared between sessions. - Callers whose only credential is a proxy-token `Authorization` header, or deployments using oauth2, share one partition unless an identity resolver is installed, because core cannot tell them apart. ## Tests `tests/test_proxy_response_cache_partition.py`: - The partition function: differs per credential and is stable for one credential; every credential and account header shape partitions; other headers do not fragment the cache; no credential and no principal gives the shared partition; it is keyed, not a plain hash; a principal separates callers sharing one credential. - `SemanticCache` refuses a call without a partition and keeps partitions apart. - End to end through the real Anthropic and OpenAI handlers: a second caller is never served the first caller's cached response, whether the credential is `x-api-key`/`Authorization`, `Cookie` or `Proxy-Authorization`. The `Cookie` and `Proxy-Authorization` cases fail without the latest change. With an identity resolver installed, callers on one operator key are partitioned. These end-to-end tests fail on `main`. - A resolver that raises, or returns an empty principal, yields no partition, and end to end (both handlers) callers on one operator key never share a cached response and nothing is stored. These fail without the fail-closed change. With no resolver installed, the partition is the credential-only one. - With the response cache disabled, neither handler calls the identity resolver. Existing cache tests now pass a fixed partition. The buffered-stream CCR test derives the same partition the handler computes. Manual run: two callers send the identical `/v1/messages` request with different `x-api-key` values through a proxy in front of a capture upstream. On `main` the second caller gets the first caller's answer and only the first key reaches the upstream. On this branch each caller gets its own answer, and a repeat by the first caller is still a cache hit. Not tested: multi-worker deployments (the cache and its key are per process, as before). ## Merge order / conflicts Part of a set. Suggested order: #3852 → #3891 → #3849 → #3860 → #3862 → #3863. Textual conflict: #3860 adds an import next to the one this PR adds in `handlers/anthropic.py` and `handlers/openai.py`. Whichever merges second keeps both imports. Revised 2026-10-04 after review: forwarded `Cookie` and `Proxy-Authorization` headers are now partition input (via the shared credential-header rule), so cookie-authenticated callers no longer share the anonymous partition. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3862" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: JD Davis <mxjerrett@gmail.com>
180 lines
6.6 KiB
Python
180 lines
6.6 KiB
Python
"""Regression tests for the proxy SemanticCache key (headroom/proxy/semantic_cache.py).
|
|
|
|
The key previously hashed only {model, messages}, so two requests with identical
|
|
messages but a different system prompt, tool set, or sampling config collided and
|
|
the second caller was served the first's response. These tests assert BOTH
|
|
directions:
|
|
|
|
- too loose -> the bug: different response-shaping inputs must produce different
|
|
keys (cross-request contamination).
|
|
- too tight -> a hit-rate regression (#327): truly-identical requests must still
|
|
hit, and a moved ``cache_control`` breakpoint must not fragment the key.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import pytest
|
|
|
|
from headroom.proxy.semantic_cache import SemanticCache
|
|
|
|
MESSAGES = [{"role": "user", "content": "hello"}]
|
|
MODEL = "claude-haiku-4-5"
|
|
|
|
|
|
def _key(cache: SemanticCache, **kw) -> str:
|
|
return cache._compute_key(MESSAGES, MODEL, partition="p_test", **kw)
|
|
|
|
|
|
# --- too loose: different inputs must NOT collide (the bug) --------------------
|
|
|
|
|
|
def test_different_system_distinct_keys():
|
|
cache = SemanticCache()
|
|
assert _key(cache, system="Answer only in French.") != _key(
|
|
cache, system="Answer only in English."
|
|
)
|
|
|
|
|
|
def test_different_tools_distinct_keys():
|
|
cache = SemanticCache()
|
|
tools_a = [{"name": "read", "description": "read a file"}]
|
|
tools_b = [{"name": "bash", "description": "run a command"}]
|
|
assert _key(cache, tools=tools_a) != _key(cache, tools=tools_b)
|
|
|
|
|
|
def test_tool_schema_cache_control_property_produces_distinct_key():
|
|
"""A user-defined schema property is not a prompt-cache annotation."""
|
|
tools_without = [{"name": "maintain", "input_schema": {"type": "object", "properties": {}}}]
|
|
tools_with = [
|
|
{
|
|
"name": "maintain",
|
|
"input_schema": {
|
|
"type": "object",
|
|
"properties": {
|
|
"cache_control": {
|
|
"type": "boolean",
|
|
"description": "Flush the application cache",
|
|
}
|
|
},
|
|
},
|
|
}
|
|
]
|
|
|
|
cache = SemanticCache()
|
|
assert _key(cache, tools=tools_without) != _key(cache, tools=tools_with)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"field,a,b",
|
|
[
|
|
# sampling
|
|
("temperature", 0.0, 1.0),
|
|
("top_p", 0.1, 0.9),
|
|
("top_k", 10, 40),
|
|
("max_tokens", 100, 200),
|
|
("stop", ["STOP"], ["HALT"]),
|
|
# OpenAI response-shaping (the #1473 review additions)
|
|
("tool_choice", "auto", "none"),
|
|
("response_format", {"type": "json_object"}, {"type": "text"}),
|
|
("parallel_tool_calls", True, False),
|
|
("seed", 1, 2),
|
|
("presence_penalty", 0.0, 1.5),
|
|
("frequency_penalty", 0.0, 1.5),
|
|
("logit_bias", {"50256": -100}, {"50256": 100}),
|
|
("n", 1, 2),
|
|
("logprobs", True, False),
|
|
("top_logprobs", 1, 5),
|
|
("reasoning_effort", "low", "high"),
|
|
("verbosity", "low", "high"),
|
|
("modalities", ["text"], ["text", "audio"]),
|
|
# Anthropic response-shaping
|
|
("thinking", {"type": "enabled", "budget_tokens": 1024}, {"type": "disabled"}),
|
|
("output_config", {"format": "json"}, {"format": "text"}),
|
|
],
|
|
)
|
|
def test_response_shaping_fields_distinct_keys(field, a, b):
|
|
cache = SemanticCache()
|
|
assert _key(cache, **{field: a}) != _key(cache, **{field: b})
|
|
|
|
|
|
# --- too tight: identical / canonically-equal inputs MUST hit -----------------
|
|
|
|
|
|
def test_identical_request_same_key():
|
|
cache = SemanticCache()
|
|
kw = {"system": "sys", "tools": [{"name": "t"}], "temperature": 0.5, "max_tokens": 50}
|
|
assert _key(cache, **kw) == _key(cache, **kw)
|
|
|
|
|
|
def test_legacy_call_stable_with_itself():
|
|
"""Backward-compat: a call passing no new fields is stable (existing callers)."""
|
|
cache = SemanticCache()
|
|
assert _key(cache) == _key(cache)
|
|
|
|
|
|
def test_cache_control_breakpoint_move_same_key():
|
|
"""Claude Code moves the cache_control breakpoint between turns; a moved
|
|
breakpoint on the system prompt must not fragment the key."""
|
|
cache = SemanticCache()
|
|
system_with_cc = [{"type": "text", "text": "sys", "cache_control": {"type": "ephemeral"}}]
|
|
system_without_cc = [{"type": "text", "text": "sys"}]
|
|
assert _key(cache, system=system_with_cc) == _key(cache, system=system_without_cc)
|
|
|
|
|
|
def test_tools_cache_control_ignored():
|
|
cache = SemanticCache()
|
|
tools_cc = [{"name": "t", "cache_control": {"type": "ephemeral"}}]
|
|
tools_plain = [{"name": "t"}]
|
|
assert _key(cache, tools=tools_cc) == _key(cache, tools=tools_plain)
|
|
|
|
|
|
def test_message_cache_control_breakpoint_move_same_key():
|
|
"""A moved cache_control breakpoint on a *message* must not fragment the key.
|
|
|
|
Messages are the primary key component and, on the Anthropic path, the most
|
|
common place a client (e.g. Claude Code) moves a breakpoint between turns.
|
|
cache_control is a prompt-caching directive that never changes the
|
|
completion, so the two requests must share a cache entry — previously only
|
|
system/tools breakpoints were stripped, so a message breakpoint missed.
|
|
"""
|
|
cache = SemanticCache()
|
|
messages_with_cc = [
|
|
{
|
|
"role": "user",
|
|
"content": [{"type": "text", "text": "hello", "cache_control": {"type": "ephemeral"}}],
|
|
}
|
|
]
|
|
messages_without_cc = [{"role": "user", "content": [{"type": "text", "text": "hello"}]}]
|
|
assert cache._compute_key(messages_with_cc, MODEL, partition="p_test") == cache._compute_key(
|
|
messages_without_cc, MODEL, partition="p_test"
|
|
)
|
|
|
|
|
|
def test_message_content_change_still_distinct_key():
|
|
"""Stripping cache_control must not collapse genuinely different messages."""
|
|
cache = SemanticCache()
|
|
a = [{"role": "user", "content": [{"type": "text", "text": "hello"}]}]
|
|
b = [{"role": "user", "content": [{"type": "text", "text": "goodbye"}]}]
|
|
assert cache._compute_key(a, MODEL, partition="p_test") != cache._compute_key(
|
|
b, MODEL, partition="p_test"
|
|
)
|
|
|
|
|
|
# --- behavioral get/set: collision prevented end to end -----------------------
|
|
|
|
|
|
async def test_get_set_collision_prevented():
|
|
"""Store under system A; fetching with system B is a MISS (no contamination),
|
|
fetching with system A is a HIT."""
|
|
cache = SemanticCache()
|
|
await cache.set(
|
|
MESSAGES, MODEL, b"french-body", {}, partition="p_test", system="Answer only in French."
|
|
)
|
|
|
|
miss = await cache.get(MESSAGES, MODEL, partition="p_test", system="Answer only in English.")
|
|
assert miss is None
|
|
|
|
hit = await cache.get(MESSAGES, MODEL, partition="p_test", system="Answer only in French.")
|
|
assert hit is not None
|
|
assert hit.response_body == b"french-body"
|