Files
chopratejas--headroom/tests/test_proxy_pipeline_lifecycle.py
wehub-resource-sync 0ef5fcb1c5
Security / Dependency audit (pip-audit) (push) Has been cancelled
Security / CodeQL (javascript-typescript) (push) Has been cancelled
Security / CodeQL (python) (push) Has been cancelled
Security / Secret scan (gitleaks) (push) Has been cancelled
rust / test (ubuntu) (push) Has been cancelled
rust / simulator e2e (macos-latest) (push) Has been cancelled
rust / simulator e2e (ubuntu-latest) (push) Has been cancelled
rust / simulator e2e (windows-latest) (push) Has been cancelled
rust / wheels (aarch64-apple-darwin) (push) Has been cancelled
rust / wheels (x86_64-unknown-linux-gnu) (push) Has been cancelled
rust / wheels (x86_64-apple-darwin) (push) Has been cancelled
rust / audit (push) Has been cancelled
rust / parity (nightly, allowed to fail during Phase 0) (push) Has been cancelled
CI / commitlint (push) Has been skipped
Dev Containers / validate (.devcontainer/devcontainer.json, default) (push) Failing after 0s
Dev Containers / validate (.devcontainer/memory-stack/devcontainer.json, memory-stack) (push) Failing after 0s
Dev Containers / validate-worktree (push) Failing after 0s
CI / changes (push) Failing after 4s
Deploy Documentation / validate (push) Has been skipped
Deploy Documentation / deploy (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, claude) (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, codex) (push) Failing after 1s
Install Native E2E / install-native (ubuntu-latest) (push) Failing after 1s
OpenCode Plugin / typecheck + build + test (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, copilot) (push) Failing after 1s
Release Please / release-please (push) Failing after 1s
Wrap E2E / docker-wrap-e2e (push) Failing after 1s
Wrap Native E2E / wrap-native (ubuntu-latest) (push) Failing after 1s
Init E2E / docker-init-e2e (push) Failing after 4s
Merge Conflicts / merge-conflicts (push) Failing after 4s
CI / lint (push) Has been cancelled
CI / build-wheel (push) Has been cancelled
CI / build-wheel-windows (push) Has been cancelled
CI / prefetch-model (push) Has been cancelled
CI / test-dashboard-ui (push) Has been cancelled
CI / test (1) (push) Has been cancelled
CI / test (2) (push) Has been cancelled
CI / test (3) (push) Has been cancelled
CI / test (4) (push) Has been cancelled
CI / test-extras (push) Has been cancelled
CI / test-agno (push) Has been cancelled
CI / build (push) Has been cancelled
CI / workflow-validation (push) Has been cancelled
CI / docker-native-e2e (push) Has been cancelled
CI / windows-native-wrapper (push) Has been cancelled
CI / macos-native-wrapper (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / promote-latest (push) Has been cancelled
Init Native E2E / init-native (macos-latest, claude) (push) Has been cancelled
Init Native E2E / init-native (macos-latest, codex) (push) Has been cancelled
Init Native E2E / init-native (macos-latest, copilot) (push) Has been cancelled
Install Native E2E / install-native (macos-latest) (push) Has been cancelled
Wrap Native E2E / wrap-native (macos-latest) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:03:20 +08:00

302 lines
10 KiB
Python

from __future__ import annotations
import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, call, patch
import httpx
from fastapi.testclient import TestClient
from headroom.pipeline import PipelineStage
from headroom.proxy.server import ProxyConfig, create_app
class _RecordingExtension:
def __init__(self) -> None:
self.stages: list[PipelineStage] = []
self.events: list = []
def on_pipeline_event(self, event):
self.stages.append(event.stage)
self.events.append(event)
return None
class _DummyTokenizer:
def count_messages(self, messages):
return len(messages)
def _assert_compressed_event_carries_originals(events: list) -> None:
"""INPUT_COMPRESSED must expose the pre-compression messages to extensions.
The probe recorder (headroom.proxy.probe_recorder) depends on this
metadata contract; dropping it silently disables session recording.
"""
compressed = [event for event in events if event.stage is PipelineStage.INPUT_COMPRESSED]
assert compressed
original = compressed[0].metadata.get("original_messages")
assert isinstance(original, list)
assert any(
message.get("role") == "user" and "hello" in str(message.get("content"))
for message in original
if isinstance(message, dict)
)
def _assert_stage_order(stages: list[PipelineStage]) -> None:
expected = [
PipelineStage.SETUP,
PipelineStage.PRE_START,
PipelineStage.POST_START,
PipelineStage.INPUT_RECEIVED,
PipelineStage.INPUT_ROUTED,
PipelineStage.INPUT_COMPRESSED,
PipelineStage.INPUT_REMEMBERED,
PipelineStage.PRE_SEND,
PipelineStage.POST_SEND,
PipelineStage.RESPONSE_RECEIVED,
]
positions = [stages.index(stage) for stage in expected]
assert positions == sorted(positions)
def test_proxy_shutdown_unloads_image_models() -> None:
config = ProxyConfig(
optimize=False,
image_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,
)
app = create_app(config)
proxy = app.state.proxy
proxy.http_client = None
proxy.memory_handler = None
quota_registry = SimpleNamespace(stop_all=AsyncMock())
with (
patch("headroom.proxy.server.get_quota_registry", return_value=quota_registry),
patch("headroom.models.ml_models.MLModelRegistry.unload_prefix") as unload_prefix,
):
asyncio.run(proxy.shutdown())
assert unload_prefix.call_args_list == [
call("technique_router:"),
call("siglip:"),
]
quota_registry.stop_all.assert_awaited_once()
def test_proxy_shutdown_flushes_savings_tracker() -> None:
"""Graceful shutdown must flush the savings tracker's batched tail.
The proxy throttles savings persistence (save_flush_every=25), so buffered
requests only reach disk on the next threshold write or an explicit flush.
shutdown() is that flush; if the wiring regresses, a graceful stop silently
drops the last few requests' lifetime totals. The tracker's flush() logic is
covered in test_proxy_savings_history.py — this guards only the call site.
"""
config = ProxyConfig(
optimize=False,
image_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,
)
app = create_app(config)
proxy = app.state.proxy
proxy.http_client = None
proxy.memory_handler = None
proxy.metrics.savings_tracker.flush = Mock()
quota_registry = SimpleNamespace(stop_all=AsyncMock())
with (
patch("headroom.proxy.server.get_quota_registry", return_value=quota_registry),
patch("headroom.models.ml_models.MLModelRegistry.unload_prefix"),
):
asyncio.run(proxy.shutdown())
proxy.metrics.savings_tracker.flush.assert_called_once()
def test_proxy_shutdown_signals_retry_waiters() -> None:
config = ProxyConfig(
optimize=False,
image_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,
)
app = create_app(config)
proxy = app.state.proxy
proxy.http_client = None
proxy.memory_handler = None
proxy._shutdown_event = asyncio.Event()
quota_registry = SimpleNamespace(stop_all=AsyncMock())
with (
patch("headroom.proxy.server.get_quota_registry", return_value=quota_registry),
patch("headroom.models.ml_models.MLModelRegistry.unload_prefix"),
):
asyncio.run(proxy.shutdown())
assert proxy._shutdown_event.is_set()
def test_openai_chat_pipeline_events_cover_proxy_lifecycle(monkeypatch) -> None:
recorder = _RecordingExtension()
config = ProxyConfig(
optimize=True,
image_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,
pipeline_extensions=[recorder],
discover_pipeline_extensions=False,
)
app = create_app(config)
with TestClient(app) as client:
proxy = client.app.state.proxy
proxy.openai_pipeline = SimpleNamespace(
apply=lambda messages, model, **kwargs: SimpleNamespace(
messages=[
{"role": "system", "content": "memory"},
{"role": "user", "content": "hello"},
],
transforms_applied=["router:text:kompress"],
tokens_before=10,
tokens_after=6,
)
)
proxy.memory_handler = SimpleNamespace(
config=SimpleNamespace(inject_context=True, inject_tools=False),
search_and_format_context=AsyncMock(return_value="memory"),
has_memory_tool_calls=lambda response, provider: False,
)
monkeypatch.setattr("headroom.tokenizers.get_tokenizer", lambda model: _DummyTokenizer())
async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001
return httpx.Response(
200,
json={
"id": "chatcmpl_1",
"object": "chat.completion",
"choices": [{"message": {"role": "assistant", "content": "ok"}}],
"usage": {"prompt_tokens": 10, "completion_tokens": 3, "total_tokens": 13},
},
)
proxy._retry_request = _fake_retry
response = client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-test", "x-headroom-user-id": "user-1"},
json={
"model": "gpt-5.4",
"messages": [{"role": "user", "content": "hello"}],
"tools": [{"type": "function", "function": {"name": "tool_a"}}],
},
)
assert response.status_code == 200
_assert_stage_order(recorder.stages)
_assert_compressed_event_carries_originals(recorder.events)
def test_anthropic_messages_pipeline_events_cover_proxy_lifecycle(monkeypatch) -> None:
recorder = _RecordingExtension()
config = ProxyConfig(
optimize=True,
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,
pipeline_extensions=[recorder],
discover_pipeline_extensions=False,
)
app = create_app(config)
with TestClient(app) as client:
proxy = client.app.state.proxy
proxy.anthropic_pipeline = SimpleNamespace(
apply=lambda messages, model, **kwargs: SimpleNamespace(
messages=[
{"role": "system", "content": "memory"},
{"role": "user", "content": "hello"},
],
transforms_applied=["router:text:kompress"],
tokens_before=10,
tokens_after=6,
)
)
proxy.memory_handler = SimpleNamespace(
config=SimpleNamespace(inject_context=True, inject_tools=False),
search_and_format_context=AsyncMock(return_value="memory"),
has_memory_tool_calls=lambda response, provider: False,
)
monkeypatch.setattr("headroom.tokenizers.get_tokenizer", lambda model: _DummyTokenizer())
async def _fake_retry(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001
return httpx.Response(
200,
json={
"id": "msg_1",
"type": "message",
"role": "assistant",
"content": [{"type": "text", "text": "ok"}],
"usage": {
"input_tokens": 10,
"output_tokens": 3,
"cache_read_input_tokens": 0,
"cache_creation_input_tokens": 0,
},
},
)
proxy._retry_request = _fake_retry
response = client.post(
"/v1/messages",
headers={
"x-api-key": "test-key",
"anthropic-version": "2023-06-01",
"x-headroom-user-id": "user-1",
},
json={
"model": "claude-sonnet-4-6",
"max_tokens": 128,
"messages": [{"role": "user", "content": "hello"}],
"tools": [
{"name": "tool_a", "description": "a", "input_schema": {"type": "object"}}
],
},
)
assert response.status_code == 200
_assert_stage_order(recorder.stages)
_assert_compressed_event_carries_originals(recorder.events)