Files
VoiceStudio/tests/test_api_activity.py
debpalash 3a528c1b42 fix(api-activity): label server cancellation honestly; tighten tests
A server-side CancelledError no longer reads as a client disconnect;
the transport still flags real disconnects. Annotates the activity
API, pairs each keepalive test with its own content type, asserts the
context reset inside each request task, and replaces a polling sleep
with an event.
2026-12-01 06:31:17 +05:30

1052 lines
42 KiB
Python

"""Content-free, bounded API activity and real streaming lifetimes."""
from __future__ import annotations
import asyncio
from concurrent.futures import ThreadPoolExecutor
import json
import pytest
pytestmark = pytest.mark.timeout(60)
def _scope(path="/v1/audio/speech", *, method="POST", query=b"", headers=()):
return {
"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1",
"method": method, "scheme": "http", "path": path,
"raw_path": path.encode(), "query_string": query,
"headers": list(headers), "client": ("192.0.2.17", 32001),
"server": ("testserver", 80),
}
async def _receive():
return {"type": "http.request", "body": b"", "more_body": False}
async def _reply(send, *, status=200, body=b"audio", more_body=False, headers=()):
await send({"type": "http.response.start", "status": status, "headers": list(headers)})
await send({"type": "http.response.body", "body": body, "more_body": more_body})
def test_store_bounds_history_and_preserves_active_on_clear():
from core.api_activity import RequestActivityStore
activity = RequestActivityStore(limit=3, max_active=2)
for _ in range(8):
request_id = activity.start("POST", "/v1/audio/speech", "api")
activity.finish(request_id, http_status=200)
assert len(activity.snapshot()["requests"]) <= 3
active_id = activity.start("POST", "/generate", "studio")
activity.clear_finished()
rows = activity.snapshot()["requests"]
assert [row["id"] for row in rows] == [active_id]
assert rows[0]["status"] == "running"
activity.finish(active_id)
activity.clear_finished()
assert activity.snapshot()["requests"] == []
def test_active_capacity_fails_open_without_unbounded_growth():
from core.api_activity import RequestActivityStore
activity = RequestActivityStore(limit=3, max_active=2)
first = activity.start("POST", "/generate", "studio")
second = activity.start("POST", "/generate", "studio")
assert first and second and first != second
assert activity.start("POST", "/generate", "studio") is None
assert activity.snapshot()["dropped"] >= 1
assert len(activity.snapshot()["requests"]) == 2
activity.finish(first)
assert activity.start("POST", "/generate", "studio") is not None
def test_store_is_thread_safe_and_snapshots_do_not_mutate_state():
from core.api_activity import RequestActivityStore
activity = RequestActivityStore(limit=200, max_active=128)
def record(_):
request_id = activity.start("POST", "/v1/audio/speech", "api")
activity.update(request_id, stage="generating", engine="omnivoice")
activity.finish(request_id, http_status=200, response_bytes=8)
return request_id
with ThreadPoolExecutor(max_workers=8) as executor:
ids = list(executor.map(record, range(80)))
assert len(set(ids)) == 80
snapshot = activity.snapshot()
assert len(snapshot["requests"]) == 80
assert all(row["status"] == "completed" for row in snapshot["requests"])
snapshot["requests"][0]["stage"] = "altered outside store"
assert all(row["stage"] != "altered outside store" for row in activity.snapshot()["requests"])
@pytest.mark.parametrize("path", [
"/v1/audio/speech", "/v1/audio/transcriptions", "/v1/audio/translations",
"/generate", "/generate/stream", "/v1/text-to-speech/private-voice-id",
"/v1/text-to-speech/private-voice-id/stream",
"/v1/text-to-speech/private-voice-id/with-timestamps",
"/v1/text-to-speech/private-voice-id/stream/with-timestamps",
"/elevenlabs/v1/text-to-speech/private-voice-id",
"/elevenlabs/v1/text-to-speech/private-voice-id/with-timestamps",
"/elevenlabs/v1/text-to-speech/private-voice-id/stream/with-timestamps",
])
def test_generation_routes_are_tracked_without_voice_identifiers(path):
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
sent = []
async def app(scope, receive, send):
await _reply(send)
async def send(message):
sent.append(message)
await ApiActivityMiddleware(app, activity_store=activity)(_scope(path), _receive, send)
row, = activity.snapshot()["requests"]
assert row["status"] == "completed"
assert row["http_status"] == 200
assert "private-voice-id" not in json.dumps(row)
assert row["path"] == path.replace("private-voice-id", "{voice_id}")
assert any(name.lower() == b"x-voicestudio-request-id" for name, _ in sent[0]["headers"])
asyncio.run(run())
@pytest.mark.parametrize("path,method", [("/health", "GET"), ("/models", "GET"), ("/v1/audio/speech", "GET")])
def test_unrelated_routes_are_not_tracked(path, method):
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
async def app(scope, receive, send):
await _reply(send)
async def send(message):
pass
await ApiActivityMiddleware(app, activity_store=activity)(_scope(path, method=method), _receive, send)
assert activity.snapshot()["requests"] == []
asyncio.run(run())
def test_stream_remains_running_until_final_body_and_counts_only_bytes():
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
async def app(scope, receive, send):
await _reply(send, body=b"first", more_body=True)
row, = activity.snapshot()["requests"]
assert row["status"] == "running"
assert row["finished_at"] is None
await asyncio.sleep(0)
await send({"type": "http.response.body", "body": b"second", "more_body": False})
async def send(message):
pass
await ApiActivityMiddleware(app, activity_store=activity)(_scope(), _receive, send)
row, = activity.snapshot()["requests"]
assert row["status"] == "completed"
assert row["response_bytes"] == 11
assert row["finished_at"] is not None
assert row["elapsed_ms"] >= 0
asyncio.run(run())
def test_concurrent_requests_and_executor_updates_keep_their_own_context():
from core import api_activity
from core.api_activity import ApiActivityMiddleware, RequestActivityStore, bind, update_current
from concurrent.futures import ThreadPoolExecutor
# A plain executor does not copy context (asyncio.to_thread would), so the
# engines only land on the right rows if bind() carries the identity.
pool = ThreadPoolExecutor(max_workers=2)
async def run():
activity = RequestActivityStore()
both_started = asyncio.Event()
started = 0
async def app(scope, receive, send):
nonlocal started
engine = "omnivoice" if scope["path"] == "/generate" else "voxcpm2"
started += 1
if started == 2:
both_started.set()
await asyncio.wait_for(both_started.wait(), timeout=15)
await asyncio.get_running_loop().run_in_executor(
pool, bind(lambda: update_current(stage="generating", engine=engine)),
)
await _reply(send)
async def send(message):
pass
middleware = ApiActivityMiddleware(app, activity_store=activity)
restored = []
async def request(path):
# Each request task must get its previous (empty) binding back.
await middleware(_scope(path), _receive, send)
restored.append(api_activity._CURRENT.get())
await asyncio.gather(request("/generate"), request("/v1/audio/speech"))
assert restored == [None, None]
rows = {row["path"]: row for row in activity.snapshot()["requests"]}
assert rows["/generate"]["engine"] == "omnivoice"
assert rows["/v1/audio/speech"]["engine"] == "voxcpm2"
assert len({row["id"] for row in rows.values()}) == 2
before = activity.snapshot()
update_current(stage="outside request", engine="other")
assert activity.snapshot() == before
try:
asyncio.run(run())
finally:
pool.shutdown(wait=True)
@pytest.mark.parametrize("outcome", ["http_error", "exception", "cancel", "disconnect"])
def test_failed_and_cancelled_requests_have_terminal_status_without_error_content(outcome):
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
async def app(scope, receive, send):
if outcome == "http_error":
await _reply(send, status=503, body=b"SECRET error body")
elif outcome == "exception":
raise ValueError("SECRET exception detail")
elif outcome == "cancel":
raise asyncio.CancelledError()
else:
await receive()
async def receive():
return {"type": "http.disconnect"}
async def send(message):
pass
middleware = ApiActivityMiddleware(app, activity_store=activity)
if outcome == "exception":
with pytest.raises(ValueError):
await middleware(_scope(), receive, send)
elif outcome == "cancel":
with pytest.raises(asyncio.CancelledError):
await middleware(_scope(), receive, send)
else:
await middleware(_scope(), receive, send)
row, = activity.snapshot()["requests"]
assert row["status"] == ("cancelled" if outcome in {"cancel", "disconnect"} else "failed")
# Only the transport can say the client left; a server cancel says nothing.
assert row["error_code"] == {
"http_error": "http_error", "exception": "internal_error",
"cancel": None, "disconnect": "client_disconnected",
}[outcome]
assert row["finished_at"] is not None
assert "SECRET" not in json.dumps(row)
asyncio.run(run())
def test_request_payload_credentials_query_and_peer_are_not_retained():
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
async def app(scope, receive, send):
assert (await receive())["body"] == b"SECRET spoken text"
await _reply(send, body=b"SECRET response audio")
async def receive():
return {"type": "http.request", "body": b"SECRET spoken text", "more_body": False}
async def send(message):
pass
scope = _scope(query=b"pin=SECRET-pin&input=SECRET-input", headers=[
(b"authorization", b"Bearer SECRET-key"), (b"cookie", b"session=SECRET-cookie"),
(b"x-voicestudio-request-id", b"SECRET-client-id"),
])
await ApiActivityMiddleware(app, activity_store=activity)(scope, receive, send)
serialized = json.dumps(activity.snapshot())
assert "SECRET" not in serialized
assert "192.0.2.17" not in serialized
row, = activity.snapshot()["requests"]
assert set(row) <= {
"id", "method", "path", "source", "status", "stage", "engine", "model",
"started_at", "finished_at", "elapsed_ms", "http_status", "response_bytes", "error_code",
}
asyncio.run(run())
def test_split_sse_error_frame_marks_failed_without_retaining_details():
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
async def app(scope, receive, send):
await _reply(send, body=b'event: error\nda', more_body=True,
headers=[(b"content-type", b"text/event-stream")])
await send({"type": "http.response.body", "body": b'ta: {"error":"SECRET upstream detail"}\n\n', "more_body": False})
async def send(message):
pass
await ApiActivityMiddleware(app, activity_store=activity)(_scope("/generate/stream"), _receive, send)
snapshot = activity.snapshot()
row, = snapshot["requests"]
assert row["status"] == "failed"
assert row["http_status"] == 200
assert "SECRET" not in json.dumps(snapshot)
asyncio.run(run())
def test_audio_bytes_that_resemble_sse_errors_are_not_parsed_as_errors():
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
async def app(scope, receive, send):
await _reply(send, body=b'event: error\ndata: {"error":"audio bytes"}\n\n',
headers=[(b"content-type", b"audio/wav")])
async def send(message):
pass
await ApiActivityMiddleware(app, activity_store=activity)(_scope(), _receive, send)
row, = activity.snapshot()["requests"]
assert row["status"] == "completed"
asyncio.run(run())
def test_admin_activity_routes_keep_active_entries_on_clear(monkeypatch):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from api.routers import api_activity as routes
from core.api_activity import RequestActivityStore
activity = RequestActivityStore()
active = activity.start("POST", "/generate", "studio")
done = activity.start("POST", "/v1/audio/speech", "api")
activity.finish(done)
monkeypatch.setattr(routes, "store", activity)
app = FastAPI()
app.include_router(routes.router)
client = TestClient(app, client=("127.0.0.1", 12345))
response = client.get("/system/api-activity")
assert response.status_code == 200, response.text
assert {row["id"] for row in response.json()["requests"]} == {active, done}
cleared = client.delete("/system/api-activity")
assert cleared.status_code in {200, 204}, cleared.text
assert [row["id"] for row in activity.snapshot()["requests"]] == [active]
def test_activity_read_and_clear_do_not_wait_for_http_worker_capacity(monkeypatch):
"""A busy synchronous speech handler must not block its own diagnostics."""
import threading
import anyio
import httpx
from fastapi import FastAPI
from hang_guard import BARRIER_WATCHDOG_S, HANG_GUARD_S
from api.routers import api_activity as routes
from core.api_activity import RequestActivityStore
activity = RequestActivityStore()
active = activity.start("POST", "/generate", "native")
finished = activity.start("POST", "/v1/audio/speech", "openai")
activity.finish(finished)
monkeypatch.setattr(routes, "store", activity)
app = FastAPI()
app.include_router(routes.router)
async def run():
limiter = anyio.to_thread.current_default_thread_limiter()
previous_tokens = limiter.total_tokens
limiter.total_tokens = 1
loop = asyncio.get_running_loop()
occupied = asyncio.Event()
release = threading.Event()
def busy_handler():
loop.call_soon_threadsafe(occupied.set)
assert release.wait(BARRIER_WATCHDOG_S), "HTTP worker watchdog expired"
worker = asyncio.create_task(anyio.to_thread.run_sync(busy_handler))
try:
await asyncio.wait_for(occupied.wait(), timeout=HANG_GUARD_S)
transport = httpx.ASGITransport(app, client=("127.0.0.1", 12345))
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
snapshot = await asyncio.wait_for(client.get("/system/api-activity"), timeout=HANG_GUARD_S)
assert snapshot.status_code == 200, snapshot.text
assert {row["id"] for row in snapshot.json()["requests"]} == {active, finished}
cleared = await asyncio.wait_for(client.delete("/system/api-activity"), timeout=HANG_GUARD_S)
assert cleared.status_code == 200, cleared.text
assert cleared.json() == {"cleared": 1}
assert [row["id"] for row in activity.snapshot()["requests"]] == [active]
assert not release.is_set()
finally:
release.set()
await worker
limiter.total_tokens = previous_tokens
asyncio.run(run())
@pytest.mark.parametrize("server_mode", [False, True])
@pytest.mark.parametrize("method", ["GET", "DELETE"])
def test_remote_activity_requires_admin_even_with_share_pin(monkeypatch, server_mode, method):
from types import SimpleNamespace
from fastapi import FastAPI
from fastapi.testclient import TestClient
from api import dependencies
from api.routers import api_activity as routes
from core.api_activity import RequestActivityStore
monkeypatch.setattr(dependencies, "_server_mode", lambda: server_mode)
monkeypatch.delenv("OMNIVOICE_API_KEY", raising=False)
monkeypatch.setattr(routes, "store", RequestActivityStore())
app = FastAPI()
app.state.network_share = SimpleNamespace(pin="123456")
app.include_router(routes.router)
client = TestClient(app, client=("192.0.2.20", 12345))
response = client.request(method, "/system/api-activity", headers={"x-omnivoice-pin": "123456"})
assert response.status_code == 403, response.text
def test_activity_read_rejects_cross_site_browser_request(monkeypatch):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from api.routers import api_activity as routes
from core.api_activity import RequestActivityStore
monkeypatch.setattr(routes, "store", RequestActivityStore())
app = FastAPI()
app.include_router(routes.router)
client = TestClient(app, client=("127.0.0.1", 12345))
response = client.get("/system/api-activity", headers={"sec-fetch-site": "cross-site"})
assert response.status_code == 403, response.text
@pytest.mark.parametrize("origin,marker,expected", [
("https://studio.example.test", "1", 200),
("https://studio.example.test", "", 403),
("https://untrusted.example.test", "1", 403),
])
def test_clear_accepts_same_site_admin_session_with_csrf(monkeypatch, origin, marker, expected):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from api.routers import api_activity as routes
from core.api_activity import RequestActivityStore
from services import admin_sessions
master = "test-administrator-key-for-api-activity"
monkeypatch.setenv("OMNIVOICE_SERVER_MODE", "1")
monkeypatch.setenv("OMNIVOICE_API_KEY", master)
monkeypatch.setenv("OMNIVOICE_ALLOWED_ORIGINS", "https://studio.example.test")
sessions = admin_sessions.AdminSessionStore()
monkeypatch.setattr(admin_sessions, "admin_session_store", sessions)
session = sessions.issue(master)
activity = RequestActivityStore()
finished = activity.start("POST", "/generate", "native")
activity.finish(finished)
monkeypatch.setattr(routes, "store", activity)
app = FastAPI()
app.include_router(routes.router)
client = TestClient(app, client=("192.0.2.20", 12345), base_url="https://api.example.test")
response = client.delete("/system/api-activity", headers={
"Cookie": f"ov_session={session.token}", "Origin": origin,
"Sec-Fetch-Site": "same-site", "X-VoiceStudio-CSRF": marker,
})
assert response.status_code == expected, response.text
assert len(activity.snapshot()["requests"]) == (0 if expected == 200 else 1)
def test_native_generation_reports_loading_once_the_load_worker_starts(monkeypatch):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from api.routers import engines, generation
from core import device_caps
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
from services import engine_memory, engine_routing, gpu_gateway, tts_backend
activity = RequestActivityStore()
phases = []
class Backend(tts_backend.TTSBackend):
id = "activity-test-engine"
sample_rate = 24000
supported_languages = ["en"]
@classmethod
def is_available(cls):
return True, "ready"
def generate(self, text, **kwargs):
raise AssertionError("generation must not start in this load-stage test")
def ensure_ready(self):
# Runs on the GPU worker: loading starts here, not while queued.
row, = activity.snapshot()["requests"]
phases.append(row["stage"])
assert row["engine"] == Backend.id
# End at the load boundary without running synthesis or saving audio.
raise TimeoutError("test model-load timeout")
backend = Backend()
real_prewarm = gpu_gateway.prewarm
async def prewarm(**kwargs):
row, = activity.snapshot()["requests"]
phases.append(row["stage"])
return await real_prewarm(**kwargs)
async def evict(*args):
pass
async def profile(*args):
return {"routing_status": "native", "routing_reason": None, "min_vram_gb": 0}
monkeypatch.setattr(tts_backend, "get_backend_class", lambda _: Backend)
monkeypatch.setattr(engines, "_get_engine_instance", lambda _: backend)
monkeypatch.setattr(generation, "_conditioning_refusal", lambda *args, **kwargs: None)
monkeypatch.setattr(device_caps, "detect_host_caps", lambda: object())
monkeypatch.setattr(engine_memory, "evict_other_tts_engines", evict)
monkeypatch.setattr(engine_routing, "runtime_compute_profile_async", profile)
monkeypatch.setattr(engine_routing, "routing_notice", lambda _: None)
monkeypatch.setattr(gpu_gateway, "prewarm", prewarm)
app = FastAPI()
app.include_router(generation.router)
app.add_middleware(ApiActivityMiddleware, activity_store=activity)
client = TestClient(app, client=("127.0.0.1", 12345))
response = client.post("/generate", data={"text": "test input", "engine": Backend.id})
assert response.status_code == 503, response.text
assert phases == ["queued", "loading_model"]
def test_finished_requests_ignore_late_executor_updates_and_duplicate_finish():
from core.api_activity import RequestActivityStore
activity = RequestActivityStore()
identity = activity.start("POST", "/generate", "native")
activity.update(identity, stage="generating", engine="omnivoice")
returned = activity.finish(identity, http_status=200, response_bytes=17)
before = activity.snapshot()
activity.update(identity, stage="loading_model", engine="voxcpm2")
activity.mark_error(identity)
assert activity.finish(identity, status="failed", http_status=500) is None
assert activity.snapshot() == before
returned["engine"] = "external mutation"
assert activity.snapshot() == before
def test_full_activity_store_does_not_block_generation():
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore(max_active=1)
existing = activity.start("POST", "/generate", "native")
sent = []
async def app(scope, receive, send):
await _reply(send)
async def send(message):
sent.append(message)
await ApiActivityMiddleware(app, activity_store=activity)(_scope(), _receive, send)
assert sent[0]["status"] == 200
assert sent[1]["body"] == b"audio"
assert [row["id"] for row in activity.snapshot()["requests"]] == [existing]
assert activity.snapshot()["dropped"] == 1
asyncio.run(run())
@pytest.mark.parametrize("mime", [b"application/x-ndjson", b"application/ndjson; charset=utf-8"])
def test_split_ndjson_error_marks_failed_without_exposing_payload_or_logs(caplog, mime):
import logging
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
caplog.set_level(logging.INFO, logger="omnivoice.api_activity")
async def run():
activity = RequestActivityStore()
chunks = [b'{"type":"progress","value":1}\n{"ty',
b'pe":"error","message":"SECRET failed generation"}\n']
sent = []
async def app(scope, receive, send):
await _reply(send, body=chunks[0], more_body=True,
headers=[(b"content-type", mime)])
await send({"type": "http.response.body", "body": chunks[1], "more_body": False})
async def send(message):
sent.append(message)
await ApiActivityMiddleware(app, activity_store=activity)(_scope("/generate/stream"), _receive, send)
row, = activity.snapshot()["requests"]
assert row["status"] == "failed"
assert row["error_code"] == "stream_error"
assert row["http_status"] == 200
assert row["response_bytes"] == sum(map(len, chunks))
assert [message["body"] for message in sent if message["type"] == "http.response.body"] == chunks
assert "SECRET" not in json.dumps(activity.snapshot())
assert "SECRET" not in caplog.text
assert row["id"] in caplog.text
asyncio.run(run())
@pytest.mark.parametrize("chunks", [
[b'data: {"type":[],"value":"SECRET"}\n\n'],
[b'data: {"type":{},"value":"SECRET"}\n\n'],
[b'data: {not-json-SECRET}\n\n'],
[b'data: \xff\xfeSECRET\n\n'],
[b'data: {"type":' + b'[' * 2000 + b'0' + b']' * 2000 + b'}\n\n'],
[b'data: ' + b'x' * 10000, b'y' * 10000 + b'\n\ndata: {"type":"progress"}\n\n'],
])
def test_malformed_or_oversized_sse_never_changes_the_stream(chunks):
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
sent = []
async def app(scope, receive, send):
await send({"type": "http.response.start", "status": 200,
"headers": [(b"content-type", b"text/event-stream")]})
for index, chunk in enumerate(chunks):
await send({"type": "http.response.body", "body": chunk,
"more_body": index < len(chunks) - 1})
async def send(message):
sent.append(message)
await ApiActivityMiddleware(app, activity_store=activity)(_scope("/generate/stream"), _receive, send)
assert sent[0]["status"] == 200
assert [message["body"] for message in sent if message["type"] == "http.response.body"] == chunks
row, = activity.snapshot()["requests"]
assert row["status"] == "completed"
assert row["response_bytes"] == sum(map(len, chunks))
assert "SECRET" not in json.dumps(activity.snapshot())
asyncio.run(run())
def test_openai_speech_reports_real_load_generate_and_encode_phases(monkeypatch):
"""Exercise the speech route; a plain executor must receive bound activity."""
from contextlib import contextmanager
from fastapi import FastAPI
from fastapi.testclient import TestClient
from api.routers import openai_compat
from core import device_caps
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
from services import engine_memory, engine_routing, model_manager, pronunciation, tts_backend
activity = RequestActivityStore()
phases = []
def current_phase():
row, = activity.snapshot()["requests"]
assert row["status"] == "running"
assert row["engine"] == "voxcpm2"
return row["stage"]
class Backend:
id = "voxcpm2"
def ensure_ready(self):
phases.append(current_phase())
assert phases[-1] == "loading_model"
backend = Backend()
monkeypatch.setattr(openai_compat, "_resolve_engine", lambda _model: backend)
monkeypatch.setattr(device_caps, "detect_host_caps", lambda: object())
async def profile(*args):
return {"routing_status": "native", "routing_reason": None}
async def evict(*args):
pass
async def run_guarded(function, **kwargs):
assert current_phase() == "queued"
# run_in_executor does not propagate ContextVars. Removing bind_activity
# from the route must break the callback's loading/generating assertion.
return await asyncio.get_running_loop().run_in_executor(None, function)
@contextmanager
def engine_in_use(*args, **kwargs):
yield
def generate(*args):
phases.append(current_phase())
assert phases[-1] == "generating"
return object(), 48000
async def encode(*args):
phases.append(current_phase())
assert phases[-1] == "encoding"
return b"fake encoded audio", "audio/wav", "wav"
monkeypatch.setattr(engine_routing, "runtime_compute_profile_async", profile)
monkeypatch.setattr(engine_routing, "routing_notice", lambda _routing: None)
monkeypatch.setattr(engine_memory, "evict_other_tts_engines", evict)
monkeypatch.setattr(pronunciation, "prepare_speech_text", lambda text, *args, **kwargs: text)
monkeypatch.setattr(model_manager, "check_gpu_admission", lambda **kwargs: None)
monkeypatch.setattr(model_manager, "_model_load_timeout", lambda: 60)
monkeypatch.setattr(model_manager, "generate_timeout_s", lambda *args, **kwargs: 60)
monkeypatch.setattr(tts_backend, "engine_in_use", engine_in_use)
monkeypatch.setattr(openai_compat, "run_on_gpu_pool_guarded", run_guarded)
monkeypatch.setattr(openai_compat, "_run_tts", generate)
monkeypatch.setattr(openai_compat, "_encode_audio", encode)
app = FastAPI()
app.include_router(openai_compat.router)
app.add_middleware(ApiActivityMiddleware, activity_store=activity)
client = TestClient(app, client=("127.0.0.1", 12345))
response = client.post("/v1/audio/speech", json={
"input": "SECRET spoken content", "model": "voxcpm2", "response_format": "wav",
})
assert response.status_code == 200, response.text
assert response.content == b"fake encoded audio"
assert phases == ["loading_model", "generating", "encoding"]
row, = activity.snapshot()["requests"]
assert row["status"] == "completed"
assert row["engine"] == "voxcpm2"
assert row["response_bytes"] == len(response.content)
assert "SECRET" not in json.dumps(activity.snapshot())
def test_real_streaming_response_client_disconnect_is_cancelled():
from starlette.requests import ClientDisconnect
from starlette.responses import StreamingResponse
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
async def app(scope, receive, send):
response = StreamingResponse(iter([b"audio"]), media_type="audio/wav")
await response(scope, receive, send)
async def disconnected_send(message):
if message["type"] == "http.response.body":
raise OSError("SECRET peer socket closed")
scope = _scope()
scope["asgi"]["spec_version"] = "2.4"
with pytest.raises(ClientDisconnect):
await ApiActivityMiddleware(app, activity_store=activity)(scope, _receive, disconnected_send)
row, = activity.snapshot()["requests"]
assert row["status"] == "cancelled"
assert row["http_status"] == 200
assert row["response_bytes"] == 0
assert row["error_code"] == "client_disconnected"
assert "SECRET" not in json.dumps(activity.snapshot())
asyncio.run(run())
@pytest.mark.parametrize("response_status", [500, 503, 499])
def test_outer_exception_response_keeps_existing_status_body_and_request_id(response_status):
import httpx
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from core.api_activity import ApiActivityMiddleware, RequestActivityStore, track_error_response
async def run():
activity = RequestActivityStore()
app = FastAPI()
@app.post("/v1/audio/speech")
async def broken_speech():
raise RuntimeError("SECRET engine failure detail")
@app.exception_handler(Exception)
@track_error_response
async def existing_exception_handler(request, error):
return JSONResponse({"message": "existing error response"}, status_code=response_status,
headers={"Retry-After": "30"})
app.add_middleware(ApiActivityMiddleware, activity_store=activity)
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app, raise_app_exceptions=False),
base_url="http://testserver") as client:
response = await client.post("/v1/audio/speech")
assert response.status_code == response_status
assert response.json() == {"message": "existing error response"}
assert response.headers["retry-after"] == "30"
row, = activity.snapshot()["requests"]
assert response.headers["x-voicestudio-request-id"] == row["id"]
assert row["http_status"] == response_status
assert row["status"] == ("cancelled" if response_status == 499 else "failed")
assert "SECRET" not in json.dumps(activity.snapshot())
asyncio.run(run())
def test_exception_after_headers_keeps_actual_200_and_partial_audio_byte_count():
import httpx
from fastapi import FastAPI
from fastapi.responses import JSONResponse, StreamingResponse
from core.api_activity import ApiActivityMiddleware, RequestActivityStore, track_error_response
async def run():
activity = RequestActivityStore()
app = FastAPI()
@app.post("/v1/audio/speech")
async def broken_stream():
async def audio():
yield b"partial audio"
raise RuntimeError("SECRET late engine failure")
return StreamingResponse(audio(), media_type="audio/wav")
@app.exception_handler(Exception)
@track_error_response
async def existing_exception_handler(request, error):
return JSONResponse({"message": "must not replace already sent audio"}, status_code=500)
app.add_middleware(ApiActivityMiddleware, activity_store=activity)
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app, raise_app_exceptions=False),
base_url="http://testserver") as client:
response = await client.post("/v1/audio/speech")
assert response.status_code == 200
assert response.content == b"partial audio"
row, = activity.snapshot()["requests"]
assert row["status"] == "failed"
assert row["http_status"] == 200
assert row["response_bytes"] == len(b"partial audio")
assert response.headers["x-voicestudio-request-id"] == row["id"]
assert "SECRET" not in json.dumps(activity.snapshot())
asyncio.run(run())
def test_incomplete_application_response_is_failed_without_disconnect_evidence():
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
async def app(scope, receive, send):
await _reply(send, body=b"unfinished audio", more_body=True)
# Returning without a final body is a broken application response,
# not evidence that the caller disconnected.
async def send(message):
pass
await ApiActivityMiddleware(app, activity_store=activity)(_scope(), _receive, send)
row, = activity.snapshot()["requests"]
assert row["status"] == "failed"
assert row["error_code"] == "internal_error"
assert row["http_status"] == 200
assert row["response_bytes"] == len(b"unfinished audio")
assert row["finished_at"] is not None
asyncio.run(run())
@pytest.mark.parametrize("mime,prefix", [(b"text/event-stream", b"data: "), (b"application/x-ndjson", b"")])
@pytest.mark.parametrize("error_value", [b"null", b"false"])
def test_benign_progress_error_field_is_not_a_stream_failure(mime, prefix, error_value):
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
body = prefix + b'{"type":"progress","error":' + error_value + b'}\n\n'
async def app(scope, receive, send):
await _reply(send, body=body, headers=[(b"content-type", mime)])
async def send(message):
pass
await ApiActivityMiddleware(app, activity_store=activity)(_scope("/generate/stream"), _receive, send)
row, = activity.snapshot()["requests"]
assert row["status"] == "completed"
assert row["error_code"] is None
assert row["response_bytes"] == len(body)
asyncio.run(run())
def test_speech_routes_behind_an_asgi_root_path_are_tracked():
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
async def app(scope, receive, send):
await _reply(send)
async def send(message):
pass
scope = {**_scope("/studio/v1/audio/speech"), "root_path": "/studio"}
await ApiActivityMiddleware(app, activity_store=activity)(scope, _receive, send)
row, = activity.snapshot()["requests"]
assert row["path"] == "/v1/audio/speech"
asyncio.run(run())
@pytest.mark.parametrize(("content_type", "keepalive", "frame"), [
(b"application/x-ndjson", b"\n", b'{"audio":"x"}\n'),
(b"text/event-stream", b": keepalive\n\n", b'data: {"audio":"x"}\n\n'),
])
def test_keepalives_do_not_mark_a_quiet_synthesis_as_streaming(content_type, keepalive, frame):
from core.api_activity import ApiActivityMiddleware, RequestActivityStore, update_current
async def run():
activity = RequestActivityStore()
stages = []
async def app(scope, receive, send):
update_current(stage="generating")
await send({"type": "http.response.start", "status": 200,
"headers": [(b"content-type", content_type)]})
await send({"type": "http.response.body", "body": keepalive, "more_body": True})
stages.append(activity.snapshot()["requests"][0]["stage"])
await send({"type": "http.response.body", "body": frame, "more_body": True})
stages.append(activity.snapshot()["requests"][0]["stage"])
await send({"type": "http.response.body", "body": b"", "more_body": False})
async def send(message):
pass
await ApiActivityMiddleware(app, activity_store=activity)(_scope("/generate/stream"), _receive, send)
assert stages == ["generating", "streaming"]
row, = activity.snapshot()["requests"]
assert row["response_bytes"] == len(keepalive) + len(frame)
asyncio.run(run())
def test_a_cold_omnivoice_load_reports_loading_model(monkeypatch):
from core import api_activity
from services import model_manager
activity = api_activity.RequestActivityStore()
identity = activity.start("POST", "/generate", "native")
stages = []
async def load():
stages.append(activity.snapshot()["requests"][0]["stage"])
return object()
monkeypatch.setattr(model_manager, "model", None)
monkeypatch.setattr(model_manager, "_ensure_omnivoice_licence", lambda: None)
monkeypatch.setattr(model_manager, "running_on_gpu_pool", lambda: False, raising=False)
monkeypatch.setattr(model_manager, "_load_model_with_timeout", load)
monkeypatch.setattr(model_manager, "make_room_before_generate", lambda: None, raising=False)
async def run():
token = api_activity._CURRENT.set((activity, identity))
try:
await model_manager.get_model()
finally:
api_activity._CURRENT.reset(token)
asyncio.run(run())
assert stages == ["loading_model"]
def test_a_keepalive_never_completes_an_unfinished_stream():
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
disconnected = False
async def app(scope, receive, send):
nonlocal disconnected
await send({"type": "http.response.start", "status": 200,
"headers": [(b"content-type", b"application/x-ndjson")]})
await send({"type": "http.response.body", "body": b"\n", "more_body": True})
# The client leaves before any audio; the app returns without raising.
disconnected = (await receive())["type"] == "http.disconnect"
async def receive():
return {"type": "http.disconnect"}
async def send(message):
pass
await ApiActivityMiddleware(app, activity_store=activity)(_scope("/generate/stream"), receive, send)
assert disconnected
row, = activity.snapshot()["requests"]
assert row["status"] == "cancelled"
assert row["error_code"] == "client_disconnected"
asyncio.run(run())
def test_binary_audio_that_looks_like_a_keepalive_is_still_output():
from core.api_activity import ApiActivityMiddleware, RequestActivityStore, update_current
async def run():
activity = RequestActivityStore()
stages = []
async def app(scope, receive, send):
update_current(stage="generating")
await send({"type": "http.response.start", "status": 200,
"headers": [(b"content-type", b"audio/pcm")]})
await send({"type": "http.response.body", "body": b":\x00\x01\x00", "more_body": True})
stages.append(activity.snapshot()["requests"][0]["stage"])
await send({"type": "http.response.body", "body": b"", "more_body": False})
async def send(message):
pass
await ApiActivityMiddleware(app, activity_store=activity)(_scope(), _receive, send)
assert stages == ["streaming"]
asyncio.run(run())
def test_a_rejected_response_start_records_no_http_status():
from core.api_activity import ApiActivityMiddleware, RequestActivityStore
async def run():
activity = RequestActivityStore()
async def app(scope, receive, send):
await _reply(send)
async def send(message):
raise OSError("transport closed")
with pytest.raises(OSError):
await ApiActivityMiddleware(app, activity_store=activity)(_scope(), _receive, send)
row, = activity.snapshot()["requests"]
assert row["status"] == "cancelled"
assert row["http_status"] is None
asyncio.run(run())