Files
headroom/tests/test_openai_responses_traffic_learner.py
957ab1830d fix(memory): fail close unresolved project operations (#2637)
## Description

An unresolved project scope still carried the global database path.
Custom-tool, native-memory, and learner paths could therefore initialize
or reuse global state after context injection had already skipped.

This PR makes unresolved project scopes backend-less and checks request
scope before any memory or learning operation. Optional memory failures
still allow the main model request to continue.

This supersedes #502 at reviewed commit
`9d45c11233959815da651393c3b3737359497882` and preserves attribution to
@chopratejas in the commit trailer.

## 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

- Remove the database path and backend from unresolved project scopes.
- Gate injection, custom tools, native operations, and learning before
backend acquisition.
- Pass request context through OpenAI and Anthropic memory-tool paths.
- Preserve explicit global/user modes and fail-open model traffic.

## Testing

### October 27 combined-tree refresh

Merged upstream `17d38e5699b7d7c69ac6addcd762f39e42dd7f00` into
`5f625dba9bccee6b38ec2e9de6c04023c29358e7`. No manual source repairs
were needed.

- Focused memory, routing, WebSocket, Anthropic, and gateway tests:
**308 passed, 2 skipped**.
- The two skips cover the macOS non-UTF8 symlink fixture and optional
native tool-search extension.
- The Python pre-push test list, invoked directly against the built
extension: **177 passed, 4 skipped**.
- The real-file proof below passed again on this combined tree.
- Independent static review found no integration blocker.
- Ruff, whitespace, and commit hooks passed, including mypy and the new
commit's commitlint check.
- Full `make ci-precheck` is not green: Rust 1.99.1 reports
`clippy::question_mark` in
`crates/headroom-core/src/ccr/backends/in_memory.rs:163`. The same
command fails on clean upstream `17d38e56`.
- The Python wrapper requires `pip`, absent from this uv environment.
Its test list was run directly after `uv sync` built the extension.
- The history-wide commitlint target rejects an older commit footer. The
new merge commit passed its commit hook.
- The push hook was bypassed for these documented limitations. Hosted
qualification for the new head remains required.

The focused command below was extended with
`tests/gateway/test_hook_tool_growth.py
tests/gateway/test_native_deferral.py
tests/gateway/test_tool_compaction_accounting.py`.

### October 25 validation

Current-main refresh: `ba3320e49f202c5880e4ef8e28efe810b78eeb07`, with
`3fef15d376d9899f77a28464e2e91f8b99514930` merged as the second parent.

- [x] Focused regression tests pass
- [x] Ruff lint and format checks pass for all ten PR files
- [x] PR diff whitespace check passes
- [ ] Type checking rerun for this refresh
- [x] Real-file behavior proof completed
- [x] Independent review found no remaining integration issue

The merge required no manual code repairs. No dependency or API changes
were added to the PR.

### Exact commands

```bash
uv sync --frozen --extra dev --extra proxy
uv run --frozen --extra dev --extra proxy python -m pytest tests/test_memory_storage_router.py tests/test_memory_handler_project_isolation.py tests/test_memory_handler_native_ops.py tests/test_memory_decision.py tests/test_memory_decision_policy.py tests/test_openai_codex_routing.py tests/test_openai_codex_ws_lifecycle.py tests/test_codex_ws_per_frame_memory.py tests/test_openai_responses_traffic_learner.py tests/test_anthropic_buffered_memory_continuation.py tests/test_memory_handler_concurrent_init.py -q
uv run --frozen --extra dev --extra proxy ruff check $(git diff --name-only 3fef15d3...HEAD)
uv run --frozen --extra dev --extra proxy ruff format --check $(git diff --name-only 3fef15d3...HEAD)
git diff --check 3fef15d3...HEAD
```

### Test Output

```text
259 passed, 1 skipped, 1 warning in 27.35s
All checks passed!
10 files already formatted
```

The skip is the non-UTF8 symlink fixture, which this macOS filesystem
cannot create. The warning is an existing Starlette/httpx deprecation.

The native extension was built from the combined source. These results
replace the earlier PR-only test counts for this refresh.

## Real Behavior Proof

I ran this on macOS 27.0.1 with Python 3.14.5 at
`ba3320e49f202c5880e4ef8e28efe810b78eeb07`.

The script uses the actual router and memory handler, with no mocked
backend. It creates a temporary SQLite canary table and native-memory
file.

A request without project identity returns no backend or database path.
Context lookup, five custom tools, six native commands, and Anthropic
tool dispatch skip memory access.

The script checks that the backend remains uninitialized, no project
backend is cached, and file paths and byte hashes remain unchanged. It
also reads the SQLite canary afterward.

This proves rejection before backend access. The canary database is not
a populated Headroom memory schema, so this does not demonstrate
resolved-project retrieval.

No provider request, model-request forwarding, live proxy, service
restart, or native Windows/Linux execution was tested by this script.
Temporary canary files are removed automatically.

### Reproduce

Save the script below as `memory-behavior-proof.py` in the repository
root after running the environment setup above.

```bash
HEADROOM_WORKSPACE_DIR="$PWD/proof-workspace" HEADROOM_CONFIG_DIR="$PWD/proof-config" HEADROOM_SETTINGS_PATH="$PWD/proof-settings.json" .venv/bin/python -u memory-behavior-proof.py
```

<details>
<summary>Executable script</summary>

```python
"""Check unresolved memory scope using real files and production handlers."""
import asyncio
import hashlib
import json
import os
from pathlib import Path
import sqlite3
import tempfile

os.environ["HEADROOM_BEACON"] = "off"
os.environ["HEADROOM_TELEMETRY"] = "off"
os.environ["HEADROOM_OFFLINE"] = "1"

from headroom.memory.storage_router import MemoryStorageMode, RequestContext
from headroom.proxy.memory_handler import MemoryConfig, MemoryHandler, MemoryMode


def snapshot(root):
    return {
        str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest()
        for path in root.rglob("*") if path.is_file()
    }


async def exercise(root):
    database = root / "memory.db"
    with sqlite3.connect(database) as connection:
        connection.execute("CREATE TABLE canary (content TEXT)")
        connection.execute("INSERT INTO canary VALUES ('private-existing-memory')")
    native_dir = root / "native"
    native_dir.mkdir()
    (native_dir / "canary.txt").write_text("private-existing-memory\n", encoding="utf-8", newline="\n")
    handler = MemoryHandler(MemoryConfig(
        enabled=True, backend="local", db_path=str(database),
        storage_root=str(root / "projects"), storage_mode=MemoryStorageMode.PROJECT,
        inject_context=True, mode=MemoryMode.AUTO_TAIL, use_native_tool=True,
        native_memory_dir=str(native_dir),
    ))
    before = snapshot(root)
    ctx = RequestContext(headers={}, system_prompt="You are helpful.", base_user_id="alice")
    backend, scope = handler._router.backend_for(ctx)
    assert backend is None and scope.db_path is None and scope.project_key is None
    print(f"scope: project_key={scope.project_key}, db_path={scope.db_path}, backend={backend}")
    context = await handler.search_and_format_context(
        "alice", [{"role": "user", "content": "Find my private memory"}], ctx,
    )
    assert context is None
    print(f"context lookup: {context}")
    expected = {"status": "skipped", "reason": "project_unresolved"}
    tools = {
        "memory_save": {"content": "must not persist"},
        "memory_search": {"query": "private-existing-memory"},
        "memory_update": {"memory_id": "m1", "new_content": "must not update"},
        "memory_delete": {"memory_id": "m1"},
        "memory_list": {},
    }
    for name, arguments in tools.items():
        result = json.loads(await handler._execute_memory_tool(name, arguments, "alice", request_context=ctx))
        assert result == expected
        print(f"{name}: {json.dumps(result, sort_keys=True)}")
    for command in ("view", "create", "str_replace", "insert", "delete", "rename"):
        arguments = {"command": command, "path": "/memories/canary.txt",
                     "file_text": "must not persist", "old_str": "private", "new_str": "public",
                     "insert_line": 0, "insert_text": "must not persist",
                     "old_path": "/memories/canary.txt", "new_path": "/memories/renamed.txt"}
        result = json.loads(await handler._execute_native_memory_tool(arguments, "alice", request_context=ctx))
        assert result == expected
        print(f"native {command}: {json.dumps(result, sort_keys=True)}")
    results = await handler.handle_memory_tool_calls({"content": [
        {"type": "tool_use", "id": "native-create", "name": "memory",
         "input": {"command": "create", "path": "/memories/canary.txt", "file_text": "must not persist"}},
        {"type": "tool_use", "id": "custom-save", "name": "memory_save",
         "input": {"content": "must not persist"}},
    ]}, "alice", "anthropic", request_context=ctx)
    assert len(results) == 2 and all(json.loads(item["content"]) == expected for item in results)
    print("Anthropic tool dispatch: both calls skipped")
    assert not handler.initialized and handler._backend is None and not handler._router._backends
    assert snapshot(root) == before
    with sqlite3.connect(database) as connection:
        assert connection.execute("SELECT content FROM canary").fetchall() == [("private-existing-memory",)]
    print("backend initialization: false; cached project backends: 0")
    print("SQLite and native files: byte hashes unchanged; no files added or removed")
    print("Provider traffic and model-request forwarding: not exercised by this proof")


with tempfile.TemporaryDirectory(prefix="headroom-pr2637-proof-") as directory:
    asyncio.run(exercise(Path(directory)))
print("Cleanup: temporary canary files removed")
```

</details>

<details>
<summary>Captured output</summary>

```text
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
scope: project_key=None, db_path=None, backend=None
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
context lookup: None
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
memory_save: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
memory_search: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
memory_update: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
memory_delete: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
memory_list: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
native view: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
native create: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
native str_replace: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
native insert: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
native delete: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
native rename: {"reason": "project_unresolved", "status": "skipped"}
event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).'
Anthropic tool dispatch: both calls skipped
backend initialization: false; cached project backends: 0
SQLite and native files: byte hashes unchanged; no files added or removed
Provider traffic and model-request forwarding: not exercised by this proof
Cleanup: temporary canary files removed
```

</details>

## Runtime Rollout Safety

- Rollout-managed feature(s): Project-scoped memory injection, tools,
native operations, and traffic learning.
- Minimum rollout channel: Stable/default.
- Stable/default behavior changed: Unresolved project requests skip
memory and learning instead of acquiring the global backend.
- Kill switch / disable path: Run without `--memory`; use `--no-learn`
to disable traffic learning.
- Unsafe override required: No.
- Qualification impact: Project memory isolation, explicit global/user
modes, and fail-open model traffic.
- Rollback path: Revert this PR. No schema or data migration is
required.

## 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
- [x] Documentation changes are not required for this internal safety
fix
- [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)

Not applicable.

## Additional Notes

Waiting follow-up: [project-scoped
TrafficLearner](https://github.com/krzkraw/headroom/tree/krz/project-scoped-traffic-learner).
It depends on the request-scoped APIs completed here.

No schema or data migration is required.
<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/2637"
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: chopratejas <chopratejas@gmail.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-28 17:42:30 -05:00

241 lines
7.6 KiB
Python

from __future__ import annotations
import asyncio
from types import SimpleNamespace
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 test_responses_traffic_skips_unresolved_project() -> None:
handler = OpenAIHandlerMixin()
learner = _RecordingLearner()
handler.traffic_learner = learner
handler.memory_handler = SimpleNamespace(is_project_unresolved=lambda _ctx: True)
asyncio.run(
handler._observe_openai_responses_traffic(
{"input": _responses_input()},
request_id="r",
request_context=object(),
)
)
assert learner.tool_results == []
assert learner.message_batches == []
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"}