fix(ccr): send batch continuations to the upstream the batch was submitted to (#4848)

## Description

When a batch result needs a CCR continuation, `BatchResultProcessor`
made the follow-up call to hard-coded public hosts (`api.anthropic.com`,
`api.openai.com`, `generativelanguage.googleapis.com`). The upstream the
batch was actually submitted to is stored in
`BatchContext.api_base_url`, written by `_store_anthropic_batch_context`
(`ANTHROPIC_API_URL`) and `_store_google_batch_context`
(`GEMINI_API_URL`), but nothing ever read it. With a custom base URL or
gateway, the continuation sent that upstream's stored credential, the
conversation and the retrieved CCR originals to the public host.

Continuations now go to `BatchContext.api_base_url`. They fall back to
the public host only when no upstream was recorded. For Gemini the key
now goes in the `x-goog-api-key` header instead of `?key=` in the URL,
so it stays out of URLs, request logs and `HTTPStatusError` text.

Behaviour change for users: none for default setups (the recorded
upstream is the public host). Batches submitted through a custom
upstream now get their continuations sent there too.

Fix adapted from a proposal by HetCreep.

## Type of Change

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

## Changes Made

- `headroom/ccr/batch_processor.py`: new `_continuation_base_url()`
(recorded upstream first, then the public default; trailing `/`
stripped). The Anthropic, OpenAI and Google continuations use it. Gemini
sends its key in `x-goog-api-key`.
- `tests/test_ccr_batch_processor.py`: one test per provider. Each
checks the request URL and the auth header when an upstream was
recorded, and for Gemini that the key is not in the URL.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
# new tests against origin/main (c21b0813)
$ pytest tests/test_ccr_batch_processor.py
FAILED ...::TestContinuationCalls::test_anthropic_continuation_uses_configured_api_base_url
FAILED ...::TestContinuationCalls::test_openai_continuation_uses_configured_api_base_url
FAILED ...::TestContinuationCalls::test_google_continuation_uses_configured_api_base_url_and_header_key
========================= 3 failed, 45 passed in 9.67s =========================

# this branch: processor tests + every tests/*batch* file
$ pytest tests/test_ccr_batch_processor.py tests/*batch*
======================= 130 passed, 14 skipped in 39.39s =======================

$ ruff check / ruff format --check (0.17.3): All checks passed!
$ mypy headroom/ccr/batch_processor.py --ignore-missing-imports
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: macOS, Python 3.12. A real `BatchResultProcessor` with a
real `httpx.AsyncClient` on an `httpx.MockTransport` that records
requests (no network).
- Exact command / steps: for each provider,
`_make_continuation_call(...)` with `BatchContext(api_key="demo-key",
api_base_url="http://127.0.0.1:9/gateway")`. Print the recorded request
URL.
- Observed result:
```text
origin/main:
anthropic -> https://api.anthropic.com/v1/messages
openai    -> https://api.openai.com/v1/chat/completions
google    -> https://generativelanguage.googleapis.com/v1beta/models/m:generateContent  key-in-url=True
this branch:
anthropic -> http://127.0.0.1:9/gateway/v1/messages
openai    -> http://127.0.0.1:9/gateway/v1/chat/completions
google    -> http://127.0.0.1:9/gateway/v1beta/models/m:generateContent  key-in-url=False
```
- Real HTTP server check (this branch): a local `http.server` listener
as the "gateway", a real `httpx.AsyncClient` (no mock transport),
`api_base_url=http://127.0.0.1:<port>/gateway`, one continuation per
provider:
```text
anthropic call returned
openai    call returned
google    call returned
local gateway received: [('/gateway/v1/messages', {'x-api-key': 'demo-key'}),
  ('/gateway/v1/chat/completions', {'authorization': 'Bearer demo-key'}),
  ('/gateway/v1beta/models/m:generateContent', {'x-goog-api-key': 'demo-key'})]
```
- Not tested: a live batch against a real provider or gateway.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: see Description
- Kill switch / disable path: none needed
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR

## Review Readiness

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

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

Out of scope here: Gemini batch *create* in
`headroom/proxy/handlers/batch.py` still moves `x-goog-api-key` into
`?key=` on the URL. It goes to the configured `GEMINI_API_URL`, so this
is about the key showing up in URLs, not about where it is sent. Worth a
separate follow-up.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Tejas Chopra
2026-11-14 10:45:48 +05:30
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent e15e342d9b
commit 5f82080329
2 changed files with 123 additions and 6 deletions
+21 -6
View File
@@ -307,6 +307,19 @@ class BatchResultProcessor:
else:
raise ValueError(f"Unknown provider: {provider}")
def _continuation_base_url(self, provider: str, batch_context: BatchContext) -> str:
"""Base URL for a continuation call.
The proxy records the resolved provider target (``ANTHROPIC_TARGET_API_URL``,
``GEMINI_TARGET_API_URL``) in ``BatchContext.api_base_url`` when it submits
the batch, and the stored credential belongs to that target. A continuation
that ignores it sends the credential, the conversation and the retrieved CCR
originals to the public provider host instead. The public host is only the
fallback for a context that never recorded a target.
"""
base = batch_context.api_base_url or self.api_urls[provider]
return base.rstrip("/")
async def _anthropic_continuation(
self,
messages: list[dict[str, Any]],
@@ -315,7 +328,7 @@ class BatchResultProcessor:
batch_context: BatchContext,
) -> dict[str, Any]:
"""Make Anthropic continuation call."""
url = f"{self.api_urls['anthropic']}/v1/messages"
url = f"{self._continuation_base_url('anthropic', batch_context)}/v1/messages"
headers = {
"Content-Type": "application/json",
@@ -368,7 +381,7 @@ class BatchResultProcessor:
batch_context: BatchContext,
) -> dict[str, Any]:
"""Make OpenAI continuation call."""
url = f"{self.api_urls['openai']}/v1/chat/completions"
url = f"{self._continuation_base_url('openai', batch_context)}/v1/chat/completions"
headers = {
"Content-Type": "application/json",
@@ -406,12 +419,14 @@ class BatchResultProcessor:
and 'parts' format for messages. Tools are already native Google Tool objects.
"""
model = request_context.model
url = f"{self.api_urls['google']}/v1beta/models/{model}:generateContent"
if batch_context.api_key:
url = f"{url}?key={batch_context.api_key}"
base = self._continuation_base_url("google", batch_context)
url = f"{base}/v1beta/models/{model}:generateContent"
headers = {"Content-Type": "application/json"}
if batch_context.api_key:
# A header, not `?key=`: a key in the URL lands in request logs and in
# the text of the HTTPStatusError raised below.
headers["x-goog-api-key"] = batch_context.api_key
# Convert messages to Google format (contents with parts)
contents = self._messages_to_google_contents(messages)
+102
View File
@@ -585,6 +585,108 @@ class TestContinuationCalls:
assert "Bearer sk-test123" in call_args.kwargs["headers"]["Authorization"]
assert call_args.kwargs["json"]["model"] == "gpt-4"
@pytest.mark.asyncio
async def test_anthropic_continuation_uses_configured_api_base_url(self):
"""The continuation goes to the target recorded at submission, not api.anthropic.com."""
mock_response = MagicMock()
mock_response.json.return_value = {"content": [{"type": "text", "text": "Final answer"}]}
mock_response.raise_for_status = MagicMock()
http_client = AsyncMock(spec=httpx.AsyncClient)
http_client.post.return_value = mock_response
processor = BatchResultProcessor(http_client)
request_context = BatchRequestContext(
custom_id="req_1",
messages=[{"role": "user", "content": "Hello"}],
model="claude-3-opus-20240229",
extras={"max_tokens": 1000},
)
batch_context = BatchContext(
batch_id="batch_123",
provider="anthropic",
api_key="gateway-credential",
api_base_url="https://llm-gateway.example.test",
)
await processor._anthropic_continuation(
[{"role": "user", "content": "Hello"}], None, request_context, batch_context
)
call_args = http_client.post.call_args
assert call_args.args[0] == "https://llm-gateway.example.test/v1/messages"
assert call_args.kwargs["headers"]["x-api-key"] == "gateway-credential"
@pytest.mark.asyncio
async def test_openai_continuation_uses_configured_api_base_url(self):
"""A trailing slash on the recorded target does not double the separator."""
mock_response = MagicMock()
mock_response.json.return_value = {"choices": [{"message": {"content": "Final answer"}}]}
mock_response.raise_for_status = MagicMock()
http_client = AsyncMock(spec=httpx.AsyncClient)
http_client.post.return_value = mock_response
processor = BatchResultProcessor(http_client)
request_context = BatchRequestContext(
custom_id="req_1",
messages=[{"role": "user", "content": "Hello"}],
model="gpt-4",
)
batch_context = BatchContext(
batch_id="batch_123",
provider="openai",
api_key="sk-test123",
api_base_url="https://llm-gateway.example.test/",
)
await processor._openai_continuation(
[{"role": "user", "content": "Hello"}], None, request_context, batch_context
)
call_args = http_client.post.call_args
assert call_args.args[0] == "https://llm-gateway.example.test/v1/chat/completions"
assert call_args.kwargs["headers"]["Authorization"] == "Bearer sk-test123"
@pytest.mark.asyncio
async def test_google_continuation_uses_configured_api_base_url_and_header_key(self):
"""Gemini: the recorded target is used and the key travels in a header, not the URL."""
mock_response = MagicMock()
mock_response.json.return_value = {
"candidates": [{"content": {"role": "model", "parts": [{"text": "Final answer"}]}}]
}
mock_response.raise_for_status = MagicMock()
http_client = AsyncMock(spec=httpx.AsyncClient)
http_client.post.return_value = mock_response
processor = BatchResultProcessor(http_client)
request_context = BatchRequestContext(
custom_id="req_1",
messages=[{"role": "user", "content": "Hello"}],
model="gemini-2.5-flash",
)
batch_context = BatchContext(
batch_id="batch_123",
provider="google",
api_key="gemini-gateway-key",
api_base_url="https://gemini-gateway.example.test",
)
await processor._google_continuation(
[{"role": "user", "content": "Hello"}], None, request_context, batch_context
)
call_args = http_client.post.call_args
assert call_args.args[0] == (
"https://gemini-gateway.example.test/v1beta/models/gemini-2.5-flash:generateContent"
)
assert "gemini-gateway-key" not in call_args.args[0]
assert call_args.kwargs["headers"]["x-goog-api-key"] == "gemini-gateway-key"
@pytest.mark.asyncio
@pytest.mark.parametrize("client_tools", ["functions", "siblings", "none"])
async def test_google_batch_create_to_results_retains_injected_native_tools(