diff --git a/backend/api/routers/api_activity.py b/backend/api/routers/api_activity.py new file mode 100644 index 0000000000..7e1b67f740 --- /dev/null +++ b/backend/api/routers/api_activity.py @@ -0,0 +1,22 @@ +"""Administrator-only, session-scoped speech API activity.""" +from fastapi import APIRouter, Depends, Request + +from api.dependencies import require_admin_action, require_admin_diagnostics +from core.api_activity import store + +router = APIRouter() + + +async def _require_clear_access(request: Request) -> None: + # This gate performs no I/O; diagnostics must not wait for HTTP workers. + require_admin_action(request) + + +@router.get("/system/api-activity", dependencies=[Depends(require_admin_diagnostics)], include_in_schema=False) +async def api_activity(): + return store.snapshot() + + +@router.delete("/system/api-activity", dependencies=[Depends(_require_clear_access)], include_in_schema=False) +async def clear_api_activity(): + return {"cleared": store.clear_finished()} diff --git a/backend/api/routers/generation.py b/backend/api/routers/generation.py index 3f705dc21b..d095ba9b7d 100644 --- a/backend/api/routers/generation.py +++ b/backend/api/routers/generation.py @@ -2058,6 +2058,8 @@ async def generate_speech( sampling_defaults = tts_defaults(engine_id) try: backend_cls = get_backend_class(engine_id) + from core.api_activity import update_current + update_current(stage="queued", engine=backend_cls.id) except ValueError: raise HTTPException( status_code=400, @@ -2577,6 +2579,9 @@ async def _stream_events(): def _line(obj) -> bytes: """Encode one streaming synthesis event as a compact NDJSON line.""" + if obj.get("type") == "error": + from core.api_activity import mark_error_current + mark_error_current() return (json.dumps(obj, separators=(",", ":")) + "\n").encode("utf-8") try: diff --git a/backend/api/routers/openai_compat.py b/backend/api/routers/openai_compat.py index 413f1b6c24..04f7c57778 100644 --- a/backend/api/routers/openai_compat.py +++ b/backend/api/routers/openai_compat.py @@ -635,6 +635,9 @@ def _engine_instructions(backend, instructions: Optional[str]) -> Optional[str]: def _speech_event(event: dict) -> str: + if event.get("type") == "error": + from core.api_activity import mark_error_current + mark_error_current() return f"data: {json.dumps(event)}\n\n" @@ -854,6 +857,9 @@ async def create_speech(req: SpeechRequest): # OpenAI's error shape; `detail` keeps the models for VoiceStudio clients. raise OpenAIError(403, exc.detail(), param="model", code=exc.detail()["code"]) from exc + from core.api_activity import bind as bind_activity, update_current + update_current(engine=backend.id) + # Compressed formats need ffmpeg: fail fast, before any model load or GPU # work, and never fall back to a body that doesn't match the format. ffmpeg = None @@ -1006,9 +1012,15 @@ async def create_speech(req: SpeechRequest): from services.model_manager import _model_load_timeout from core import diagnostic_reports diagnostic_epoch = diagnostic_reports.inherited_grant() + update_current(stage="queued") + + def load_for_request(): + update_current(stage="loading_model") + return backend.ensure_ready() + try: await diagnostic_reports.await_owned(run_on_gpu_pool_guarded( - backend.ensure_ready, + bind_activity(load_for_request), what=f"TTS engine '{backend.id}' model load", timeout=_model_load_timeout(), ), diagnostic_epoch) @@ -1086,16 +1098,19 @@ async def create_speech(req: SpeechRequest): async def render(segment: str) -> tuple[bytes, str, str]: def generate(): + update_current(stage="generating") with engine_in_use(backend, yield_to_native=True): return _run_tts(backend, segment, kw) try: + update_current(stage="queued") wav, sr = await run_on_gpu_pool_guarded( - generate, what="OpenAI TTS generate", + bind_activity(generate), what="OpenAI TTS generate", timeout=generate_timeout_s(segment, engine=backend)) except EngineBusyError: # A native stream owns this engine until it closes. raise _native_pcm_busy() from None + update_current(stage="encoding") return await _encode_audio(wav, sr, req.response_format, ffmpeg) # Finish the first segment before sending headers so validation and @@ -1103,6 +1118,7 @@ def generate(): diagnostic_epoch = diagnostic_reports.inherited_grant() try: if native: + update_current(stage="generating") sse = req.stream_format == "sse" stream = _native_pcm_stream(backend, text, kw, sse=sse) first = await diagnostic_reports.await_owned(anext(stream), diagnostic_epoch) @@ -1410,7 +1426,10 @@ async def _transcribe_request( explicit_engine = model if _is_asr_engine_id(model) else None def _run(): + from core.api_activity import update_current + update_current(stage="loading_model") backend = load_active_asr_backend(warm=True, require_installed=require_installed) + update_current(stage="generating", engine=getattr(backend, "id", None)) if explicit_engine and getattr(backend, "id", None) != explicit_engine: raise _ModelNotActive(explicit_engine, getattr(backend, "id", "?")) extra = _backend_request_kwargs(backend, options) @@ -1422,8 +1441,10 @@ def _run(): raise _TaskUnsupported(backend.id) return backend.transcribe(tmp_path, word_timestamps=word_ts, **extra) + from core.api_activity import bind as bind_activity, update_current + update_current(stage="queued") result = await diagnostic_reports.await_owned( - run_transcribe_guarded(_gpu_pool, _run, what="OpenAI", audio_path=tmp_path), diagnostic_epoch) + run_transcribe_guarded(_gpu_pool, bind_activity(_run), what="OpenAI", audio_path=tmp_path), diagnostic_epoch) segments = _result_segments(result) full_text = (result.get("text") or "").strip() if not segments else " ".join( diff --git a/backend/core/activity.py b/backend/core/activity.py index d5316f48d6..bc7cd13b56 100644 --- a/backend/core/activity.py +++ b/backend/core/activity.py @@ -18,7 +18,7 @@ logger = logging.getLogger("omnivoice.activity") # Polls of these paths are how owners observe the backend; they are not use. -_PASSIVE_PATHS = frozenset({"/health", "/startup/progress", "/system/activity"}) +_PASSIVE_PATHS = frozenset({"/health", "/startup/progress", "/system/activity", "/system/api-activity"}) _lock = threading.Lock() _inflight = 0 diff --git a/backend/core/api_activity.py b/backend/core/api_activity.py new file mode 100644 index 0000000000..2e46ae5a9d --- /dev/null +++ b/backend/core/api_activity.py @@ -0,0 +1,323 @@ +"""Bounded, content-free activity for local speech API requests.""" +from __future__ import annotations + +import asyncio +from collections import deque +from contextvars import ContextVar +from functools import wraps +import json +import logging +import re +import threading +import time +import uuid + +from starlette.types import ASGIApp, Receive, Scope, Send +from starlette.requests import ClientDisconnect + +STAGES = frozenset({"received", "queued", "loading_model", "generating", "encoding", "streaming"}) +ERROR_CODES = frozenset({"http_error", "internal_error", "client_disconnected", "stream_error"}) +_CURRENT = ContextVar("speech_api_activity", default=None) +_IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9._/-]{0,159}\Z") +logger = logging.getLogger("omnivoice.api_activity") + + +def _identifier(value): + # Only explicitly supplied model/engine identifiers, never filesystem paths. + if isinstance(value, str) and _IDENTIFIER.fullmatch(value) and ".." not in value: + return value + return None + + +class RequestActivityStore: + """Keep active requests separate so a burst cannot evict ongoing work.""" + + def __init__(self, limit: int = 200, max_active: int = 128): + self.limit = max(1, min(int(limit), 1000)) + self.max_active = max(1, min(int(max_active), 1000)) + self._active = {} + self._recent = deque(maxlen=self.limit) + self._lock = threading.Lock() + self._dropped = 0 + + def start(self, method: str, path: str, source: str) -> str | None: + with self._lock: + if len(self._active) >= self.max_active: + self._dropped += 1 + return None + identity = uuid.uuid4().hex + self._active[identity] = { + "id": identity, "method": method, "path": path, "source": source, + "status": "running", "stage": "received", "engine": None, "model": None, + "started_at": time.time(), "finished_at": None, "elapsed_ms": 0, + "http_status": None, "response_bytes": 0, "error_code": None, + "_started": time.monotonic(), + } + return identity + + def update(self, identity, *, stage=None, engine=None, model=None, http_status=None, response_bytes=None): + with self._lock: + record = self._active.get(identity) + if record is None: + return + if isinstance(stage, str) and stage in STAGES: + record["stage"] = stage + if isinstance(http_status, int) and 100 <= http_status <= 599: + record["http_status"] = http_status + if isinstance(response_bytes, int) and response_bytes >= 0: + record["response_bytes"] = response_bytes + for key, value in (("engine", engine), ("model", model)): + if _identifier(value) is not None: + record[key] = value + + def mark_error(self, identity, code="stream_error"): + with self._lock: + if identity in self._active and code in ERROR_CODES: + self._active[identity]["error_code"] = code + + def finish(self, identity, *, status="completed", http_status=None, response_bytes=0, error_code=None): + with self._lock: + record = self._active.pop(identity, None) + if record is None: + return + if error_code in ERROR_CODES: + record["error_code"] = error_code + if status == "completed" and record["error_code"]: + status = "failed" + record.update( + status=status, stage=status, http_status=http_status, + response_bytes=max(0, int(response_bytes)), finished_at=time.time(), + elapsed_ms=round((time.monotonic() - record.pop("_started")) * 1000), + ) + if len(self._recent) == self.limit: + self._dropped += 1 + self._recent.append(record) + return dict(record) + + def snapshot(self) -> dict: + with self._lock: + records = [dict(record) for record in self._recent] + now = time.monotonic() + for record in self._active.values(): + public = dict(record) + public["elapsed_ms"] = round((now - public.pop("_started")) * 1000) + records.append(public) + records.sort(key=lambda item: item["started_at"], reverse=True) + return {"requests": records, "dropped": self._dropped, "limit": self.limit} + + def error_response(self, identity, http_status, response_bytes=0): + """Correlate an error produced by Starlette's outer error boundary.""" + with self._lock: + for record in reversed(self._recent): + if record["id"] != identity: + continue + record["http_status"] = http_status + record["response_bytes"] += max(0, int(response_bytes)) + if http_status == 499: + record.update(status="cancelled", stage="cancelled", error_code="client_disconnected") + break + + def clear_finished(self) -> int: + with self._lock: + count = len(self._recent) + self._recent.clear() + self._dropped = 0 + return count + + +store = RequestActivityStore() + + +def update_current(*, stage=None, engine=None, model=None): + current = _CURRENT.get() + if current is not None: + activity_store, identity = current + activity_store.update(identity, stage=stage, engine=engine, model=model) + + +def mark_error_current(code="stream_error"): + current = _CURRENT.get() + if current is not None: + current[0].mark_error(current[1], code) + + +def bind(function): + """Carry only activity identity into an executor; leave other contexts alone.""" + current = _CURRENT.get() + if current is None: + return function + + @wraps(function) + def wrapped(*args, **kwargs): + token = _CURRENT.set(current) + try: + return function(*args, **kwargs) + finally: + _CURRENT.reset(token) + return wrapped + + +def track_error_response(handler): + """Preserve error-handler responses and their request correlation header.""" + @wraps(handler) + async def wrapped(request, exc): + response = await handler(request, exc) + current = request.scope.get("_voicestudio_api_activity") + if current is not None and not request.scope.get("_voicestudio_api_response_started"): + activity_store, identity = current + response.headers["X-VoiceStudio-Request-ID"] = identity + exposed = response.headers.get("Access-Control-Expose-Headers", "") + names = [name.strip() for name in exposed.split(",") if name.strip()] + if not any(name.lower() == "x-voicestudio-request-id" for name in names): + names.append("X-VoiceStudio-Request-ID") + response.headers["Access-Control-Expose-Headers"] = ", ".join(names) + activity_store.error_response(identity, response.status_code, len(getattr(response, "body", b""))) + logger.info("API error response %s: HTTP %s", identity, response.status_code) + return response + return wrapped + + +def _tracked_path(scope): + if scope.get("type") != "http" or scope.get("method") != "POST": + return None + path = scope.get("path", "") + if path in {"/v1/audio/speech", "/v1/audio/transcriptions", "/v1/audio/translations"}: + return path, "openai" + if path in {"/generate", "/generate/stream"}: + return path, "native" + for prefix in ("/elevenlabs/v1/text-to-speech/", "/v1/text-to-speech/"): + if path.startswith(prefix): + pieces = path[len(prefix):].split("/") + tail = tuple(pieces[1:]) + if pieces[0] and tail in {(), ("stream",), ("with-timestamps",), ("stream", "with-timestamps")}: + suffix = "/" + "/".join(tail) if tail else "" + return prefix + "{voice_id}" + suffix, "elevenlabs" + return None + + +class _SseFailureDetector: + """Inspect bounded SSE lines for coarse error signals, retaining no payload.""" + + def __init__(self): + self.pending = bytearray() + self.oversized = False + self.failed = False + + def feed(self, chunk): + for part in chunk.splitlines(keepends=True): + ended = part.endswith((b"\n", b"\r")) + if not self.oversized: + if len(self.pending) + len(part) > 16384: + self.pending.clear() + self.oversized = True + else: + self.pending.extend(part) + if not ended: + continue + if not self.oversized: + line = bytes(self.pending).strip() + if line.startswith(b"event:") and line[6:].strip() == b"error": + self.failed = True + elif line.startswith(b"data:") or line.startswith(b"{"): + try: + value = json.loads(line[5:].strip() if line.startswith(b"data:") else line) + except (ValueError, UnicodeError, RecursionError): + value = None + if isinstance(value, dict) and (value.get("type") == "error" or value.get("type") == "speech.audio.error" or bool(value.get("error"))): + self.failed = True + self.pending.clear() + self.oversized = False + + +class ApiActivityMiddleware: + """Observe the full ASGI response without consuming or retaining request data.""" + + def __init__(self, app: ASGIApp, activity_store=store): + self.app = app + self.store = activity_store + + async def __call__(self, scope: Scope, receive: Receive, send: Send): + tracked = _tracked_path(scope) + if tracked is None: + await self.app(scope, receive, send) + return + identity = self.store.start("POST", *tracked) + if identity is None: + await self.app(scope, receive, send) + return + logger.info("API request %s POST %s: received", identity, tracked[0]) + token = _CURRENT.set((self.store, identity)) + scope["_voicestudio_api_activity"] = (self.store, identity) + http_status = None + response_bytes = 0 + complete = False + disconnected = False + streaming = False + detector = _SseFailureDetector() + outcome, error = "failed", "internal_error" + + async def observed_receive(): + nonlocal disconnected + message = await receive() + if message["type"] == "http.disconnect": + disconnected = True + return message + + async def observed_send(message): + nonlocal http_status, response_bytes, complete, streaming, disconnected + if message["type"] == "http.response.start": + http_status = message["status"] + headers = [(k, v) for k, v in message.get("headers", []) if k.lower() != b"x-voicestudio-request-id"] + headers.append((b"x-voicestudio-request-id", identity.encode("ascii"))) + streaming = any( + k.lower() == b"content-type" and any( + mime in v.lower() for mime in (b"text/event-stream", b"application/x-ndjson", b"application/ndjson") + ) for k, v in headers + ) + message = {**message, "headers": headers} + try: + await send(message) + except OSError: + disconnected = True + raise + if message["type"] == "http.response.start": + scope["_voicestudio_api_response_started"] = True + self.store.update(identity, http_status=http_status) + if message["type"] == "http.response.body": + body = message.get("body", b"") + response_bytes += len(body) + self.store.update(identity, response_bytes=response_bytes) + if streaming: + detector.feed(body) + if message.get("more_body", False): + self.store.update(identity, stage="streaming") + else: + complete = True + + try: + await self.app(scope, observed_receive, observed_send) + if detector.failed: + outcome, error = "failed", "stream_error" + elif http_status is not None and http_status >= 400: + outcome, error = "failed", "http_error" + elif complete: + outcome, error = "completed", None + else: + outcome, error = "failed", "internal_error" + except asyncio.CancelledError: + outcome, error = "cancelled", "client_disconnected" + raise + except ClientDisconnect: + outcome, error = "cancelled", "client_disconnected" + raise + finally: + if disconnected and not complete: + outcome, error = "cancelled", "client_disconnected" + try: + result = self.store.finish(identity, status=outcome, http_status=http_status, + response_bytes=response_bytes, error_code=error) + if result is not None: + logger.info("API request %s POST %s: %s (HTTP %s, %d ms)", + identity, tracked[0], result["status"], http_status, result["elapsed_ms"]) + finally: + _CURRENT.reset(token) diff --git a/backend/core/render_trace.py b/backend/core/render_trace.py index c83937fa62..e2cef14f7c 100644 --- a/backend/core/render_trace.py +++ b/backend/core/render_trace.py @@ -86,6 +86,11 @@ def recent(): def stage(name: str): if name not in _STAGES: raise ValueError('Unknown render stage') + from core.api_activity import update_current + if name == 'synthesis': + update_current(stage='generating') + elif name in {'join', 'effects', 'save', 'watermark', 'mux'}: + update_current(stage='encoding') trace = _current.get() if trace is None: yield diff --git a/backend/main.py b/backend/main.py index d964e9b087..75cdbdca7b 100644 --- a/backend/main.py +++ b/backend/main.py @@ -808,6 +808,7 @@ def _phase_a_build_inner() -> None: _startup_progress.begin_step("api_routes") from api.routers import ( + api_activity, system, profiles, profile_images, @@ -855,6 +856,7 @@ def _phase_a_build_inner() -> None: from api.routers import calls as _calls_router # noqa: E402 from api.routers import cloud_sync as _cloud_sync_router # noqa: E402 _router_modules.extend([ + api_activity, system, profiles, profile_images, exports, generation, voice_convert, sfx, dub_core, dub_generate, dub_export, dub_translate, projects, glossary, engines, tools, stories, setup, gallery, demo_assets_router, archetypes, describe_voice, community, @@ -1832,7 +1834,11 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE ) +from core.api_activity import track_error_response + + @app.exception_handler(Exception) +@track_error_response async def global_exception_handler(request: Request, exc: Exception): # Client disconnected mid-stream (browser canceled a