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
263 lines
10 KiB
Python
263 lines
10 KiB
Python
"""Test OpenAI /v1/chat/completions streaming through headroom proxy backends.
|
|
|
|
Proves that streaming works end-to-end: client → headroom proxy → backend → OpenAI API.
|
|
|
|
Two test modes:
|
|
1. Real API test (requires OPENAI_API_KEY): hits actual OpenAI with gpt-4o-mini
|
|
2. Mock test: proves the proxy returns SSE when stream:true with a backend configured
|
|
|
|
Run with:
|
|
OPENAI_API_KEY=sk-... pytest tests/test_openai_streaming_backend.py -v
|
|
"""
|
|
|
|
import os
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
fastapi = pytest.importorskip("fastapi")
|
|
httpx = pytest.importorskip("httpx")
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
from headroom.backends.base import BackendResponse # noqa: E402
|
|
from headroom.proxy.server import ProxyConfig, create_app # noqa: E402
|
|
|
|
# =============================================================================
|
|
# Real API test (requires OPENAI_API_KEY)
|
|
# =============================================================================
|
|
|
|
|
|
@pytest.mark.skipif(not os.environ.get("OPENAI_API_KEY"), reason="OPENAI_API_KEY not set")
|
|
class TestOpenAIStreamingRealAPI:
|
|
"""Test streaming with real OpenAI API calls through the proxy."""
|
|
|
|
@pytest.fixture
|
|
def openai_api_key(self):
|
|
return os.environ["OPENAI_API_KEY"]
|
|
|
|
@pytest.fixture
|
|
def direct_proxy_client(self):
|
|
"""Proxy with NO backend — direct to OpenAI. This is the baseline."""
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
)
|
|
app = create_app(config)
|
|
with TestClient(app) as client:
|
|
yield client
|
|
|
|
@pytest.fixture
|
|
def litellm_backend_client(self):
|
|
"""Proxy with litellm-openai backend — routes through LiteLLM."""
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
backend="litellm-openai",
|
|
)
|
|
app = create_app(config)
|
|
with TestClient(app) as client:
|
|
yield client
|
|
|
|
def test_baseline_streaming_works_direct(self, direct_proxy_client, openai_api_key):
|
|
"""Baseline: streaming through proxy WITHOUT backend works (direct to OpenAI)."""
|
|
response = direct_proxy_client.post(
|
|
"/v1/chat/completions",
|
|
json={
|
|
"model": "gpt-4o-mini",
|
|
"messages": [{"role": "user", "content": "Say 'hello' and nothing else."}],
|
|
"stream": True,
|
|
"max_tokens": 10,
|
|
},
|
|
headers={"Authorization": f"Bearer {openai_api_key}"},
|
|
)
|
|
|
|
assert response.status_code == 200, f"Got {response.status_code}: {response.text[:200]}"
|
|
|
|
content_type = response.headers.get("content-type", "")
|
|
assert "text/event-stream" in content_type, (
|
|
f"Direct proxy streaming broken: got content-type '{content_type}'"
|
|
)
|
|
|
|
# Verify we got actual SSE chunks
|
|
body = response.text
|
|
assert "data: " in body, "No SSE data chunks in response"
|
|
assert "data: [DONE]" in body, "Missing [DONE] terminator"
|
|
|
|
def test_streaming_with_litellm_backend(self, litellm_backend_client, openai_api_key):
|
|
"""CRITICAL: streaming through proxy WITH litellm backend must also stream.
|
|
|
|
This test fails before the fix — the proxy returns a JSON blob
|
|
instead of SSE events, causing clients to hang.
|
|
"""
|
|
response = litellm_backend_client.post(
|
|
"/v1/chat/completions",
|
|
json={
|
|
"model": "gpt-4o-mini",
|
|
"messages": [{"role": "user", "content": "Say 'hello' and nothing else."}],
|
|
"stream": True,
|
|
"max_tokens": 10,
|
|
},
|
|
headers={"Authorization": f"Bearer {openai_api_key}"},
|
|
)
|
|
|
|
assert response.status_code == 200, f"Got {response.status_code}: {response.text[:200]}"
|
|
|
|
content_type = response.headers.get("content-type", "")
|
|
assert "text/event-stream" in content_type, (
|
|
f"STREAMING BUG: litellm backend returned '{content_type}' instead of "
|
|
f"'text/event-stream'. Client sees a JSON blob, not SSE events.\n"
|
|
f"Response body (first 300 chars): {response.text[:300]}"
|
|
)
|
|
|
|
# Verify SSE format
|
|
body = response.text
|
|
assert "data: " in body, "No SSE data chunks in streaming response"
|
|
|
|
def test_non_streaming_with_litellm_backend(self, litellm_backend_client, openai_api_key):
|
|
"""Non-streaming with backend should return normal JSON (sanity check)."""
|
|
response = litellm_backend_client.post(
|
|
"/v1/chat/completions",
|
|
json={
|
|
"model": "gpt-4o-mini",
|
|
"messages": [{"role": "user", "content": "Say 'hello' and nothing else."}],
|
|
"stream": False,
|
|
"max_tokens": 10,
|
|
},
|
|
headers={"Authorization": f"Bearer {openai_api_key}"},
|
|
)
|
|
|
|
assert response.status_code == 200, f"Got {response.status_code}: {response.text[:200]}"
|
|
|
|
content_type = response.headers.get("content-type", "")
|
|
assert "application/json" in content_type
|
|
|
|
data = response.json()
|
|
assert "choices" in data
|
|
assert data["choices"][0]["message"]["content"]
|
|
|
|
|
|
# =============================================================================
|
|
# Mock test (no API key needed — proves the routing bug)
|
|
# =============================================================================
|
|
|
|
|
|
class TestOpenAIStreamingMock:
|
|
"""Prove the streaming bug with mocks — no API key needed."""
|
|
|
|
def test_streaming_request_returns_sse_not_json(self):
|
|
"""When stream:true with a backend, content-type MUST be text/event-stream.
|
|
|
|
This test FAILS before the fix: the proxy calls send_openai_message()
|
|
(non-streaming) and returns application/json even though stream:true.
|
|
"""
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
backend="anyllm",
|
|
anyllm_provider="openai",
|
|
)
|
|
|
|
mock_backend = MagicMock()
|
|
mock_backend.name = "anyllm-openai"
|
|
mock_backend.send_openai_message = AsyncMock(
|
|
return_value=BackendResponse(
|
|
body={
|
|
"id": "chatcmpl-123",
|
|
"object": "chat.completion",
|
|
"model": "test-model",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"message": {"role": "assistant", "content": "Hello!"},
|
|
"finish_reason": "stop",
|
|
}
|
|
],
|
|
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
|
},
|
|
status_code=200,
|
|
headers={"content-type": "application/json"},
|
|
)
|
|
)
|
|
|
|
with patch("headroom.proxy.server.AnyLLMBackend", return_value=mock_backend):
|
|
app = create_app(config)
|
|
|
|
with TestClient(app) as client:
|
|
response = client.post(
|
|
"/v1/chat/completions",
|
|
json={
|
|
"model": "test-model",
|
|
"messages": [{"role": "user", "content": "hello"}],
|
|
"stream": True,
|
|
},
|
|
headers={"Authorization": "Bearer test-key"},
|
|
)
|
|
|
|
assert response.status_code == 200, (
|
|
f"Got {response.status_code}: {response.text[:200]}"
|
|
)
|
|
|
|
content_type = response.headers.get("content-type", "")
|
|
assert "text/event-stream" in content_type, (
|
|
f"STREAMING BUG: stream:true with backend returned '{content_type}' "
|
|
f"instead of 'text/event-stream'. The proxy ignored the stream flag "
|
|
f"and returned a JSON blob. Clients expecting SSE will hang.\n"
|
|
f"Response: {response.text[:300]}"
|
|
)
|
|
|
|
def test_non_streaming_still_returns_json(self):
|
|
"""Sanity: stream:false with backend should return JSON as before."""
|
|
config = ProxyConfig(
|
|
optimize=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
backend="anyllm",
|
|
anyllm_provider="openai",
|
|
)
|
|
|
|
mock_backend = MagicMock()
|
|
mock_backend.name = "anyllm-openai"
|
|
mock_backend.send_openai_message = AsyncMock(
|
|
return_value=BackendResponse(
|
|
body={
|
|
"id": "chatcmpl-123",
|
|
"object": "chat.completion",
|
|
"model": "test-model",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"message": {"role": "assistant", "content": "Hello!"},
|
|
"finish_reason": "stop",
|
|
}
|
|
],
|
|
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
|
},
|
|
status_code=200,
|
|
headers={"content-type": "application/json"},
|
|
)
|
|
)
|
|
|
|
with patch("headroom.proxy.server.AnyLLMBackend", return_value=mock_backend):
|
|
app = create_app(config)
|
|
|
|
with TestClient(app) as client:
|
|
response = client.post(
|
|
"/v1/chat/completions",
|
|
json={
|
|
"model": "test-model",
|
|
"messages": [{"role": "user", "content": "hello"}],
|
|
"stream": False,
|
|
},
|
|
headers={"Authorization": "Bearer test-key"},
|
|
)
|
|
|
|
assert response.status_code == 200
|
|
content_type = response.headers.get("content-type", "")
|
|
assert "application/json" in content_type
|
|
data = response.json()
|
|
assert data["choices"][0]["message"]["content"] == "Hello!"
|