headroom/tests/test_ccr_response_handler_openai_responses.py
Rod Boev 62cd3072a2
feat(ccr): wire retrieve-tool interception into OpenAI Responses handler (#1898)
## Description

Refs #1877. `handle_openai_responses` (the `/v1/responses` HTTP handler)
had zero CCR / `headroom_retrieve` wiring, so a retrieve `function_call`
in a Responses API reply passed straight through to the client instead
of being resolved server-side, unlike the parallel chat-completions
backend path (`handle_openai_chat`, ~2775-2848), which already
intercepts `headroom_retrieve` tool calls via
`ccr_response_handler.has_ccr_tool_calls()` / `handle_response()`.

This PR is scoped to the core interception gap only. The issue's
proposals A (egress scrubber) and B/C (event-level SSE parsing/splicing
for true mid-stream interception) are out of scope here; the streaming
case is instead handled by forcing a buffered (non-streaming) upstream
call when `headroom_retrieve` is offered, matching the existing
buffered-CCR pattern in the Anthropic handler.

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/ccr/response_handler.py`: added an `"openai_responses"`
provider branch to `CCRResponseHandler`; `_extract_tool_calls` reads
flat `function_call` items from the top-level `output[]` array,
tool-call IDs key off `call_id`, and `_extract_assistant_message` /
`_create_tool_result_message` return sentinel-keyed item lists that
`handle_response()` extends into the running item history.
- `headroom/ccr/tool_injection.py`: added a `parse_tool_call` branch for
`"openai_responses"` where name and arguments are flat on the item.
- `headroom/proxy/handlers/openai.py`: detects non-streaming
`headroom_retrieve` function calls and runs
`ccr_response_handler.handle_response()` with a stateless continuation
that resends the full `input[]` item history.
- `headroom/proxy/handlers/openai.py`: forces `stream:true` requests
with `headroom_retrieve` available through a buffered `stream:false`
upstream call, resolves retrieval server-side, then reconstructs a
minimal Responses SSE stream for the client.
- `headroom/proxy/handlers/openai.py`: treats `ccr_response_handler` as
optional on `OpenAIHandlerMixin` consumers, so handlers without CCR
support keep the existing Codex routing, streaming, header stripping,
memory timeout, and compression fail-open behavior.
- Non-CCR streaming requests are unaffected; they still go through
`_stream_response()` as before.

## Testing

- [x] Unit tests pass (`uv run pytest
tests/test_ccr_response_handler_openai_responses.py -q`)
- [x] Integration tests pass (`uv run pytest
tests/test_proxy/test_openai_responses_ccr.py -q`)
- [x] Regression tests pass (`uv run pytest
tests/test_openai_codex_routing.py -q`)
- [x] Linting passes (`uv run ruff check
headroom/proxy/handlers/openai.py tests/test_openai_codex_routing.py
tests/test_proxy/test_openai_responses_ccr.py
tests/test_ccr_response_handler_openai_responses.py`)
- [x] New tests added for new functionality when applicable
- [x] Manual testing performed

### Test Output

```text
$ uv run pytest tests/test_openai_codex_routing.py -q
tests\test_openai_codex_routing.py ....................                  [100%]
20 passed in 0.51s

$ uv run pytest tests/test_proxy/test_openai_responses_ccr.py tests/test_ccr_response_handler_openai_responses.py -q
tests\test_proxy\test_openai_responses_ccr.py ....                       [ 25%]
tests\test_ccr_response_handler_openai_responses.py ............         [100%]
16 passed, 1 warning in 27.51s

$ uv run ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_routing.py tests/test_proxy/test_openai_responses_ccr.py tests/test_ccr_response_handler_openai_responses.py
All checks passed!
```

## Real Behavior Proof

- Environment: Windows, Python 3.12 via uv-managed venv, local PR
worktree on branch `pr/1877-ccr-responses-interception`, no live LLM
provider needed because the tests stub upstream HTTP and CCR
continuation behavior.
- Exact command / steps: Ran `uv run pytest
tests/test_openai_codex_routing.py -q` to reproduce the CI-failing Codex
routing surface after the optional-handler fix; ran `uv run pytest
tests/test_proxy/test_openai_responses_ccr.py
tests/test_ccr_response_handler_openai_responses.py -q` to cover the
positive Responses CCR interception path; ran targeted Ruff on the
touched handler and related tests.
- Observed result: Codex routing tests that previously failed with
`AttributeError: '_DummyOpenAIHandler' object has no attribute
'ccr_response_handler'` now pass; Responses CCR still detects and
resolves `headroom_retrieve` when a real proxy installs
`ccr_response_handler`; non-CCR streaming requests still route through
`_stream_response()`.
- Not tested: true event-level mid-stream Responses SSE splicing and
client-bound egress marker scrubbing are out of scope for this PR and
remain future work from issue #1877's broader proposals.

## 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
- [ ] I have updated the CHANGELOG.md if applicable

## Additional Notes

No documentation or changelog update was made because this is internal
proxy CCR behavior, not a user-facing command or configuration change.
2026-07-09 09:41:06 -04:00

245 lines
8.4 KiB
Python

"""Tests for CCR response handling of the OpenAI Responses API shape.
Covers #1877: `CCRResponseHandler` previously only understood "anthropic",
"openai" (chat completions), and "google" response shapes. Responses API
function calls are flat `function_call` items in a top-level `output[]`
array (not nested under `choices[].message.tool_calls`), and results are
`function_call_output` items appended to `input[]` rather than a single
role/content message — these tests exercise the new "openai_responses"
provider branch end to end.
"""
from __future__ import annotations
import json
import pytest
from headroom.cache.compression_store import (
get_compression_store,
reset_compression_store,
)
from headroom.ccr.response_handler import CCRResponseHandler, CCRToolResult
from headroom.ccr.tool_injection import CCR_TOOL_NAME, parse_tool_call
@pytest.fixture(autouse=True)
def reset_store():
reset_compression_store()
yield
reset_compression_store()
def _function_call_response(hash_key: str, call_id: str = "call_abc") -> dict:
return {
"id": "resp_1",
"object": "response",
"status": "completed",
"output": [
{
"type": "reasoning",
"id": "rs_1",
"summary": [],
},
{
"type": "function_call",
"id": "fc_1",
"call_id": call_id,
"name": CCR_TOOL_NAME,
"arguments": json.dumps({"hash": hash_key}),
},
],
"usage": {"input_tokens": 50, "output_tokens": 10},
}
class TestOpenAIResponsesDetection:
def test_detect_function_call_tool_call(self) -> None:
handler = CCRResponseHandler()
response = _function_call_response("abc123def456abc123def456")
assert handler.has_ccr_tool_calls(response, "openai_responses")
def test_no_false_positive_for_other_function_call(self) -> None:
handler = CCRResponseHandler()
response = {
"output": [
{
"type": "function_call",
"id": "fc_1",
"call_id": "call_1",
"name": "some_other_tool",
"arguments": "{}",
}
]
}
assert not handler.has_ccr_tool_calls(response, "openai_responses")
def test_no_false_positive_for_message_only_output(self) -> None:
handler = CCRResponseHandler()
response = {
"output": [
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "hi"}],
}
]
}
assert not handler.has_ccr_tool_calls(response, "openai_responses")
def test_empty_output(self) -> None:
handler = CCRResponseHandler()
assert not handler.has_ccr_tool_calls({"output": []}, "openai_responses")
assert not handler.has_ccr_tool_calls({}, "openai_responses")
class TestOpenAIResponsesParsing:
def test_parse_extracts_call_id_not_item_id(self) -> None:
"""`call_id` (not the function_call item's own `id`) matches the
`function_call_output.call_id` the continuation must echo back."""
handler = CCRResponseHandler()
response = _function_call_response("abc123def456abc123def456", call_id="call_xyz")
ccr_calls, other_calls = handler._parse_ccr_tool_calls(response, "openai_responses")
assert len(ccr_calls) == 1
assert ccr_calls[0].tool_call_id == "call_xyz"
assert ccr_calls[0].hash_key == "abc123def456abc123def456"
assert not other_calls
def test_parse_tool_call_direct(self) -> None:
"""`parse_tool_call` reads flat name/arguments, not a nested `function` key."""
tool_call = {
"type": "function_call",
"call_id": "call_1",
"name": CCR_TOOL_NAME,
"arguments": '{"hash": "abc123def456abc123def456"}',
}
assert parse_tool_call(tool_call, "openai_responses") == "abc123def456abc123def456"
def test_parse_tool_call_rejects_other_names(self) -> None:
tool_call = {
"type": "function_call",
"call_id": "call_1",
"name": "read_file",
"arguments": '{"path": "/etc/config"}',
}
assert parse_tool_call(tool_call, "openai_responses") is None
def test_parse_tool_call_malformed_arguments(self) -> None:
tool_call = {
"type": "function_call",
"call_id": "call_1",
"name": CCR_TOOL_NAME,
"arguments": "not json",
}
assert parse_tool_call(tool_call, "openai_responses") is None
class TestOpenAIResponsesMessageShaping:
def test_extract_assistant_message_echoes_full_output_array(self) -> None:
handler = CCRResponseHandler()
response = _function_call_response("abc123def456abc123def456")
result = handler._extract_assistant_message(response, "openai_responses")
assert result == {"_openai_responses_output_items": response["output"]}
def test_create_tool_result_message_uses_call_id(self) -> None:
handler = CCRResponseHandler()
results = [
CCRToolResult(tool_call_id="call_xyz", content='{"data": "x"}', success=True),
CCRToolResult(tool_call_id="call_abc", content='{"data": "y"}', success=True),
]
message = handler._create_tool_result_message(results, "openai_responses")
assert "_openai_responses_tool_results" in message
items = message["_openai_responses_tool_results"]
assert len(items) == 2
assert items[0] == {
"type": "function_call_output",
"call_id": "call_xyz",
"output": '{"data": "x"}',
}
class TestOpenAIResponsesHandleResponse:
@pytest.mark.asyncio
async def test_handle_response_resolves_retrieve_and_extends_input(self) -> None:
store = get_compression_store()
original = json.dumps([{"id": i} for i in range(30)])
hash_key = store.store(original=original, compressed="[]", original_item_count=30)
handler = CCRResponseHandler()
initial_response = _function_call_response(hash_key, call_id="call_1")
final_response = {
"id": "resp_2",
"object": "response",
"status": "completed",
"output": [
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "Here are all 30 items."}],
}
],
}
captured_calls: list[list[dict]] = []
async def mock_api_call(items, tools):
captured_calls.append(items)
return final_response
result = await handler.handle_response(
initial_response,
[{"role": "user", "content": "get the data"}],
None,
mock_api_call,
"openai_responses",
)
assert result == final_response
assert len(captured_calls) == 1
# Original input item + the two echoed output items (reasoning +
# function_call) + the function_call_output — extended, not
# appended as a single blob.
sent_items = captured_calls[0]
assert sent_items[0] == {"role": "user", "content": "get the data"}
assert {"type": "function_call", "name": CCR_TOOL_NAME} in [
{"type": i.get("type"), "name": i.get("name")}
for i in sent_items
if i.get("type") == "function_call"
]
tool_outputs = [i for i in sent_items if i.get("type") == "function_call_output"]
assert len(tool_outputs) == 1
assert tool_outputs[0]["call_id"] == "call_1"
@pytest.mark.asyncio
async def test_handle_response_no_ccr_passthrough(self) -> None:
handler = CCRResponseHandler()
response = {
"output": [
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "no tool call here"}],
}
]
}
async def mock_api_call(items, tools):
raise AssertionError("should not be called")
result = await handler.handle_response(
response, [], None, mock_api_call, "openai_responses"
)
assert result == response