headroom/tests/test_openai_responses_traffic_learner.py
Abhay Singh f669149769
fix(proxy/openai): feed Codex WS traffic into the traffic learner (#2334)
## Description

Follow-up to the chat/completions ingestion work — this wires the Codex
`/v1/responses` **WebSocket** path into the traffic learner, the
remaining gap in #2060.

`handle_openai_responses_ws` (the transport newer Codex versions default
to) had no traffic-learner ingestion, so Codex subscription traffic
produced no learned patterns even with Learn enabled. Unlike the
one-shot HTTP path, a long-lived Codex WebSocket:

- resends the **full transcript** on every `response.create` frame, and
- replays it **wholesale on reconnect/resume**.

So naive per-turn ingestion would count the same tool result as evidence
over and over, and every reconnect would re-ingest the whole history.

## Fix

Add `_observe_openai_ws_response_create`, which dedups per connection by
tool-call id:

- A per-connection `ws_learner_seen_call_ids: set[str]` tracks which
tool-call ids have been observed on this WebSocket.
- The **first** `response.create` frame is a **baseline**: its
already-present transcript is recorded as seen but **not learned**, and
preference extraction is skipped. This is the replayed/initial history,
which may already have been learned on a prior connection.
- **Later** frames learn only the tool results whose call id first
appears after the baseline, then mark them seen. Preference extraction
(`on_messages`) runs on these frames (it already looks only at the most
recent messages).

On reconnect the client opens a fresh WebSocket and replays the
transcript in its first frame, which is baselined again, so it adds no
spurious evidence. It hooks both frame paths: the first-frame handler
seeds the baseline from the original client frame (parsed before memory
injection / compression), and `_maybe_compress_response_create_frame`
observes each subsequent frame.

To dedup by identity,
`TrafficLearner.extract_tool_results_from_messages` now also returns the
`call_id` (the `tool_use`/`tool_result` id, which
`_responses_input_to_learner_messages` already sets from the Responses
`call_id`). This is additive — existing callers that don't read it are
unaffected.

Relationship to the chat path: the `/v1/chat/completions` ingestion is a
separate change; together they cover HTTP chat, HTTP Responses (already
wired), and Codex WS. This PR is independent and branches off `main`.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] 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/memory/traffic_learner.py`:
`extract_tool_results_from_messages` now returns `call_id` for per-turn
dedup (additive).
- `headroom/proxy/handlers/openai.py`: add
`_observe_openai_ws_response_create` (per-connection dedup + baseline);
initialise `ws_learner_seen_call_ids`; observe the first frame as a
baseline and each subsequent `response.create` frame.
- `tests/test_openai_responses_traffic_learner.py`: add WS
dedup/baseline coverage (baseline records-not-learns, later frames learn
only new results, reconnect replay adds no evidence); update the
existing extractor-equality assertion to include `call_id`.
- `CHANGELOG.md`: Bug Fixes entry.

## Testing

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

### Test Output

```text
$ uvx ruff@0.15.17 check headroom/memory/traffic_learner.py headroom/proxy/handlers/openai.py tests/test_openai_responses_traffic_learner.py
All checks passed!
$ uvx ruff@0.15.17 format --check <same files + test_memory/test_traffic_learner.py>
all files already formatted
$ uvx mypy@1.20.2 --ignore-missing-imports headroom/proxy/handlers/openai.py
# no errors in the changed files (the one reported error is a pre-existing
# headroom/_subprocess.py:18 no-any-return, present on main with these edits stashed)
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12, `uvx ruff@0.15.17` / `uvx
mypy@1.20.2`. A full `pytest` OOMs this box (ML-stack import), so I
reproduced the dedup/baseline loop with a dependency-free asyncio script
and left the full pytest to CI.
- Exact command / steps: simulated a connection where the baseline frame
carries tool-call ids A,B; later frames replay A,B and append C, then D;
plus a reconnect whose first frame replays A,B,C,D.
- Observed result: baseline recorded A,B without learning; frame 2
learned only C; frame 3 learned only D (A/B/C never re-counted); the
reconnect's replayed transcript was baselined and learned nothing. The
added unit tests assert the same through the real handler method with a
recording learner.
- Not tested: a live Codex WebSocket session end to end; the added tests
drive `_observe_openai_ws_response_create` directly with a recording
learner and the real `_responses_input_to_learner_messages` + extractor.

## 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
- [ ] New and existing unit tests pass locally with my changes
- [x] I have updated the CHANGELOG.md if applicable

## Additional Notes

The "unit tests pass locally" box is unchecked because a local pytest
run imports the ML stack and OOMs this box; the added tests reuse the
existing `_RecordingLearner` harness (no real backend) and run under the
normal CI pytest job, and the dedup/baseline behavior is corroborated by
the standalone proof above. Design note: baselining the first frame
means a brand-new conversation's first-turn tool results are not learned
on that connection (subsequent turns are); this is the deliberate
trade-off the issue calls for to keep reconnect/resume from inflating
evidence.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-08-11 23:54:41 -05:00

221 lines
7.1 KiB
Python

from __future__ import annotations
import asyncio
from typing import Any
import httpx
from fastapi.testclient import TestClient
from headroom.memory.traffic_learner import TrafficLearner
from headroom.proxy.handlers.openai import (
OpenAIHandlerMixin,
_responses_input_to_learner_messages,
)
from headroom.proxy.server import ProxyConfig, create_app
class _CompletedResponseTransport(httpx.AsyncBaseTransport):
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
headers={"content-type": "application/json"},
json={
"id": "resp_test",
"object": "response",
"status": "completed",
"model": "gpt-5",
"output": [],
"usage": {"input_tokens": 10, "output_tokens": 1},
},
)
class _RecordingLearner:
def __init__(self) -> None:
self._backend = None
self._extractor = TrafficLearner(backend=None)
self.message_batches: list[list[dict[str, Any]]] = []
self.tool_results: list[dict[str, Any]] = []
def extract_tool_results_from_messages(
self,
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
return self._extractor.extract_tool_results_from_messages(messages)
async def on_tool_result(self, **tool_result: Any) -> None:
self.tool_results.append(tool_result)
async def on_messages(self, messages: list[dict[str, Any]]) -> None:
self.message_batches.append(messages)
def _responses_input() -> list[dict[str, Any]]:
return [
{
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "Always return compact JSON."}],
},
{
"type": "function_call",
"call_id": "call_1",
"name": "shell",
"arguments": '{"cmd":"missing-command"}',
},
{
"type": "function_call_output",
"call_id": "call_1",
"output": "command not found",
"status": "failed",
},
]
def test_responses_input_normalizes_messages_and_tool_results() -> None:
messages = _responses_input_to_learner_messages("Follow repository rules.", _responses_input())
learner = TrafficLearner(backend=None)
assert messages[0] == {"role": "system", "content": "Follow repository rules."}
assert messages[1] == {"role": "user", "content": "Always return compact JSON."}
assert learner.extract_tool_results_from_messages(messages) == [
{
"tool_name": "shell",
"input": {"cmd": "missing-command"},
"output": "command not found",
"is_error": True,
"call_id": "call_1",
}
]
def test_responses_input_does_not_promote_unknown_role_to_user() -> None:
messages = _responses_input_to_learner_messages(
None,
[
{
"type": "message",
"content": [{"type": "input_text", "text": "Never expose ambient UI."}],
},
{
"type": "message",
"role": "developer",
"content": [{"type": "input_text", "text": "Always follow runtime policy."}],
},
],
)
assert messages == [
{"role": "unknown", "content": "Never expose ambient UI."},
{"role": "developer", "content": "Always follow runtime policy."},
]
def test_responses_http_request_reaches_traffic_learner() -> None:
config = ProxyConfig(
optimize=False,
cache_enabled=False,
rate_limit_enabled=False,
cost_tracking_enabled=False,
log_requests=False,
ccr_inject_tool=False,
ccr_handle_responses=False,
ccr_context_tracking=False,
image_optimize=False,
)
app = create_app(config)
learner = _RecordingLearner()
proxy = app.state.proxy
proxy.traffic_learner = learner
proxy.http_client = httpx.AsyncClient(transport=_CompletedResponseTransport())
client = TestClient(app)
response = client.post(
"/v1/responses",
headers={"authorization": "Bearer test-token"},
json={"model": "gpt-5", "input": _responses_input(), "stream": False},
)
assert response.status_code == 200, response.text
assert len(learner.message_batches) == 1
assert learner.tool_results == [
{
"tool_name": "shell",
"tool_input": {"cmd": "missing-command"},
"tool_output": "command not found",
"is_error": True,
}
]
def _ws_frame(call_ids: list[str]) -> dict[str, Any]:
"""A response.create inner payload whose input carries one shell tool
round-trip per call id."""
input_items: list[dict[str, Any]] = []
for cid in call_ids:
input_items.append(
{"type": "function_call", "call_id": cid, "name": "shell", "arguments": "{}"}
)
input_items.append(
{
"type": "function_call_output",
"call_id": cid,
"output": "ok",
"status": "completed",
}
)
return {"input": input_items}
def test_ws_response_create_baselines_and_dedups_replayed_transcript() -> None:
handler = OpenAIHandlerMixin()
learner = _RecordingLearner()
handler.traffic_learner = learner
seen: set[str] = set()
# First frame is the baseline: A and B are recorded as seen but NOT learned,
# and preference extraction is skipped.
asyncio.run(
handler._observe_openai_ws_response_create(
_ws_frame(["A", "B"]), seen_call_ids=seen, baseline=True, request_id="r"
)
)
assert learner.tool_results == []
assert learner.message_batches == []
assert seen == {"A", "B"}
# Second frame replays A, B and appends C -> only C is learned.
asyncio.run(
handler._observe_openai_ws_response_create(
_ws_frame(["A", "B", "C"]), seen_call_ids=seen, baseline=False, request_id="r"
)
)
assert len(learner.tool_results) == 1
assert seen == {"A", "B", "C"}
assert len(learner.message_batches) == 1
# Third frame replays A, B, C and appends D -> only D is learned.
asyncio.run(
handler._observe_openai_ws_response_create(
_ws_frame(["A", "B", "C", "D"]), seen_call_ids=seen, baseline=False, request_id="r"
)
)
assert len(learner.tool_results) == 2 # C then D, never A/B again
assert seen == {"A", "B", "C", "D"}
def test_ws_reconnect_replay_adds_no_evidence() -> None:
# A reconnect is a fresh connection: its first frame replays the whole
# transcript, which is baselined, so nothing is re-learned.
handler = OpenAIHandlerMixin()
learner = _RecordingLearner()
handler.traffic_learner = learner
seen: set[str] = set()
asyncio.run(
handler._observe_openai_ws_response_create(
_ws_frame(["A", "B", "C", "D"]), seen_call_ids=seen, baseline=True, request_id="r"
)
)
assert learner.tool_results == []
assert seen == {"A", "B", "C", "D"}