From 40fe6e2bb989d01918ac30a54e145452f2941683 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:07:07 -0800 Subject: [PATCH 1/7] feat: add header_provider and per-call headers on WebSockets for trace context FishAudio(header_provider=...) and AsyncFishAudio(header_provider=...) take a function the SDK calls for every HTTP request and every WebSocket handshake, right before it is sent, on the caller's thread or task. It returns headers to add, such as the W3C traceparent of the caller's current request, so Fish Audio continues the caller's trace instead of starting a new one. - Headers the SDK sets (Authorization, model, User-Agent, Content-Type, the WebSocket handshake headers) cannot be set by the provider; per-call headers and headers on a custom httpx client win over it. - An exception it raises reaches the caller unchanged before anything is sent; a result that is not a mapping of str to str raises TypeError, an illegal header value ValueError (without echoing it). - tts.stream_websocket and asr.stream_websocket (sync and async) take request_options like the HTTP methods. Their handshake headers are now built when the connection opens, so the provider sees the caller's context then. - HeaderProvider and RequestOptions are exported from fishaudio. Part of FISH-2233. Co-Authored-By: Claude Opus 5.5 --- README.md | 78 ++++ src/fishaudio/__init__.py | 4 + src/fishaudio/client.py | 29 ++ src/fishaudio/core/__init__.py | 3 +- src/fishaudio/core/client_wrapper.py | 131 +++++- src/fishaudio/resources/asr.py | 28 +- src/fishaudio/resources/tts.py | 16 +- tests/unit/realtime_server.py | 7 +- tests/unit/test_header_provider.py | 583 +++++++++++++++++++++++++++ tests/unit/test_tts_realtime.py | 6 + 10 files changed, 871 insertions(+), 14 deletions(-) create mode 100644 tests/unit/test_header_provider.py diff --git a/README.md b/README.md index f1ca832..f36bc2d 100644 --- a/README.md +++ b/README.md @@ -325,6 +325,84 @@ except FishAudioError as e: print(f"API error: {e}") ``` +## Tracing + +Fish Audio continues your distributed trace when a request carries a W3C +[`traceparent`](https://www.w3.org/TR/trace-context/) header, on HTTP calls and on +both WebSockets. Pass a `header_provider`: the SDK calls it for every request and +every WebSocket handshake, right before sending, on the thread (`FishAudio`) or in +the task (`AsyncFishAudio`) that makes the call. It takes no arguments, so read your +current span or request inside it, and returns the headers to add, or `None`. + +**OpenTelemetry.** If `httpx` is instrumented (`opentelemetry-instrumentation-httpx`, +or `opentelemetry-instrument`), every SDK request, both WebSockets included, already +carries `traceparent`: you need nothing here. If it is not: + +```python +from opentelemetry.propagate import inject + +def otel_headers(): + carrier = {} + inject(carrier) # the current span's traceparent (and baggage, if configured) + return carrier + +client = FishAudio(header_provider=otel_headers) +``` + +Using both is harmless: the instrumentation replaces the provider's `traceparent` +with its own child span's. + +**Your own trace IDs.** The API accepts only a valid `traceparent` (version `00`: +32 hex digits of trace ID, 16 of parent ID, 2 of flags). Convert your IDs; an +invalid value is ignored by the API, and the request gets a new trace ID. + +```python +import contextvars +import re + +current_request = contextvars.ContextVar("current_request", default=None) # set by your middleware + +def to_traceparent(trace_id: str, span_id: str): + trace_id = trace_id.replace("-", "").lower().rjust(32, "0") # a UUID becomes 32 hex digits + span_id = span_id.lower().rjust(16, "0") + if not re.fullmatch(r"[0-9a-f]{32}", trace_id) or not re.fullmatch(r"[0-9a-f]{16}", span_id): + return None # not convertible: no header is sent + if int(trace_id, 16) == 0 or int(span_id, 16) == 0: + return None # all zeros is invalid + return f"00-{trace_id}-{span_id}-01" # 01: sampled + +def my_trace_headers(): + request = current_request.get() + if request is None: + return None # no header is added + return {"traceparent": to_traceparent(request.trace_id, request.span_id)} + +client = FishAudio(header_provider=my_trace_headers) +``` + +**No tracing.** Nothing to do. + +For one call, pass headers with `request_options`, on HTTP and WebSocket methods alike. +They win over the provider: + +```python +from fishaudio import RequestOptions + +client.tts.convert(text="Hello", request_options=RequestOptions(additional_headers={"traceparent": tp})) +client.asr.stream_websocket(audio, request_options=RequestOptions(additional_headers={"traceparent": tp})) +``` + +Rules: +- The provider cannot set `Authorization`, `model`, `User-Agent`, `Content-Type`, + `Content-Length`, `Host` or WebSocket handshake headers; those names are ignored. + Per-call headers and headers on your own `httpx_client` win over it. +- An exception it raises fails the call, unchanged, before anything is sent. A result + that is not a mapping of `str` to `str` (or `None` values, which are skipped) raises + `TypeError`; a value with line breaks raises `ValueError`. +- It runs once per request, synchronously, so keep it fast and free of I/O. With + `AsyncFishAudio` it runs on the event loop. +- Streams connect when you start iterating them; the provider runs then. + ## Resources - **Documentation:** [SDK Guide](https://docs.fish.audio/developer-guide/sdk-guide/python/) | [API Reference](https://docs.fish.audio/api-reference/sdk/python/) diff --git a/src/fishaudio/__init__.py b/src/fishaudio/__init__.py index c771486..000a07e 100644 --- a/src/fishaudio/__init__.py +++ b/src/fishaudio/__init__.py @@ -28,12 +28,14 @@ from ._version import __version__ from .client import AsyncFishAudio, FishAudio +from .core.client_wrapper import HeaderProvider from .core.iterators import ( AsyncAudioStream, AsyncTTSTimestampStream, AudioStream, TTSTimestampStream, ) +from .core.request_options import RequestOptions from .core.websocket_options import WebSocketOptions from .exceptions import ( APIError, @@ -90,6 +92,8 @@ "ASRResults", "ASRTurnDetection", "TTSConfig", + "HeaderProvider", + "RequestOptions", "WebSocketOptions", # Types "ASRContextItem", diff --git a/src/fishaudio/client.py b/src/fishaudio/client.py index 11f2aa2..53e7782 100644 --- a/src/fishaudio/client.py +++ b/src/fishaudio/client.py @@ -5,6 +5,7 @@ import httpx from .core import AsyncClientWrapper, ClientWrapper +from .core.client_wrapper import HeaderProvider from .resources import ( AccountClient, ASRClient, @@ -46,6 +47,7 @@ def __init__( base_url: str = "https://api.fish.audio", timeout: float = 240.0, httpx_client: Optional[httpx.Client] = None, + header_provider: Optional[HeaderProvider] = None, ): """ Initialize Fish Audio client. @@ -55,12 +57,25 @@ def __init__( base_url: API base URL timeout: Request timeout in seconds httpx_client: Optional custom HTTP client + header_provider: Optional function the SDK calls for every request + and WebSocket handshake, right before it is sent, to add headers + such as the W3C ``traceparent`` of your current request. It takes + no arguments and returns a mapping of header names to values, or + None. It runs on the thread (sync client) or in the task (async + client) that makes the call, so it can read ``contextvars`` and + the current OpenTelemetry span; keep it fast and free of I/O. + Headers the SDK sets (``Authorization``, ``model``, + ``User-Agent``, ``Content-Type``, WebSocket handshake headers), + per-call ``additional_headers`` and headers on ``httpx_client`` + win over it. An exception it raises fails the call, unchanged, + before anything is sent. See the README's "Tracing" section. """ self._client_wrapper = ClientWrapper( api_key=api_key, base_url=base_url, timeout=timeout, httpx_client=httpx_client, + header_provider=header_provider, ) # Lazy-loaded namespace clients @@ -140,6 +155,7 @@ def __init__( base_url: str = "https://api.fish.audio", timeout: float = 240.0, httpx_client: Optional[httpx.AsyncClient] = None, + header_provider: Optional[HeaderProvider] = None, ): """ Initialize async Fish Audio client. @@ -149,12 +165,25 @@ def __init__( base_url: API base URL timeout: Request timeout in seconds httpx_client: Optional custom async HTTP client + header_provider: Optional function the SDK calls for every request + and WebSocket handshake, right before it is sent, to add headers + such as the W3C ``traceparent`` of your current request. It takes + no arguments and returns a mapping of header names to values, or + None. It runs on the thread (sync client) or in the task (async + client) that makes the call, so it can read ``contextvars`` and + the current OpenTelemetry span; keep it fast and free of I/O. + Headers the SDK sets (``Authorization``, ``model``, + ``User-Agent``, ``Content-Type``, WebSocket handshake headers), + per-call ``additional_headers`` and headers on ``httpx_client`` + win over it. An exception it raises fails the call, unchanged, + before anything is sent. See the README's "Tracing" section. """ self._client_wrapper = AsyncClientWrapper( api_key=api_key, base_url=base_url, timeout=timeout, httpx_client=httpx_client, + header_provider=header_provider, ) # Lazy-loaded namespace clients diff --git a/src/fishaudio/core/__init__.py b/src/fishaudio/core/__init__.py index 2b0cc45..e1684a7 100644 --- a/src/fishaudio/core/__init__.py +++ b/src/fishaudio/core/__init__.py @@ -1,6 +1,6 @@ """Core infrastructure for the Fish Audio SDK.""" -from .client_wrapper import AsyncClientWrapper, ClientWrapper +from .client_wrapper import AsyncClientWrapper, ClientWrapper, HeaderProvider from .omit import OMIT from .request_options import RequestOptions from .websocket_options import WebSocketOptions @@ -8,6 +8,7 @@ __all__ = [ "AsyncClientWrapper", "ClientWrapper", + "HeaderProvider", "OMIT", "RequestOptions", "WebSocketOptions", diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 31cbf7f..8efac97 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -4,8 +4,9 @@ import platform import re import sys +from collections.abc import Iterable, Mapping from json import JSONDecodeError -from typing import Any, Optional, Union +from typing import Any, Callable, Optional, Union import httpx @@ -133,6 +134,90 @@ def _caller_user_agent( return value +HeaderProvider = Callable[[], Optional[Mapping[str, Optional[str]]]] +"""A function the SDK calls for every outgoing request and WebSocket handshake. + +It takes no arguments: read the caller's current state (an OpenTelemetry span, +a ``contextvars.ContextVar``) inside it. It returns the headers to add, or +``None`` to add none; a header whose value is ``None`` is skipped. See +``FishAudio(header_provider=...)``. +""" + +# Headers the SDK sets itself or that the HTTP and WebSocket protocols own. A +# header provider can never set them, so it cannot replace the API key or the +# model by accident, e.g. when it copies an inbound request's headers. +_RESERVED_HEADERS = frozenset( + { + "authorization", + "model", + "user-agent", + "content-type", + "content-length", + "host", + "connection", + "upgrade", + "transfer-encoding", + } +) + +# RFC 9110 token characters, for header names. +_HEADER_NAME = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+") +# Control characters other than horizontal tab may not appear in a header value. +_FORBIDDEN_IN_VALUE = re.compile(r"[\x00-\x08\x0a-\x1f\x7f]") + + +def _is_reserved(name: str) -> bool: + lowered = name.lower() + return lowered in _RESERVED_HEADERS or lowered.startswith("sec-websocket-") + + +def _provided_headers( + provider: Optional[HeaderProvider], taken: Iterable[str] +) -> dict[str, str]: + """Call ``provider`` and return the headers it may add to a request. + + ``taken`` are the names the request already has (any casing): they win + over the provider, as do the reserved names. An exception raised by the + provider reaches the caller unchanged, before anything is sent. + """ + if provider is None: + return {} + result = provider() + if result is None: + return {} + if not isinstance(result, Mapping): + raise TypeError( + "header_provider must return a mapping of header names to strings or None, " + f"not {type(result).__name__}" + ) + taken_names = {name.lower() for name in taken} + headers: dict[str, str] = {} + for name, value in result.items(): + if value is None: + continue + if not isinstance(name, str) or not isinstance(value, str): + raise TypeError( + "header_provider must return header names and values as str, " + f"got {type(name).__name__}: {type(value).__name__}" + ) + if not _HEADER_NAME.fullmatch(name): + raise ValueError( + f"header_provider returned an invalid header name {name!r}" + ) + if _FORBIDDEN_IN_VALUE.search(value): + # The value is not echoed: it may be a credential. + raise ValueError( + f"header_provider returned an invalid value for header {name!r}" + ) + if _is_reserved(name) or name.lower() in taken_names: + continue + # One spelling per name: a later one replaces an earlier one. + for existing in [n for n in headers if n.lower() == name.lower()]: + del headers[existing] + headers[name] = value + return headers + + class BaseClientWrapper: """Base wrapper with shared logic for sync/async clients.""" @@ -141,13 +226,17 @@ def __init__( *, api_key: Optional[str] = None, base_url: str = "https://api.fish.audio", + header_provider: Optional[HeaderProvider] = None, ): self.api_key = api_key or os.getenv("FISH_API_KEY") if not self.api_key: raise ValueError( "API key must be provided either as argument or via FISH_API_KEY environment variable" ) + if header_provider is not None and not callable(header_provider): + raise TypeError("header_provider must be callable") self.base_url = base_url + self.header_provider = header_provider def get_headers( self, additional_headers: Optional[dict[str, str]] = None @@ -182,10 +271,23 @@ def _prepare_request_kwargs( # {"Model": ...} from request options must not travel next to {"model": ...}. explicit = kwargs.get("headers", {}) explicit_names = {name.lower() for name in explicit} - kwargs["headers"] = { + merged = { **{k: v for k, v in headers.items() if k.lower() not in explicit_names}, **explicit, } + # The header provider runs last, once per request, on the caller's + # thread or task, so it sees the caller's context at the moment the + # request is sent. Every header set so far, and the headers set on the + # httpx client, win over it. (A retry loop added here later must call + # this once per attempt.) + client = getattr(self, "_client", None) + merged.update( + _provided_headers( + self.header_provider, + [*merged, *(client.headers.keys() if client is not None else [])], + ) + ) + kwargs["headers"] = merged # Apply timeout override if provided if request_options and request_options.timeout is not None: @@ -198,6 +300,21 @@ def _prepare_request_kwargs( params.update(request_options.additional_query_params) kwargs["params"] = params + def websocket_kwargs( + self, model: str, request_options: Optional[RequestOptions] + ) -> dict[str, Any]: + """Headers and query parameters for a WebSocket handshake. + + Call it when the connection is opened, not before, so the header + provider sees the caller's context of that moment. Request options + apply as on HTTP requests, except ``timeout``: WebSocket timeouts are + set with ``WebSocketOptions``. + """ + kwargs: dict[str, Any] = {"headers": {"model": model}} + self._prepare_request_kwargs(request_options, kwargs) + kwargs.pop("timeout", None) + return kwargs + class ClientWrapper(BaseClientWrapper): """Wrapper for httpx.Client that handles authentication and error handling.""" @@ -209,8 +326,11 @@ def __init__( base_url: str = "https://api.fish.audio", timeout: float = 240.0, httpx_client: Optional[httpx.Client] = None, + header_provider: Optional[HeaderProvider] = None, ): - super().__init__(api_key=api_key, base_url=base_url) + super().__init__( + api_key=api_key, base_url=base_url, header_provider=header_provider + ) if httpx_client is not None: self._client = httpx_client @@ -299,8 +419,11 @@ def __init__( base_url: str = "https://api.fish.audio", timeout: float = 240.0, httpx_client: Optional[httpx.AsyncClient] = None, + header_provider: Optional[HeaderProvider] = None, ): - super().__init__(api_key=api_key, base_url=base_url) + super().__init__( + api_key=api_key, base_url=base_url, header_provider=header_provider + ) if httpx_client is not None: self._client = httpx_client diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 514c5ac..d64a577 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -142,6 +142,7 @@ def stream_websocket( config: ASRRealtimeConfig = ASRRealtimeConfig(), model: str = "transcribe-stream-1", ws_options: Optional[WebSocketOptions] = None, + request_options: Optional[RequestOptions] = None, ) -> ASRRealtimeStream: """ Stream audio and receive transcripts in real-time via WebSocket. @@ -178,6 +179,9 @@ def stream_websocket( model: Realtime speech-to-text model ws_options: WebSocket connection options for configuring timeouts, message size limits, etc. See WebSocketOptions class for available parameters. + request_options: Request-level overrides for the handshake, as on HTTP + calls: ``additional_headers`` and ``additional_query_params`` (``timeout`` + does not apply here; use ``ws_options``) Returns: ASRRealtimeStream: an iterator of typed events (check event.type), with @@ -226,12 +230,16 @@ def audio_chunks(): ``` """ ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - headers = self._client.get_headers({"model": model}) - client = self._client.client + wrapper = self._client + # Headers are built when the session connects (first iteration), so the + # header provider sees the caller's context of that moment. return ASRRealtimeStream( lambda: connect_ws( - REALTIME_PATH, client=client, headers=headers, **ws_kwargs + REALTIME_PATH, + client=wrapper.client, + **wrapper.websocket_kwargs(model, request_options), + **ws_kwargs, ), _realtime_config( config, @@ -329,6 +337,7 @@ def stream_websocket( config: ASRRealtimeConfig = ASRRealtimeConfig(), model: str = "transcribe-stream-1", ws_options: Optional[WebSocketOptions] = None, + request_options: Optional[RequestOptions] = None, ) -> AsyncASRRealtimeStream: """ Stream audio and receive transcripts in real-time via WebSocket (async). @@ -365,6 +374,9 @@ def stream_websocket( model: Realtime speech-to-text model ws_options: WebSocket connection options for configuring timeouts, message size limits, etc. See WebSocketOptions class for available parameters. + request_options: Request-level overrides for the handshake, as on HTTP + calls: ``additional_headers`` and ``additional_query_params`` (``timeout`` + does not apply here; use ``ws_options``) Returns: AsyncASRRealtimeStream: an async iterator of typed events (check event.type), with @@ -413,12 +425,16 @@ async def audio_chunks(): ``` """ ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - headers = self._client.get_headers({"model": model}) - client = self._client.client + wrapper = self._client + # Headers are built when the session connects (first iteration), so the + # header provider sees the caller's context of that moment. return AsyncASRRealtimeStream( lambda: aconnect_ws( - REALTIME_PATH, client=client, headers=headers, **ws_kwargs + REALTIME_PATH, + client=wrapper.client, + **wrapper.websocket_kwargs(model, request_options), + **ws_kwargs, ), _realtime_config( config, diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 73d83f2..15f5e09 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -448,6 +448,7 @@ def stream_websocket( model: Union[Model, str] = "s2.1-pro", max_workers: int = 10, ws_options: Optional[WebSocketOptions] = None, + request_options: Optional[RequestOptions] = None, ) -> Iterator[bytes]: """ Stream text and receive audio in real-time via WebSocket. @@ -467,6 +468,9 @@ def stream_websocket( ws_options: WebSocket connection options for configuring timeouts, message size limits, etc. Useful for long-running generations that may exceed default timeout values. See WebSocketOptions class for available parameters. + request_options: Request-level overrides for the handshake, as on HTTP + calls: ``additional_headers`` and ``additional_query_params`` (``timeout`` + does not apply here; use ``ws_options``) Returns: Iterator of audio bytes @@ -560,10 +564,12 @@ def text_generator(): try: ws: WebSocketSession + # Built here, when iteration opens the connection, so the header + # provider sees the caller's context of that moment. with connect_ws( "/v1/tts/live", client=self._client.client, - headers=self._client.get_headers({"model": model}), + **self._client.websocket_kwargs(model, request_options), **ws_kwargs, ) as ws: @@ -914,6 +920,7 @@ async def stream_websocket( config: TTSConfig = TTSConfig(), model: Union[Model, str] = "s2.1-pro", ws_options: Optional[WebSocketOptions] = None, + request_options: Optional[RequestOptions] = None, ): """ Stream text and receive audio in real-time via WebSocket (async). @@ -932,6 +939,9 @@ async def stream_websocket( ws_options: WebSocket connection options for configuring timeouts, message size limits, etc. Useful for long-running generations that may exceed default timeout values. See WebSocketOptions class for available parameters. + request_options: Request-level overrides for the handshake, as on HTTP + calls: ``additional_headers`` and ``additional_query_params`` (``timeout`` + does not apply here; use ``ws_options``) Returns: Async iterator of audio bytes @@ -1022,10 +1032,12 @@ async def text_generator(): ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} ws: AsyncWebSocketSession + # Built here, when iteration opens the connection, so the header + # provider sees the caller's context of that moment. async with aconnect_ws( "/v1/tts/live", client=self._client.client, - headers=self._client.get_headers({"model": model}), + **self._client.websocket_kwargs(model, request_options), **ws_kwargs, ) as ws: diff --git a/tests/unit/realtime_server.py b/tests/unit/realtime_server.py index 550e573..12a0aee 100644 --- a/tests/unit/realtime_server.py +++ b/tests/unit/realtime_server.py @@ -48,6 +48,8 @@ def __init__(self, sock: socket.socket, reject_status: Optional[int]): self._pending: deque[dict[str, Any]] = deque() self._partial = b"" self.headers: dict[str, str] = {} + # Every handshake header in order, repeated names included. + self.header_list: list[tuple[str, str]] = [] self.path: Optional[str] = None self.received: list[dict[str, Any]] = [] self.close_code: Optional[int] = None @@ -68,7 +70,10 @@ def _read(self) -> None: for event in self._ws.events(): if isinstance(event, Request): self.path = event.target - self.headers = {k.decode(): v.decode() for k, v in event.extra_headers} + self.header_list = [ + (k.decode(), v.decode()) for k, v in event.extra_headers + ] + self.headers = dict(self.header_list) if self._reject_status is not None: self._write(RejectConnection(status_code=self._reject_status)) raise ClientGone diff --git a/tests/unit/test_header_provider.py b/tests/unit/test_header_provider.py new file mode 100644 index 0000000..5cd3909 --- /dev/null +++ b/tests/unit/test_header_provider.py @@ -0,0 +1,583 @@ +"""The header provider and per-call headers, against real local servers. + +Each test records the raw headers a request arrived with, repeated names +included, so a header sent twice is caught. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import contextvars +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import TYPE_CHECKING, Any, Optional + +import httpx +import pytest +from httpx_ws import WebSocketUpgradeError + +from fishaudio import AsyncFishAudio, FishAudio, RequestOptions +from fishaudio.core.client_wrapper import USER_AGENT +from fishaudio.exceptions import AuthenticationError, ServerError + +from .realtime_server import RealtimeServer + +if TYPE_CHECKING: + from collections.abc import Iterator + +VOICE = { + "_id": "v", + "type": "tts", + "title": "v", + "description": "", + "cover_image": "", + "train_mode": "fast", + "state": "trained", + "tags": [], + "samples": [], + "created_at": "2026-01-01T00:00:00Z", + "updated_at": "2026-01-01T00:00:00Z", + "languages": [], + "visibility": "private", + "lock_visibility": False, + "like_count": 0, + "mark_count": 0, + "shared_count": 0, + "task_count": 0, + "liked": False, + "marked": False, + "author": {"_id": "a", "nickname": "a", "avatar": ""}, +} + +TRACE_A = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" +TRACE_B = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" + +current_trace: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar( + "current_trace", default=None +) + + +def from_contextvar() -> Optional[dict[str, Optional[str]]]: + return {"traceparent": current_trace.get()} + + +class _Recorder(BaseHTTPRequestHandler): + """Records each request's headers and answers ``status``.""" + + seen: list[tuple[str, list[tuple[str, str]]]] + status = 200 + + def _answer(self) -> None: + self.rfile.read(int(self.headers.get("Content-Length") or 0)) + type(self).seen.append((self.path, list(self.headers.items()))) + if self.status != 200: + body, content_type = b'{"message": "nope"}', "application/json" + elif self.path.startswith("/v1/tts"): + body, content_type = b"\x01\x02", "audio/mpeg" + elif self.path.startswith("/v1/asr"): + body = b'{"text": "", "duration": 0, "segments": []}' + content_type = "application/json" + elif self.path.startswith("/model") and self.command == "GET": + body, content_type = b'{"items": [], "total": 0}', "application/json" + elif self.path.startswith("/model"): + body, content_type = json.dumps(VOICE).encode(), "application/json" + else: + body = ( + b'{"_id": "c", "user_id": "u", "credit": "1",' + b' "created_at": "2026-01-01", "updated_at": "2026-01-01"}' + ) + content_type = "application/json" + self.send_response(self.status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + do_GET = do_POST = do_PATCH = do_DELETE = _answer + + def log_message(self, *args: Any) -> None: + pass + + +@contextlib.contextmanager +def recording_server(status: int = 200) -> Iterator[tuple[str, list]]: + handler = type("Handler", (_Recorder,), {"seen": [], "status": status}) + # The default listen backlog (5) refuses bursts of concurrent connections. + server_class = type("Server", (ThreadingHTTPServer,), {"request_queue_size": 128}) + server = server_class(("127.0.0.1", 0), handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}", handler.seen + finally: + server.shutdown() + server.server_close() + + +def values(headers: list[tuple[str, str]], name: str) -> list[str]: + return [v for k, v in headers if k.lower() == name.lower()] + + +@contextlib.contextmanager +def refusing_ws_server() -> Iterator[RealtimeServer]: + """Records the handshake, then refuses it with 401.""" + server = RealtimeServer(lambda conn: None, reject_status=401) + try: + yield server + finally: + server.close() + + +class Counter: + """A provider that counts its calls and returns the contextvar's trace.""" + + def __init__(self) -> None: + self.calls = 0 + self.threads: list[int] = [] + + def __call__(self) -> dict[str, Optional[str]]: + self.calls += 1 + self.threads.append(threading.get_ident()) + return {"traceparent": current_trace.get()} + + +class TestHTTP: + def test_every_endpoint_type_gets_it_once_per_request(self): + provider = Counter() + token = current_trace.set(TRACE_A) + try: + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", base_url=url, header_provider=provider + ) + client.account.get_credits() + client.voices.list() + client.voices.create(title="v", voices=[b"\x00"]) + client.tts.convert(text="hi") + client.tts.stream(text="hi").collect() + client.asr.transcribe(audio=b"\x00\x01") + client.close() + finally: + current_trace.reset(token) + assert provider.calls == len(seen) == 6 + for path, headers in seen: + assert values(headers, "traceparent") == [TRACE_A], path + assert values(headers, "authorization") == ["Bearer test-key"], path + + def test_called_at_send_time_with_the_callers_context(self): + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", base_url=url, header_provider=from_contextvar + ) + for trace in (TRACE_A, TRACE_B): + token = current_trace.set(trace) + try: + client.account.get_credits() + finally: + current_trace.reset(token) + client.account.get_credits() # no trace in context: no header + client.close() + assert [values(h, "traceparent") for _, h in seen] == [ + [TRACE_A], + [TRACE_B], + [], + ] + + def test_called_once_for_a_failing_request(self): + provider = Counter() + with recording_server(status=500) as (url, seen): + client = FishAudio( + api_key="test-key", base_url=url, header_provider=provider + ) + with pytest.raises(ServerError): + client.account.get_credits() + client.close() + assert provider.calls == 1 + assert len(seen) == 1 + + def test_concurrent_threads_each_send_their_own_value(self): + provider = Counter() + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", base_url=url, header_provider=provider + ) + barrier = threading.Barrier(16) + + def call(i: int) -> None: + current_trace.set(f"00-{i:032x}-00f067aa0ba902b7-01") + barrier.wait() + client.account.get_credits( + request_options=RequestOptions( + additional_headers={"x-call": str(i)} + ) + ) + + threads = [threading.Thread(target=call, args=(i,)) for i in range(16)] + for t in threads: + t.start() + for t in threads: + t.join() + client.close() + assert len(seen) == 16 + for _, headers in seen: + (call_id,) = values(headers, "x-call") + assert values(headers, "traceparent") == [ + f"00-{int(call_id):032x}-00f067aa0ba902b7-01" + ] + # Called on the calling threads only. + assert len(set(provider.threads)) == 16 + + async def test_async_tasks_each_send_their_own_value(self): + with recording_server() as (url, seen): + client = AsyncFishAudio( + api_key="test-key", base_url=url, header_provider=from_contextvar + ) + + async def call(i: int) -> None: + current_trace.set(f"00-{i:032x}-00f067aa0ba902b7-01") + await asyncio.sleep(0) # let the other tasks interleave + await client.account.get_credits( + request_options=RequestOptions( + additional_headers={"x-call": str(i)} + ) + ) + + await asyncio.gather(*(call(i) for i in range(32))) + await client.close() + assert len(seen) == 32 + for _, headers in seen: + (call_id,) = values(headers, "x-call") + assert values(headers, "traceparent") == [ + f"00-{int(call_id):032x}-00f067aa0ba902b7-01" + ] + + async def test_async_every_endpoint_type(self): + token = current_trace.set(TRACE_B) + try: + with recording_server() as (url, seen): + client = AsyncFishAudio( + api_key="test-key", base_url=url, header_provider=from_contextvar + ) + await client.account.get_credits() + await client.voices.list() + await client.tts.convert(text="hi") + await client.asr.transcribe(audio=b"\x00\x01") + await client.close() + finally: + current_trace.reset(token) + assert len(seen) == 4 + for path, headers in seen: + assert values(headers, "traceparent") == [TRACE_B], path + + def test_per_call_header_wins_over_the_provider(self): + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", + base_url=url, + header_provider=lambda: {"traceparent": TRACE_A, "baggage": "k=v"}, + ) + client.tts.convert( + text="hi", + request_options=RequestOptions( + additional_headers={"TraceParent": TRACE_B} + ), + ) + client.close() + headers = seen[0][1] + assert values(headers, "traceparent") == [TRACE_B] + assert values(headers, "baggage") == ["k=v"] + + def test_headers_on_a_custom_httpx_client_win_over_the_provider(self): + with recording_server() as (url, seen): + own = httpx.Client(base_url=url, headers={"x-request-id": "static"}) + client = FishAudio( + api_key="test-key", + httpx_client=own, + header_provider=lambda: { + "X-Request-Id": "dynamic", + "traceparent": TRACE_A, + }, + ) + client.account.get_credits() + own.close() + headers = seen[0][1] + assert values(headers, "x-request-id") == ["static"] + assert values(headers, "traceparent") == [TRACE_A] + + def test_cannot_replace_sdk_headers(self): + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", + base_url=url, + header_provider=lambda: { + "authorization": "Bearer stolen", + "Authorization": "Bearer stolen", + "model": "s1", + "User-Agent": "evil/1", + "Content-Type": "text/plain", + "Content-Length": "1", + "Host": "example.com", + "Connection": "close", + "Sec-WebSocket-Key": "x", + "traceparent": TRACE_A, + }, + ) + client.tts.convert(text="hi", model="s2-pro") + client.close() + headers = seen[0][1] + assert values(headers, "authorization") == ["Bearer test-key"] + assert values(headers, "model") == ["s2-pro"] + assert values(headers, "user-agent") == [USER_AGENT] + assert values(headers, "content-type") == ["application/msgpack"] + assert values(headers, "host") != ["example.com"] + assert values(headers, "sec-websocket-key") == [] + assert values(headers, "traceparent") == [TRACE_A] + + @pytest.mark.parametrize("result", [None, {}, {"traceparent": None}]) + def test_returning_nothing_adds_nothing(self, result): + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", base_url=url, header_provider=lambda: result + ) + client.account.get_credits() + client.close() + assert values(seen[0][1], "traceparent") == [] + + def test_an_exception_reaches_the_caller_unchanged_and_nothing_is_sent(self): + error = RuntimeError("tracer is down") + + def provider(): + raise error + + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", base_url=url, header_provider=provider + ) + with pytest.raises(RuntimeError) as info: + client.tts.convert(text="hi") + client.close() + assert info.value is error + assert seen == [] + + @pytest.mark.parametrize( + "result, error", + [ + (["traceparent", TRACE_A], TypeError), + ({"traceparent": 1}, TypeError), + ({1: "x"}, TypeError), + ({"traceparent": b"00-..."}, TypeError), + ({"traceparent": "a\r\nInjected: yes"}, ValueError), + ({"bad name": "x"}, ValueError), + ], + ) + def test_invalid_results_fail_before_sending(self, result, error): + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", base_url=url, header_provider=lambda: result + ) + with pytest.raises(error) as info: + client.account.get_credits() + client.close() + assert seen == [] + assert "Injected" not in str(info.value) # the value is never echoed + + def test_must_be_callable(self): + with pytest.raises(TypeError): + FishAudio(api_key="test-key", header_provider={"traceparent": TRACE_A}) # type: ignore[arg-type] + + def test_without_a_provider_nothing_changes(self): + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + client.account.get_credits() + client.close() + assert values(seen[0][1], "traceparent") == [] + assert values(seen[0][1], "authorization") == ["Bearer test-key"] + + +class TestWebSockets: + """Both handshakes, sync and async. The server refuses them after recording.""" + + def test_tts_handshake_sync(self): + provider = Counter() + with refusing_ws_server() as server: + client = FishAudio( + api_key="test-key", base_url=server.url, header_provider=provider + ) + stream = client.tts.stream_websocket( + iter(["hi"]), + model="s2-pro", + request_options=RequestOptions(additional_headers={"x-call": "1"}), + ) + assert provider.calls == 0 # nothing happens before iteration + token = current_trace.set(TRACE_A) + try: + with pytest.raises(WebSocketUpgradeError): + list(stream) + finally: + current_trace.reset(token) + client.close() + conn = server.stop() + assert provider.calls == 1 + assert conn.path == "/v1/tts/live" + assert values(conn.header_list, "traceparent") == [TRACE_A] + assert values(conn.header_list, "x-call") == ["1"] + assert values(conn.header_list, "model") == ["s2-pro"] + assert values(conn.header_list, "authorization") == ["Bearer test-key"] + + async def test_tts_handshake_async(self): + with refusing_ws_server() as server: + client = AsyncFishAudio( + api_key="test-key", base_url=server.url, header_provider=from_contextvar + ) + + async def text(): + yield "hi" + + current_trace.set(TRACE_B) + with pytest.raises(WebSocketUpgradeError): + async for _ in client.tts.stream_websocket( + text(), + request_options=RequestOptions( + additional_headers={"traceparent": TRACE_A} + ), + ): + pass + await client.close() + conn = server.stop() + # The per-call header wins over the provider. + assert values(conn.header_list, "traceparent") == [TRACE_A] + + def test_asr_realtime_handshake_sync_reads_context_when_iterated(self): + with refusing_ws_server() as server: + client = FishAudio( + api_key="test-key", base_url=server.url, header_provider=from_contextvar + ) + token = current_trace.set(TRACE_A) + stream = client.asr.stream_websocket( + iter([b"\x00\x00"]), + request_options=RequestOptions( + additional_headers={"x-call": "2"}, + additional_query_params={"q": "1"}, + ), + ) + current_trace.reset(token) + token = current_trace.set(TRACE_B) + try: + with pytest.raises(AuthenticationError): + list(stream) + finally: + current_trace.reset(token) + client.close() + conn = server.stop() + assert conn.path == "/v1/asr/realtime?q=1" + assert values(conn.header_list, "traceparent") == [TRACE_B] + assert values(conn.header_list, "x-call") == ["2"] + assert values(conn.header_list, "model") == ["transcribe-stream-1"] + assert values(conn.header_list, "user-agent") == [USER_AGENT] + + async def test_asr_realtime_handshake_async_reads_the_iterating_task(self): + with refusing_ws_server() as server: + client = AsyncFishAudio( + api_key="test-key", + base_url=server.url, + header_provider=lambda: { + "traceparent": current_trace.get(), + "Authorization": "Bearer stolen", + "Sec-WebSocket-Version": "8", + }, + ) + + async def audio(): + yield b"\x00\x00" + + stream = client.asr.stream_websocket(audio()) + + async def consume() -> None: + current_trace.set(TRACE_A) + async for _ in stream: + pass + + with pytest.raises(AuthenticationError): + await asyncio.create_task(consume()) + await client.close() + conn = server.stop() + assert values(conn.header_list, "traceparent") == [TRACE_A] + assert values(conn.header_list, "authorization") == ["Bearer test-key"] + + def test_provider_error_on_a_handshake_reaches_the_caller_sync(self): + error = LookupError("no span") + + def provider(): + raise error + + with refusing_ws_server() as server: + client = FishAudio( + api_key="test-key", base_url=server.url, header_provider=provider + ) + with pytest.raises(LookupError) as tts_info: + list(client.tts.stream_websocket(iter(["hi"]))) + with pytest.raises(LookupError) as asr_info: + list(client.asr.stream_websocket(iter([b"\x00\x00"]))) + client.close() + assert tts_info.value is error and asr_info.value is error + assert server.connection is None # nothing was sent + + async def test_provider_error_on_a_handshake_reaches_the_caller_async(self): + error = LookupError("no span") + + def provider(): + raise error + + async def text(): + yield "hi" + + async def audio(): + yield b"\x00\x00" + + with refusing_ws_server() as server: + client = AsyncFishAudio( + api_key="test-key", base_url=server.url, header_provider=provider + ) + with pytest.raises(LookupError) as tts_info: + async for _ in client.tts.stream_websocket(text()): + pass + with pytest.raises(LookupError) as asr_info: + async for _ in client.asr.stream_websocket(audio()): + pass + await client.close() + assert tts_info.value is error and asr_info.value is error + assert server.connection is None + + async def test_concurrent_async_sessions_each_send_their_own_value(self): + servers = [ + RealtimeServer(lambda conn: None, reject_status=401) for _ in range(8) + ] + try: + + async def session(i: int) -> None: + current_trace.set(f"00-{i:032x}-00f067aa0ba902b7-01") + client = AsyncFishAudio( + api_key="test-key", + base_url=servers[i].url, + header_provider=from_contextvar, + ) + + async def audio(): + yield b"\x00\x00" + + with pytest.raises(AuthenticationError): + async for _ in client.asr.stream_websocket(audio()): + pass + await client.close() + + await asyncio.gather(*(session(i) for i in range(8))) + for i, server in enumerate(servers): + conn = server.stop() + assert values(conn.header_list, "traceparent") == [ + f"00-{i:032x}-00f067aa0ba902b7-01" + ] + finally: + for server in servers: + server.close() diff --git a/tests/unit/test_tts_realtime.py b/tests/unit/test_tts_realtime.py index 9e2a425..b4ee996 100644 --- a/tests/unit/test_tts_realtime.py +++ b/tests/unit/test_tts_realtime.py @@ -23,6 +23,9 @@ def mock_client_wrapper(mock_api_key): "User-Agent": "fish-audio-python/test", **(additional or {}), } + wrapper.websocket_kwargs = lambda model, request_options=None: { + "headers": wrapper.get_headers({"model": model}) + } return wrapper @@ -39,6 +42,9 @@ def async_mock_client_wrapper(mock_api_key): "User-Agent": "fish-audio-python/test", **(additional or {}), } + wrapper.websocket_kwargs = lambda model, request_options=None: { + "headers": wrapper.get_headers({"model": model}) + } return wrapper From b9ee3706c83a2ecf1d8ee52f7578ae61a06e9f40 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:36:00 -0800 Subject: [PATCH 2/7] feat: send the current OpenTelemetry span as traceparent by default header_provider now defaults to fishaudio.opentelemetry_headers, which returns the current OpenTelemetry span as a W3C traceparent, so an app that already uses OpenTelemetry has its Fish Audio requests in its traces with no setup. header_provider=None turns it off; a provider of your own replaces it. - No dependency: opentelemetry-api is imported on first use, inside try/except. Without it, without an active span, or with the API installed but no SDK configured, nothing is sent. - traceparent only, from the span context: no baggage (it can carry application data), no tracestate, not the configured propagator (Fish Audio reads W3C traceparent only). - It never fails a request: an error inside OpenTelemetry sends no header. - With opentelemetry-instrumentation-httpx the instrumentation replaces the header with its client span's: one header, one trace (tested on HTTP and both WebSockets, sync and async). opentelemetry-api, -sdk and -instrumentation-httpx are dev dependencies, for the tests only. Re-locking also records the package version 1.6.0, which the lock had left at 1.5.0. Part of FISH-2233. Co-Authored-By: Claude Opus 5.5 --- README.md | 39 +-- pyproject.toml | 3 + src/fishaudio/__init__.py | 2 + src/fishaudio/client.py | 33 ++- src/fishaudio/core/tracing.py | 60 +++++ tests/unit/test_opentelemetry_default.py | 290 +++++++++++++++++++++++ uv.lock | 233 +++++++++++++++++- 7 files changed, 630 insertions(+), 30 deletions(-) create mode 100644 src/fishaudio/core/tracing.py create mode 100644 tests/unit/test_opentelemetry_default.py diff --git a/README.md b/README.md index f36bc2d..15a3ff5 100644 --- a/README.md +++ b/README.md @@ -329,28 +329,33 @@ except FishAudioError as e: Fish Audio continues your distributed trace when a request carries a W3C [`traceparent`](https://www.w3.org/TR/trace-context/) header, on HTTP calls and on -both WebSockets. Pass a `header_provider`: the SDK calls it for every request and -every WebSocket handshake, right before sending, on the thread (`FishAudio`) or in -the task (`AsyncFishAudio`) that makes the call. It takes no arguments, so read your -current span or request inside it, and returns the headers to add, or `None`. +both WebSockets. -**OpenTelemetry.** If `httpx` is instrumented (`opentelemetry-instrumentation-httpx`, -or `opentelemetry-instrument`), every SDK request, both WebSockets included, already -carries `traceparent`: you need nothing here. If it is not: +**OpenTelemetry: on by default.** If your app uses OpenTelemetry, the SDK sends the +current trace ID to Fish Audio in a `traceparent` header so you can find your +requests in Fish Audio's traces. It sends no other trace data (no `baggage`, no +`tracestate`). To turn this off, pass `header_provider=None`: ```python -from opentelemetry.propagate import inject +client = FishAudio(header_provider=None) +``` -def otel_headers(): - carrier = {} - inject(carrier) # the current span's traceparent (and baggage, if configured) - return carrier +It needs no extra package: without `opentelemetry-api`, or without an active span, +nothing is sent. With `httpx` instrumentation (`opentelemetry-instrumentation-httpx`, +or `opentelemetry-instrument`) the instrumentation replaces this header with its own +client span's, so each request still carries one `traceparent` in one trace. -client = FishAudio(header_provider=otel_headers) -``` +**Any other tracing system.** Pass your own `header_provider`. The SDK calls it for +every request and every WebSocket handshake, right before sending, on the thread +(`FishAudio`) or in the task (`AsyncFishAudio`) that makes the call. It takes no +arguments, so read your current span or request inside it, and returns the headers +to add, or `None`. It replaces the OpenTelemetry default; to keep both: -Using both is harmless: the instrumentation replaces the provider's `traceparent` -with its own child span's. +```python +from fishaudio import opentelemetry_headers + +client = FishAudio(header_provider=lambda: {**(opentelemetry_headers() or {}), **my_headers()}) +``` **Your own trace IDs.** The API accepts only a valid `traceparent` (version `00`: 32 hex digits of trace ID, 16 of parent ID, 2 of flags). Convert your IDs; an @@ -380,7 +385,7 @@ def my_trace_headers(): client = FishAudio(header_provider=my_trace_headers) ``` -**No tracing.** Nothing to do. +**No tracing.** Nothing to do, and nothing is sent. For one call, pass headers with `request_options`, on HTTP and WebSocket methods alike. They win over the provider: diff --git a/pyproject.toml b/pyproject.toml index bb44d0c..6ee5a52 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,6 +57,9 @@ asyncio_mode = "auto" [dependency-groups] dev = [ "fish-audio-sdk[utils]", + "opentelemetry-api>=1.41.1", + "opentelemetry-instrumentation-httpx>=0.62b1", + "opentelemetry-sdk>=1.41.1", "poethepoet>=0.32.0", "pydoc-markdown>=4.8.2", "pytest>=8.3.5", diff --git a/src/fishaudio/__init__.py b/src/fishaudio/__init__.py index 000a07e..82e9a97 100644 --- a/src/fishaudio/__init__.py +++ b/src/fishaudio/__init__.py @@ -36,6 +36,7 @@ TTSTimestampStream, ) from .core.request_options import RequestOptions +from .core.tracing import opentelemetry_headers from .core.websocket_options import WebSocketOptions from .exceptions import ( APIError, @@ -95,6 +96,7 @@ "HeaderProvider", "RequestOptions", "WebSocketOptions", + "opentelemetry_headers", # Types "ASRContextItem", "ASRFinalizeEvent", diff --git a/src/fishaudio/client.py b/src/fishaudio/client.py index 53e7782..09b51fd 100644 --- a/src/fishaudio/client.py +++ b/src/fishaudio/client.py @@ -6,6 +6,7 @@ from .core import AsyncClientWrapper, ClientWrapper from .core.client_wrapper import HeaderProvider +from .core.tracing import opentelemetry_headers from .resources import ( AccountClient, ASRClient, @@ -47,7 +48,7 @@ def __init__( base_url: str = "https://api.fish.audio", timeout: float = 240.0, httpx_client: Optional[httpx.Client] = None, - header_provider: Optional[HeaderProvider] = None, + header_provider: Optional[HeaderProvider] = opentelemetry_headers, ): """ Initialize Fish Audio client. @@ -57,11 +58,15 @@ def __init__( base_url: API base URL timeout: Request timeout in seconds httpx_client: Optional custom HTTP client - header_provider: Optional function the SDK calls for every request - and WebSocket handshake, right before it is sent, to add headers - such as the W3C ``traceparent`` of your current request. It takes - no arguments and returns a mapping of header names to values, or - None. It runs on the thread (sync client) or in the task (async + header_provider: Function the SDK calls for every request and + WebSocket handshake, right before it is sent, to add headers such + as the W3C ``traceparent`` of your current request. It takes no + arguments and returns a mapping of header names to values, or + None. The default, ``opentelemetry_headers``, sends the current + OpenTelemetry span as ``traceparent`` when your app uses + OpenTelemetry, so you can find your requests in Fish Audio's + traces; it sends no other trace data. Pass None to turn this + off, or your own function to replace it. It runs on the thread (sync client) or in the task (async client) that makes the call, so it can read ``contextvars`` and the current OpenTelemetry span; keep it fast and free of I/O. Headers the SDK sets (``Authorization``, ``model``, @@ -155,7 +160,7 @@ def __init__( base_url: str = "https://api.fish.audio", timeout: float = 240.0, httpx_client: Optional[httpx.AsyncClient] = None, - header_provider: Optional[HeaderProvider] = None, + header_provider: Optional[HeaderProvider] = opentelemetry_headers, ): """ Initialize async Fish Audio client. @@ -165,11 +170,15 @@ def __init__( base_url: API base URL timeout: Request timeout in seconds httpx_client: Optional custom async HTTP client - header_provider: Optional function the SDK calls for every request - and WebSocket handshake, right before it is sent, to add headers - such as the W3C ``traceparent`` of your current request. It takes - no arguments and returns a mapping of header names to values, or - None. It runs on the thread (sync client) or in the task (async + header_provider: Function the SDK calls for every request and + WebSocket handshake, right before it is sent, to add headers such + as the W3C ``traceparent`` of your current request. It takes no + arguments and returns a mapping of header names to values, or + None. The default, ``opentelemetry_headers``, sends the current + OpenTelemetry span as ``traceparent`` when your app uses + OpenTelemetry, so you can find your requests in Fish Audio's + traces; it sends no other trace data. Pass None to turn this + off, or your own function to replace it. It runs on the thread (sync client) or in the task (async client) that makes the call, so it can read ``contextvars`` and the current OpenTelemetry span; keep it fast and free of I/O. Headers the SDK sets (``Authorization``, ``model``, diff --git a/src/fishaudio/core/tracing.py b/src/fishaudio/core/tracing.py new file mode 100644 index 0000000..88767ac --- /dev/null +++ b/src/fishaudio/core/tracing.py @@ -0,0 +1,60 @@ +"""The default header provider: the current OpenTelemetry span as ``traceparent``.""" + +from __future__ import annotations + +import logging +from typing import Any, Optional + +logger = logging.getLogger(__name__) + +# The OpenTelemetry API's get_current_span, imported on first use: None until +# then, False when the API is not installed (not retried on every request). +_get_current_span: Any = None + + +def _current_span_getter() -> Any: + global _get_current_span + if _get_current_span is None: + try: + from opentelemetry.trace import get_current_span + except ImportError: + _get_current_span = False + else: + _get_current_span = get_current_span + return _get_current_span + + +def opentelemetry_headers() -> Optional[dict[str, str]]: + """The current OpenTelemetry span as a W3C ``traceparent`` header, or None. + + The default ``header_provider`` of ``FishAudio`` and ``AsyncFishAudio``. + It needs no dependency: when the ``opentelemetry-api`` package is not + installed, or no span is active (also when the API is installed but no + OpenTelemetry SDK is configured), it returns None and no header is sent. + + It sends ``traceparent`` only, built from the span's IDs and flags. It + sends no ``baggage``, which can carry application data, and no + ``tracestate``, and it does not use the configured propagator, because + Fish Audio reads the W3C ``traceparent`` only. + + It never fails a request: an error inside OpenTelemetry is logged at + debug level and no header is sent. + + To combine it with headers of your own:: + + FishAudio(header_provider=lambda: {**(opentelemetry_headers() or {}), **mine()}) + """ + get_current_span = _current_span_getter() + if not get_current_span: + return None + try: + context = get_current_span().get_span_context() + if not context.is_valid: + return None + return { + "traceparent": f"00-{context.trace_id:032x}-{context.span_id:016x}" + f"-{int(context.trace_flags):02x}" + } + except Exception: + logger.debug("Could not read the current OpenTelemetry span", exc_info=True) + return None diff --git a/tests/unit/test_opentelemetry_default.py b/tests/unit/test_opentelemetry_default.py new file mode 100644 index 0000000..ef343c7 --- /dev/null +++ b/tests/unit/test_opentelemetry_default.py @@ -0,0 +1,290 @@ +"""The default header provider: the current OpenTelemetry span as traceparent.""" + +from __future__ import annotations + +import subprocess +import sys +import textwrap +from typing import TYPE_CHECKING + +import pytest +from httpx_ws import WebSocketUpgradeError +from opentelemetry import trace +from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, +) +from opentelemetry.sdk.trace.sampling import ALWAYS_OFF + +from fishaudio import AsyncFishAudio, FishAudio, opentelemetry_headers +from fishaudio.core import tracing +from fishaudio.exceptions import AuthenticationError + +from .realtime_server import RealtimeServer +from .test_header_provider import recording_server, values + +if TYPE_CHECKING: + from opentelemetry.trace import Span + + +def traceparent_of(span: Span) -> str: + context = span.get_span_context() + return ( + f"00-{context.trace_id:032x}-{context.span_id:016x}" + f"-{int(context.trace_flags):02x}" + ) + + +@pytest.fixture +def tracer_provider(): + """A local tracer provider: the global one is never set by these tests.""" + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + provider.exporter = exporter # type: ignore[attr-defined] + yield provider + provider.shutdown() + + +@pytest.fixture +def no_opentelemetry(monkeypatch): + """Behave as if the opentelemetry-api package were not installed.""" + monkeypatch.setitem(sys.modules, "opentelemetry.trace", None) # import fails + monkeypatch.setattr(tracing, "_get_current_span", None) + yield + tracing._get_current_span = None + + +def get_credits_headers(client: FishAudio, seen: list) -> list[tuple[str, str]]: + client.account.get_credits() + return seen[-1][1] + + +class TestDefault: + def test_is_the_default_of_both_clients(self): + assert ( + FishAudio(api_key="k")._client_wrapper.header_provider + is opentelemetry_headers + ) + assert ( + AsyncFishAudio(api_key="k")._client_wrapper.header_provider + is opentelemetry_headers + ) + + def test_sends_the_current_span(self, tracer_provider): + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + with tracer_provider.get_tracer("t").start_as_current_span("s") as span: + headers = get_credits_headers(client, seen) + client.close() + assert values(headers, "traceparent") == [traceparent_of(span)] + assert values(headers, "tracestate") == [] + assert values(headers, "baggage") == [] + + def test_unsampled_span_keeps_its_flags(self): + provider = TracerProvider(sampler=ALWAYS_OFF) + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + with provider.get_tracer("t").start_as_current_span("s") as span: + headers = get_credits_headers(client, seen) + client.close() + assert not span.get_span_context().trace_flags.sampled + assert values(headers, "traceparent") == [traceparent_of(span)] + + def test_no_span_or_an_invalid_one_sends_nothing(self): + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + outside = get_credits_headers(client, seen) + with trace.use_span(trace.INVALID_SPAN): + invalid = get_credits_headers(client, seen) + client.close() + assert values(outside, "traceparent") == [] + assert values(invalid, "traceparent") == [] + + def test_api_installed_without_an_sdk_sends_nothing(self): + # A fresh interpreter, so no test's tracer provider can be in place. + with recording_server() as (url, seen): + script = textwrap.dedent( + f""" + from opentelemetry import trace + from fishaudio import FishAudio, opentelemetry_headers + with trace.get_tracer("t").start_as_current_span("s"): + assert opentelemetry_headers() is None + FishAudio(api_key="k", base_url={url!r}).account.get_credits() + """ + ) + subprocess.run([sys.executable, "-c", script], check=True, timeout=60) + assert len(seen) == 1 + assert values(seen[0][1], "traceparent") == [] + + def test_api_absent_sends_nothing(self, no_opentelemetry, tracer_provider): + assert opentelemetry_headers() is None + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + with tracer_provider.get_tracer("t").start_as_current_span("s"): + headers = get_credits_headers(client, seen) + client.close() + assert values(headers, "traceparent") == [] + + def test_an_opentelemetry_error_never_fails_the_request(self, monkeypatch): + def broken(): + raise RuntimeError("broken tracer") + + monkeypatch.setattr(tracing, "_get_current_span", broken) + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + headers = get_credits_headers(client, seen) + client.close() + assert values(headers, "traceparent") == [] + + def test_none_turns_it_off(self, tracer_provider): + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url, header_provider=None) + with tracer_provider.get_tracer("t").start_as_current_span("s"): + headers = get_credits_headers(client, seen) + client.close() + assert values(headers, "traceparent") == [] + + def test_your_own_provider_replaces_it(self, tracer_provider): + own = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", + base_url=url, + header_provider=lambda: {"x-request-id": "r1"}, + ) + client_own_trace = FishAudio( + api_key="test-key", + base_url=url, + header_provider=lambda: {"traceparent": own}, + ) + with tracer_provider.get_tracer("t").start_as_current_span("s"): + replaced = get_credits_headers(client, seen) + own_trace = get_credits_headers(client_own_trace, seen) + client.close() + client_own_trace.close() + assert values(replaced, "traceparent") == [] + assert values(replaced, "x-request-id") == ["r1"] + assert values(own_trace, "traceparent") == [own] + + def test_combined_with_your_own_headers(self, tracer_provider): + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", + base_url=url, + header_provider=lambda: { + **(opentelemetry_headers() or {}), + "x-request-id": "r1", + }, + ) + with tracer_provider.get_tracer("t").start_as_current_span("s") as span: + headers = get_credits_headers(client, seen) + client.close() + assert values(headers, "traceparent") == [traceparent_of(span)] + assert values(headers, "x-request-id") == ["r1"] + + +@pytest.fixture +def instrumented(tracer_provider): + """opentelemetry-instrumentation-httpx, on for one test.""" + instrumentor = HTTPXClientInstrumentor() + instrumentor.instrument(tracer_provider=tracer_provider) + yield tracer_provider + instrumentor.uninstrument() + + +class TestWithHttpxInstrumentation: + """The instrumentation replaces the default's header with its client span's: + one header, and that span is a child of the caller's span in the same trace.""" + + @staticmethod + def assert_one_correct_trace(headers, outer: Span, exporter) -> None: + (sent,) = values(headers, "traceparent") + _, trace_id, span_id, _ = sent.split("-") + outer_context = outer.get_span_context() + assert trace_id == f"{outer_context.trace_id:032x}" + assert span_id != f"{outer_context.span_id:016x}" # not the caller's span + client_spans = { + f"{s.context.span_id:016x}": s for s in exporter.get_finished_spans() + } + assert span_id in client_spans # the instrumentation's span ... + parent = client_spans[span_id].parent + assert ( + parent is not None and parent.span_id == outer_context.span_id + ) # ... a child + + def test_http_sync(self, instrumented): + tracer = instrumented.get_tracer("t") + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + with tracer.start_as_current_span("outer") as outer: + client.tts.convert(text="hi") + client.close() + self.assert_one_correct_trace(seen[0][1], outer, instrumented.exporter) + + async def test_http_async(self, instrumented): + tracer = instrumented.get_tracer("t") + with recording_server() as (url, seen): + client = AsyncFishAudio(api_key="test-key", base_url=url) + with tracer.start_as_current_span("outer") as outer: + await client.asr.transcribe(audio=b"\x00") + await client.close() + self.assert_one_correct_trace(seen[0][1], outer, instrumented.exporter) + + def test_tts_and_realtime_stt_handshakes_sync(self, instrumented): + tracer = instrumented.get_tracer("t") + for open_stream in ( + lambda c: list(c.tts.stream_websocket(iter(["hi"]))), + lambda c: list(c.asr.stream_websocket(iter([b"\x00\x00"]))), + ): + server = RealtimeServer(lambda conn: None, reject_status=401) + try: + client = FishAudio(api_key="test-key", base_url=server.url) + with ( + tracer.start_as_current_span("outer") as outer, + pytest.raises((WebSocketUpgradeError, AuthenticationError)), + ): + open_stream(client) + client.close() + conn = server.stop() + finally: + server.close() + self.assert_one_correct_trace( + conn.header_list, outer, instrumented.exporter + ) + + async def test_tts_and_realtime_stt_handshakes_async(self, instrumented): + tracer = instrumented.get_tracer("t") + + async def text(): + yield "hi" + + async def audio(): + yield b"\x00\x00" + + async def tts(client): + async for _ in client.tts.stream_websocket(text()): + pass + + async def stt(client): + async for _ in client.asr.stream_websocket(audio()): + pass + + for open_stream in (tts, stt): + server = RealtimeServer(lambda conn: None, reject_status=401) + try: + client = AsyncFishAudio(api_key="test-key", base_url=server.url) + with ( + tracer.start_as_current_span("outer") as outer, + pytest.raises((WebSocketUpgradeError, AuthenticationError)), + ): + await open_stream(client) + await client.close() + conn = server.stop() + finally: + server.close() + self.assert_one_correct_trace( + conn.header_list, outer, instrumented.exporter + ) diff --git a/uv.lock b/uv.lock index b4753f0..dfe8b83 100644 --- a/uv.lock +++ b/uv.lock @@ -652,7 +652,7 @@ wheels = [ [[package]] name = "fish-audio-sdk" -version = "1.5.0" +version = "1.6.0" source = { editable = "." } dependencies = [ { name = "httpx" }, @@ -673,6 +673,12 @@ utils = [ [package.dev-dependencies] dev = [ { name = "fish-audio-sdk", extra = ["utils"] }, + { name = "opentelemetry-api", version = "1.41.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" }, + { name = "opentelemetry-api", version = "1.45.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" }, + { name = "opentelemetry-instrumentation-httpx", version = "0.62b1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" }, + { name = "opentelemetry-instrumentation-httpx", version = "0.66b2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" }, + { name = "opentelemetry-sdk", version = "1.41.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" }, + { name = "opentelemetry-sdk", version = "1.45.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" }, { name = "poethepoet", version = "0.37.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" }, { name = "poethepoet", version = "0.41.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" }, { name = "pydoc-markdown" }, @@ -701,6 +707,9 @@ provides-extras = ["utils"] [package.metadata.requires-dev] dev = [ { name = "fish-audio-sdk", extras = ["utils"], editable = "." }, + { name = "opentelemetry-api", specifier = ">=1.41.1" }, + { name = "opentelemetry-instrumentation-httpx", specifier = ">=0.62b1" }, + { name = "opentelemetry-sdk", specifier = ">=1.41.1" }, { name = "poethepoet", specifier = ">=0.32.0" }, { name = "pydoc-markdown", specifier = ">=4.8.2" }, { name = "pytest", specifier = ">=8.3.5" }, @@ -795,6 +804,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d2/23/408243171aa9aaba178d3e2559159c24c1171a641aa83b67bdd3394ead8e/idna-3.15-py3-none-any.whl", hash = "sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8", size = 72340, upload-time = "2026-05-12T22:45:55.733Z" }, ] +[[package]] +name = "importlib-metadata" +version = "8.7.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "zipp" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f3/49/3b30cad09e7771a4982d9975a8cbf64f00d4a1ececb53297f1d9a7be1b10/importlib_metadata-8.7.1.tar.gz", hash = "sha256:49fef1ae6440c182052f407c8d34a68f72efc36db9ca90dc0113398f2fdde8bb", size = 57107, upload-time = "2025-12-21T10:00:19.278Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/5e/f8e9a1d23b9c20a551a8a02ea3637b4642e22c2626e3a13a9a29cdea99eb/importlib_metadata-8.7.1-py3-none-any.whl", hash = "sha256:5a1f80bf1daa489495071efbb095d75a634cf28a8bc299581244063b53176151", size = 27865, upload-time = "2025-12-21T10:00:18.329Z" }, +] + [[package]] name = "iniconfig" version = "2.1.0" @@ -1172,6 +1193,207 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/95/8e/2844c3959ce9a63acc7c8e50881133d86666f0420bcde695e115ced0920f/numpy-2.3.4-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:81b3a59793523e552c4a96109dde028aa4448ae06ccac5a76ff6532a85558a7f", size = 12973130, upload-time = "2025-10-15T16:18:09.397Z" }, ] +[[package]] +name = "opentelemetry-api" +version = "1.41.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +dependencies = [ + { name = "importlib-metadata" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/fa/fc/b7564cbef36601aef0d6c9bc01f7badb64be8e862c2e1c3c5c3b43b53e4f/opentelemetry_api-1.41.1.tar.gz", hash = "sha256:0ad1814d73b875f84494387dae86ce0b12c68556331ce6ce8fe789197c949621", size = 71416, upload-time = "2026-04-24T13:15:38.262Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/29/59/3e7118ed140f76b0982ba4321bdaed1997a0473f9720de2d10788a577033/opentelemetry_api-1.41.1-py3-none-any.whl", hash = "sha256:a22df900e75c76dc08440710e51f52f1aa6b451b429298896023e60db5b3139f", size = 69007, upload-time = "2026-04-24T13:15:15.662Z" }, +] + +[[package]] +name = "opentelemetry-api" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation" +version = "0.62b1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.41.1", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.62b1", source = { registry = "https://pypi.org/simple" } }, + { name = "packaging" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/52/cb/0523b92c112a6cc70be43724343dc45225d3af134419844d7879a07755d4/opentelemetry_instrumentation-0.62b1.tar.gz", hash = "sha256:90e92a905ba4f84db06ac3aec96701df6c079b2d66e9379f8739f0a1bdcc7f45", size = 34043, upload-time = "2026-04-24T13:22:31.997Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4d/0f/45adbaea1f81b847cffdcee4f4b5f89297e42facf7fac78c7aaac4c38e75/opentelemetry_instrumentation-0.62b1-py3-none-any.whl", hash = "sha256:976fc6e640f2006599e97429c949e622c108d0c17c2059347d1e6c93c707f257", size = 34163, upload-time = "2026-04-24T13:21:31.722Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.45.2", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.66b2", source = { registry = "https://pypi.org/simple" } }, + { name = "packaging" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation-httpx" +version = "0.62b1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.41.1", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-instrumentation", version = "0.62b1", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.62b1", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-util-http", version = "0.62b1", source = { registry = "https://pypi.org/simple" } }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/33/cb/7a418e69c7dad281803529cb4f6de1b747d802cca44c38032668690b4836/opentelemetry_instrumentation_httpx-0.62b1.tar.gz", hash = "sha256:a1fac9bcc3a6ef5996a7990563f1af0798468b2c146de535fd598369383fba7e", size = 24181, upload-time = "2026-04-24T13:22:52.124Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/e0/eca824e9492ccec00e055bdd243aeda8eb7c5eda746d98af4d7a2d97ecf3/opentelemetry_instrumentation_httpx-0.62b1-py3-none-any.whl", hash = "sha256:88614015df451d61bc7e73f22524e6f223611f80b6caad2f6bdcbe05fa0df653", size = 17201, upload-time = "2026-04-24T13:21:58.072Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation-httpx" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.45.2", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-instrumentation", version = "0.66b2", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.66b2", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-util-http", version = "0.66b2", source = { registry = "https://pypi.org/simple" } }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/41/43/3204ca7e7d91bd9e1b569a98a5f9252c98ae70ba3bb562d2770c34e21d49/opentelemetry_instrumentation_httpx-0.66b2.tar.gz", hash = "sha256:b4c81e4a6dc7b8d7cb2d3088eb8848f6db6bd4abdc443ac9586ec176f1460187", size = 26638, upload-time = "2026-10-29T17:38:31.46Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/53/40/37d6161dcd95285c9c3eb75e2dbeb1dbc6e868551532735374918a22e298/opentelemetry_instrumentation_httpx-0.66b2-py3-none-any.whl", hash = "sha256:93e2b6ab1a505d76ec3d98abcf7e8527d4712167d6c3b5ebbb9c68d9309d9ba5", size = 17723, upload-time = "2026-10-29T17:37:33.735Z" }, +] + +[[package]] +name = "opentelemetry-sdk" +version = "1.41.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.41.1", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.62b1", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/d0/54ee30dab82fb0acda23d144502771ff76ef8728459c83c3e89ef9fb1825/opentelemetry_sdk-1.41.1.tar.gz", hash = "sha256:724b615e1215b5aeacda0abb8a6a8922c9a1853068948bd0bd225a56d0c792e6", size = 230180, upload-time = "2026-04-24T13:15:50.991Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b4/e7/a1420b698aad018e1cf60fdbaaccbe49021fb415e2a0d81c242f4c518f54/opentelemetry_sdk-1.41.1-py3-none-any.whl", hash = "sha256:edee379c126c1bce952b0c812b48fe8ff35b30df0eecf17e98afa4d598b7d85d", size = 180213, upload-time = "2026-04-24T13:15:33.767Z" }, +] + +[[package]] +name = "opentelemetry-sdk" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.45.2", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.66b2", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, +] + +[[package]] +name = "opentelemetry-semantic-conventions" +version = "0.62b1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.41.1", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/de/911ac9e309052aca1b20b2d5549d3db45d1011e1a610e552c6ccdd1b64f8/opentelemetry_semantic_conventions-0.62b1.tar.gz", hash = "sha256:c5cc6e04a7f8c7cdd30be2ed81499fa4e75bfbd52c9cb70d40af1f9cd3619802", size = 145750, upload-time = "2026-04-24T13:15:52.236Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/eb/a6/83dc2ab6fa397ee66fba04fe2e74bdf7be3b3870005359ceb7689103c058/opentelemetry_semantic_conventions-0.62b1-py3-none-any.whl", hash = "sha256:cf506938103d331fbb78eded0d9788095f7fd59016f2bda813c3324e5a74a93c", size = 231620, upload-time = "2026-04-24T13:15:35.454Z" }, +] + +[[package]] +name = "opentelemetry-semantic-conventions" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.45.2", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, +] + +[[package]] +name = "opentelemetry-util-http" +version = "0.62b1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +sdist = { url = "https://files.pythonhosted.org/packages/24/1b/aa71b63e18d30a8384036b9937f40f7618f8030a7aa213155fb54f6f2b47/opentelemetry_util_http-0.62b1.tar.gz", hash = "sha256:adf6facbb89aef8f8bc566e2f04624942ba08a7b678b3479a91051a8f4dc70a3", size = 11393, upload-time = "2026-04-24T13:23:12.994Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/85/a9d9d32161c1ced61346267db4c9702da54f81ec5dc88214bc65c23f4e9d/opentelemetry_util_http-0.62b1-py3-none-any.whl", hash = "sha256:c57e8a6c19fc422c288e6074e882f506f85030b69b7376182f74f9257b9261f0", size = 9295, upload-time = "2026-04-24T13:22:28.078Z" }, +] + +[[package]] +name = "opentelemetry-util-http" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/57/33566966a7bced4d02fbc672f92029184e4a743f5b531e44b4c0dc4c999b/opentelemetry_util_http-0.66b2.tar.gz", hash = "sha256:7ba066ea609202e474679ddf1d0f753a1e6619bd206b36afaecba4bbb86e25d0", size = 11587, upload-time = "2026-10-29T17:38:56.043Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/8d/39885564eefa43f6181acfa3d698af2f6b5fe3e64c86dce3f1b955f6397f/opentelemetry_util_http-0.66b2-py3-none-any.whl", hash = "sha256:c4bb5d6744e60353bcaa3e325bc529a1515346b51cb4d9c8e5b730579337e06d", size = 8383, upload-time = "2026-10-29T17:38:07.462Z" }, +] + [[package]] name = "ormsgpack" version = "1.11.0" @@ -2132,3 +2354,12 @@ sdist = { url = "https://files.pythonhosted.org/packages/23/97/b6f296d1e9cc1ec25 wheels = [ { url = "https://files.pythonhosted.org/packages/37/81/6acd6601f61e31cfb8729d3da6d5df966f80f374b78eff83760714487338/yapf-0.43.0-py3-none-any.whl", hash = "sha256:224faffbc39c428cb095818cf6ef5511fdab6f7430a10783fdfb292ccf2852ca", size = 256158, upload-time = "2024-11-14T00:11:39.37Z" }, ] + +[[package]] +name = "zipp" +version = "3.23.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/30/21/093488dfc7cc8964ded15ab726fad40f25fd3d788fd741cc1c5a17d78ee8/zipp-3.23.1.tar.gz", hash = "sha256:32120e378d32cd9714ad503c1d024619063ec28aad2248dc6672ad13edfa5110", size = 25965, upload-time = "2026-04-13T23:21:46.6Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/08/8a/0861bec20485572fbddf3dfba2910e38fe249796cb73ecdeb74e07eeb8d3/zipp-3.23.1-py3-none-any.whl", hash = "sha256:0b3596c50a5c700c9cb40ba8d86d9f2cc4807e9bedb06bcdf7fac85633e444dc", size = 10378, upload-time = "2026-04-13T23:21:45.386Z" }, +] From 02b4fa374d8623b78641030c8d14902c31d67c57 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:04:50 -0800 Subject: [PATCH 3/7] feat: warn once when the API did not continue the trace the SDK sent Every /v1 response (HTTP, errors included, and the WebSocket handshake) carries x-fish-trace-id, the trace the gateway used. When the SDK put a traceparent on the request (default OpenTelemetry provider, header_provider, per-call headers, or headers on a custom httpx client) and the response names another trace, the SDK issues one fishaudio.TraceNotContinuedWarning per process with both trace IDs, the usual causes and the docs link. - Checked on every HTTP path (plain, streamed, error) and on both WebSocket handshakes, accepted or refused, sync and async. - No traceparent sent, no x-fish-trace-id, or one that is not a trace ID: nothing happens. - A sent value that is not a valid W3C traceparent is reported as such, never echoed. - Once per process: a module flag under a lock, not the per-location filter. - Never fails a request: the check catches its own errors, and a warning that -W error turns into an exception is caught and logged at WARNING instead. - With opentelemetry-instrumentation-httpx the header is replaced by the same trace's client span, so no warning (tested with the real instrumentation). Part of FISH-2233. Co-Authored-By: Claude Fable 5.2 --- README.md | 8 + src/fishaudio/__init__.py | 2 + src/fishaudio/client.py | 10 +- src/fishaudio/core/client_wrapper.py | 15 + src/fishaudio/core/tracing.py | 175 ++++++- src/fishaudio/exceptions.py | 12 + src/fishaudio/resources/asr.py | 43 +- src/fishaudio/resources/tts.py | 29 +- tests/unit/realtime_server.py | 30 +- tests/unit/test_header_provider.py | 25 +- tests/unit/test_trace_continued.py | 661 +++++++++++++++++++++++++++ 11 files changed, 976 insertions(+), 34 deletions(-) create mode 100644 tests/unit/test_trace_continued.py diff --git a/README.md b/README.md index 15a3ff5..d73df4c 100644 --- a/README.md +++ b/README.md @@ -408,6 +408,14 @@ Rules: `AsyncFishAudio` it runs on the event loop. - Streams connect when you start iterating them; the provider runs then. +**If your trace is not continued.** Every response names the trace Fish Audio used +(`x-fish-trace-id`). When the SDK sent a `traceparent` and the API used a different +trace, the SDK issues one `fishaudio.TraceNotContinuedWarning` per process, with both +trace IDs. The usual cause is two `traceparent` headers on one request (an HTTP +auto-instrumentation plus a `header_provider`: keep only one) or a value that is not a +valid W3C `traceparent`. It never fails a request; to silence it, use +`warnings.filterwarnings("ignore", category=fishaudio.TraceNotContinuedWarning)`. + ## Resources - **Documentation:** [SDK Guide](https://docs.fish.audio/developer-guide/sdk-guide/python/) | [API Reference](https://docs.fish.audio/api-reference/sdk/python/) diff --git a/src/fishaudio/__init__.py b/src/fishaudio/__init__.py index 82e9a97..12ca135 100644 --- a/src/fishaudio/__init__.py +++ b/src/fishaudio/__init__.py @@ -48,6 +48,7 @@ PermissionError, RateLimitError, ServerError, + TraceNotContinuedWarning, ValidationError, WebSocketError, ) @@ -117,6 +118,7 @@ "PermissionError", "RateLimitError", "ServerError", + "TraceNotContinuedWarning", "ValidationError", "WebSocketError", # Version diff --git a/src/fishaudio/client.py b/src/fishaudio/client.py index 09b51fd..58d22ea 100644 --- a/src/fishaudio/client.py +++ b/src/fishaudio/client.py @@ -73,7 +73,10 @@ def __init__( ``User-Agent``, ``Content-Type``, WebSocket handshake headers), per-call ``additional_headers`` and headers on ``httpx_client`` win over it. An exception it raises fails the call, unchanged, - before anything is sent. See the README's "Tracing" section. + before anything is sent. If a response shows that Fish Audio + did not continue the ``traceparent`` the SDK sent, the SDK + issues one ``TraceNotContinuedWarning`` per process. See the + README's "Tracing" section. """ self._client_wrapper = ClientWrapper( api_key=api_key, @@ -185,7 +188,10 @@ def __init__( ``User-Agent``, ``Content-Type``, WebSocket handshake headers), per-call ``additional_headers`` and headers on ``httpx_client`` win over it. An exception it raises fails the call, unchanged, - before anything is sent. See the README's "Tracing" section. + before anything is sent. If a response shows that Fish Audio + did not continue the ``traceparent`` the SDK sent, the SDK + issues one ``TraceNotContinuedWarning`` per process. See the + README's "Tracing" section. """ self._client_wrapper = AsyncClientWrapper( api_key=api_key, diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 8efac97..1e379fe 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -21,6 +21,7 @@ ) from .request_options import RequestOptions +from .tracing import check_trace_continued, sent_traceparents def _api_error(status: int, message: str, body: Optional[str] = None) -> APIError: @@ -300,6 +301,14 @@ def _prepare_request_kwargs( params.update(request_options.additional_query_params) kwargs["params"] = params + def traceparents_sent(self, headers: Mapping[str, str]) -> list[str]: + """The ``traceparent`` values a request with ``headers`` carries, as + httpx merges them with the client's headers: what the SDK put there + (the header provider, per-call headers, the httpx client's headers). + Compared with the response by ``check_trace_continued``.""" + client = getattr(self, "_client", None) + return sent_traceparents(headers, getattr(client, "headers", None)) + def websocket_kwargs( self, model: str, request_options: Optional[RequestOptions] ) -> dict[str, Any]: @@ -369,6 +378,7 @@ def request( APIError: On non-2xx responses """ self._prepare_request_kwargs(request_options, kwargs) + sent = self.traceparents_sent(kwargs["headers"]) if stream: timeout = kwargs.pop("timeout", httpx.USE_CLIENT_DEFAULT) @@ -376,6 +386,7 @@ def request( method, path, timeout=timeout, **kwargs ) response = self._client.send(http_request, stream=True) + check_trace_continued(sent, response) if not response.is_success: try: response.read() @@ -386,6 +397,7 @@ def request( # Make the request response = self._client.request(method, path, **kwargs) + check_trace_continued(sent, response) # Handle errors if not response.is_success: @@ -462,6 +474,7 @@ async def request( APIError: On non-2xx responses """ self._prepare_request_kwargs(request_options, kwargs) + sent = self.traceparents_sent(kwargs["headers"]) if stream: timeout = kwargs.pop("timeout", httpx.USE_CLIENT_DEFAULT) @@ -469,6 +482,7 @@ async def request( method, path, timeout=timeout, **kwargs ) response = await self._client.send(http_request, stream=True) + check_trace_continued(sent, response) if not response.is_success: try: await response.aread() @@ -479,6 +493,7 @@ async def request( # Make the request response = await self._client.request(method, path, **kwargs) + check_trace_continued(sent, response) # Handle errors if not response.is_success: diff --git a/src/fishaudio/core/tracing.py b/src/fishaudio/core/tracing.py index 88767ac..5a2dfa0 100644 --- a/src/fishaudio/core/tracing.py +++ b/src/fishaudio/core/tracing.py @@ -1,9 +1,24 @@ -"""The default header provider: the current OpenTelemetry span as ``traceparent``.""" +"""Trace context: the default header provider, and the check that the API +continued the trace the SDK sent.""" from __future__ import annotations +import contextlib import logging -from typing import Any, Optional +import re +import sys +import threading +import warnings +from typing import TYPE_CHECKING, Any, Optional + +from httpx_ws import WebSocketUpgradeError + +from fishaudio.exceptions import TraceNotContinuedWarning + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterator, Sequence + + import httpx logger = logging.getLogger(__name__) @@ -58,3 +73,159 @@ def opentelemetry_headers() -> Optional[dict[str, str]]: except Exception: logger.debug("Could not read the current OpenTelemetry span", exc_info=True) return None + + +# -- Did the API continue the trace the SDK sent? --------------------------- + +TRACE_ID_HEADER = "x-fish-trace-id" +"""The response header that names the trace the API used for a request.""" + +OBSERVABILITY_DOCS = "https://docs.fish.audio/api-reference/observability" + +# W3C Trace Context, section 3.2: version, trace-id, parent-id, trace-flags, +# lowercase hex. Version ff is invalid; a version after 00 may append fields. +_TRACEPARENT = re.compile( + r"(?P[0-9a-f]{2})-(?P[0-9a-f]{32})-(?P[0-9a-f]{16})" + r"-[0-9a-f]{2}(?P-.*)?" +) +_TRACE_ID = re.compile(r"[0-9a-fA-F]{32}") + +# Set once the warning has been issued (or attempted): it is issued at most +# once per process, whichever thread, task or call site sees the mismatch. +_warned = False +_warned_lock = threading.Lock() + + +def traceparent_trace_id(value: str) -> Optional[str]: + """The trace ID of a valid W3C ``traceparent``, or None if it is not one.""" + match = _TRACEPARENT.fullmatch(value.strip(" \t")) + if match is None: + return None + version, trace_id = match.group("version"), match.group("trace_id") + if version == "ff" or (version == "00" and match.group("rest") is not None): + return None + if int(trace_id, 16) == 0 or int(match.group("parent_id"), 16) == 0: + return None + return trace_id + + +def sent_traceparents( + headers: Any, client_headers: Optional[httpx.Headers] = None +) -> list[str]: + """The ``traceparent`` values a request sends, as httpx merges them. + + ``headers`` are the request's own (they win over the client's, name by + name, in any casing); ``client_headers`` those set on the httpx client. + Never raises: anything unreadable gives an empty list. + """ + if _warned: + return [] # Nothing left to check. + try: + import httpx + + merged = httpx.Headers(client_headers) + merged.update(headers) + return merged.get_list("traceparent") + except Exception: + return [] + + +def check_trace_continued(sent: Sequence[str], response: Any) -> None: + """Warn once if ``response`` shows that the API did not continue ``sent``. + + ``sent`` are the ``traceparent`` values the SDK put on the request (from + ``sent_traceparents``); ``response`` is the HTTP response, or the + WebSocket handshake response. Nothing happens when no traceparent was + sent, or when the response has no ``x-fish-trace-id`` (another server, a + proxy that drops it) or one that is not a trace ID. + + It never raises into the caller's call path: a failure inside it is + logged at debug level, and a warning that the caller's filters turn into + an exception (``-W error``) is caught and logged instead. + """ + if _warned or not sent: + return + try: + received = response.headers.get(TRACE_ID_HEADER) + if not isinstance(received, str) or not _TRACE_ID.fullmatch(received.strip()): + return + received = received.strip().lower() + sent_ids = [traceparent_trace_id(value) for value in sent] + if len(sent_ids) == 1 and sent_ids[0] == received: + return + sent_id = next((trace_id for trace_id in sent_ids if trace_id), None) + _warn_once(sent_id, received) + except Exception: + logger.debug("Could not check the trace ID of the response", exc_info=True) + + +def _warn_once(sent_id: Optional[str], received: str) -> None: + global _warned + with _warned_lock: + if _warned: + return + _warned = True + # Only the two trace IDs are included: never a header value as sent. + sent_part = ( + f"sent trace id {sent_id}" + if sent_id is not None + else "the traceparent it sent is not a valid W3C traceparent" + ) + message = ( + f"Fish Audio did not continue the trace this SDK sent ({sent_part}; " + f"the API used {received}). Usual causes: the request carried two " + "traceparent headers (an HTTP auto-instrumentation plus a header " + "provider; use only one), or the value is not a valid W3C traceparent. " + f"See {OBSERVABILITY_DOCS}" + ) + try: + warnings.warn(message, TraceNotContinuedWarning, stacklevel=_stacklevel()) + except Exception: + # The caller's warning filters turned it into an exception: the + # request has succeeded or failed on its own, so log it instead. + logger.warning("%s", message) + + +def _stacklevel() -> int: + """The stack level of the first frame outside the SDK, for warnings.warn, + so the warning names the caller's line. Level 1 is ``_warn_once``.""" + level = 2 + frame = sys._getframe(2) # The caller of _warn_once, at level 2. + while frame is not None: + module = frame.f_globals.get("__name__", "") + if not (module.startswith("fishaudio.") or module == "contextlib"): + break + frame = frame.f_back + level += 1 + return level + + +@contextlib.contextmanager +def checked_websocket(connection: Any, sent: Sequence[str]) -> Iterator[Any]: + """Enter an httpx-ws ``connect_ws`` and check its handshake response. + + A refused handshake (``WebSocketUpgradeError``) is checked too. + """ + with contextlib.ExitStack() as stack: + try: + ws = stack.enter_context(connection) + except WebSocketUpgradeError as exc: + check_trace_continued(sent, getattr(exc, "response", None)) + raise + check_trace_continued(sent, getattr(ws, "response", None)) + yield ws + + +@contextlib.asynccontextmanager +async def achecked_websocket( + connection: Any, sent: Sequence[str] +) -> AsyncIterator[Any]: + """Enter an httpx-ws ``aconnect_ws`` and check its handshake response.""" + async with contextlib.AsyncExitStack() as stack: + try: + ws = await stack.enter_async_context(connection) + except WebSocketUpgradeError as exc: + check_trace_continued(sent, getattr(exc, "response", None)) + raise + check_trace_continued(sent, getattr(ws, "response", None)) + yield ws diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index e8ac4ac..d3e9c80 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -111,3 +111,15 @@ def __init__(self, dependency: str, install_command: str): f"Missing required dependency: {dependency}\n" f"Install it with: {install_command}" ) + + +class TraceNotContinuedWarning(UserWarning): + """Fish Audio did not continue the trace the SDK sent. + + Issued at most once per process, when a request carried a ``traceparent`` + the SDK added (from the default OpenTelemetry provider, your + ``header_provider``, per-call headers or your httpx client's headers) and + the ``x-fish-trace-id`` in the response names a different trace. It never + fails a request, also when warnings are turned into errors. Silence it + with ``warnings.filterwarnings("ignore", category=TraceNotContinuedWarning)``. + """ diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index d64a577..e570792 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -13,6 +13,7 @@ RequestOptions, WebSocketOptions, ) +from fishaudio.core.tracing import achecked_websocket, checked_websocket from fishaudio.types import ( ASRContext, ASRRealtimeConfig, @@ -27,6 +28,34 @@ from .asr_realtime import REALTIME_PATH, ASRRealtimeStream, AsyncASRRealtimeStream +def _connect_ws( + wrapper: ClientWrapper, + model: str, + request_options: Optional[RequestOptions], + ws_kwargs: dict, +): + """Open the realtime STT WebSocket and check its handshake's trace ID.""" + handshake = wrapper.websocket_kwargs(model, request_options) + return checked_websocket( + connect_ws(REALTIME_PATH, client=wrapper.client, **handshake, **ws_kwargs), + wrapper.traceparents_sent(handshake["headers"]), + ) + + +def _aconnect_ws( + wrapper: AsyncClientWrapper, + model: str, + request_options: Optional[RequestOptions], + ws_kwargs: dict, +): + """Open the async realtime STT WebSocket and check its handshake's trace ID.""" + handshake = wrapper.websocket_kwargs(model, request_options) + return achecked_websocket( + aconnect_ws(REALTIME_PATH, client=wrapper.client, **handshake, **ws_kwargs), + wrapper.traceparents_sent(handshake["headers"]), + ) + + def _realtime_config( config: ASRRealtimeConfig, *, @@ -235,12 +264,7 @@ def audio_chunks(): # Headers are built when the session connects (first iteration), so the # header provider sees the caller's context of that moment. return ASRRealtimeStream( - lambda: connect_ws( - REALTIME_PATH, - client=wrapper.client, - **wrapper.websocket_kwargs(model, request_options), - **ws_kwargs, - ), + lambda: _connect_ws(wrapper, model, request_options, ws_kwargs), _realtime_config( config, sample_rate=sample_rate, @@ -430,12 +454,7 @@ async def audio_chunks(): # Headers are built when the session connects (first iteration), so the # header provider sees the caller's context of that moment. return AsyncASRRealtimeStream( - lambda: aconnect_ws( - REALTIME_PATH, - client=wrapper.client, - **wrapper.websocket_kwargs(model, request_options), - **ws_kwargs, - ), + lambda: _aconnect_ws(wrapper, model, request_options, ws_kwargs), _realtime_config( config, sample_rate=sample_rate, diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 15f5e09..e9e03fe 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -25,6 +25,7 @@ AudioStream, TTSTimestampStream, ) +from fishaudio.core.tracing import achecked_websocket, checked_websocket from fishaudio.exceptions import FishAudioError from fishaudio.types import ( AudioFormat, @@ -566,11 +567,15 @@ def text_generator(): ws: WebSocketSession # Built here, when iteration opens the connection, so the header # provider sees the caller's context of that moment. - with connect_ws( - "/v1/tts/live", - client=self._client.client, - **self._client.websocket_kwargs(model, request_options), - **ws_kwargs, + handshake = self._client.websocket_kwargs(model, request_options) + with checked_websocket( + connect_ws( + "/v1/tts/live", + client=self._client.client, + **handshake, + **ws_kwargs, + ), + self._client.traceparents_sent(handshake["headers"]), ) as ws: def sender(): @@ -1034,11 +1039,15 @@ async def text_generator(): ws: AsyncWebSocketSession # Built here, when iteration opens the connection, so the header # provider sees the caller's context of that moment. - async with aconnect_ws( - "/v1/tts/live", - client=self._client.client, - **self._client.websocket_kwargs(model, request_options), - **ws_kwargs, + handshake = self._client.websocket_kwargs(model, request_options) + async with achecked_websocket( + aconnect_ws( + "/v1/tts/live", + client=self._client.client, + **handshake, + **ws_kwargs, + ), + self._client.traceparents_sent(handshake["headers"]), ) as ws: async def sender(): diff --git a/tests/unit/realtime_server.py b/tests/unit/realtime_server.py index 12a0aee..1dd98e0 100644 --- a/tests/unit/realtime_server.py +++ b/tests/unit/realtime_server.py @@ -34,6 +34,10 @@ } +# Builds the handshake response's extra headers from the request's headers. +ResponseHeaders = Callable[[list[tuple[str, str]]], list[tuple[str, str]]] + + class ClientGone(Exception): """The client closed the connection.""" @@ -41,10 +45,16 @@ class ClientGone(Exception): class Connection: """One client connection, as seen by a server script.""" - def __init__(self, sock: socket.socket, reject_status: Optional[int]): + def __init__( + self, + sock: socket.socket, + reject_status: Optional[int], + response_headers: Optional[ResponseHeaders] = None, + ): self._sock = sock self._ws = WSConnection(ConnectionType.SERVER) self._reject_status = reject_status + self._response_headers = response_headers self._pending: deque[dict[str, Any]] = deque() self._partial = b"" self.headers: dict[str, str] = {} @@ -74,10 +84,20 @@ def _read(self) -> None: (k.decode(), v.decode()) for k, v in event.extra_headers ] self.headers = dict(self.header_list) + extra = [ + (k.encode(), v.encode()) + for k, v in ( + self._response_headers(self.header_list) + if self._response_headers is not None + else [] + ) + ] if self._reject_status is not None: - self._write(RejectConnection(status_code=self._reject_status)) + self._write( + RejectConnection(status_code=self._reject_status, headers=extra) + ) raise ClientGone - self._write(AcceptConnection()) + self._write(AcceptConnection(extra_headers=extra)) elif isinstance(event, BytesMessage): self._partial += bytes(event.data) if event.message_finished: @@ -161,9 +181,11 @@ def __init__( script: Callable[[Connection], None], *, reject_status: Optional[int] = None, + response_headers: Optional[ResponseHeaders] = None, ): self._script = script self._reject_status = reject_status + self._response_headers = response_headers self._listener = socket.create_server(("127.0.0.1", 0)) self._listener.settimeout(5) self.url = f"http://127.0.0.1:{self._listener.getsockname()[1]}" @@ -180,7 +202,7 @@ def _serve(self) -> None: self.finished.set() return sock.settimeout(5) - self.connection = Connection(sock, self._reject_status) + self.connection = Connection(sock, self._reject_status, self._response_headers) try: self.connection.handshake() self._script(self.connection) diff --git a/tests/unit/test_header_provider.py b/tests/unit/test_header_provider.py index 5cd3909..039f507 100644 --- a/tests/unit/test_header_provider.py +++ b/tests/unit/test_header_provider.py @@ -12,7 +12,7 @@ import json import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, Callable, Optional import httpx import pytest @@ -64,10 +64,15 @@ def from_contextvar() -> Optional[dict[str, Optional[str]]]: class _Recorder(BaseHTTPRequestHandler): - """Records each request's headers and answers ``status``.""" + """Records each request's headers and answers ``status``. + + ``trace_id``, if set, names the ``x-fish-trace-id`` to answer with, from + the request's headers (None: no such header). + """ seen: list[tuple[str, list[tuple[str, str]]]] status = 200 + trace_id: Optional[Callable[[list[tuple[str, str]]], Optional[str]]] = None def _answer(self) -> None: self.rfile.read(int(self.headers.get("Content-Length") or 0)) @@ -92,6 +97,11 @@ def _answer(self) -> None: self.send_response(self.status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) + trace_id = type(self).trace_id + if trace_id is not None: + value = trace_id(list(self.headers.items())) + if value is not None: + self.send_header("x-fish-trace-id", value) self.end_headers() self.wfile.write(body) @@ -102,8 +112,15 @@ def log_message(self, *args: Any) -> None: @contextlib.contextmanager -def recording_server(status: int = 200) -> Iterator[tuple[str, list]]: - handler = type("Handler", (_Recorder,), {"seen": [], "status": status}) +def recording_server( + status: int = 200, + trace_id: Optional[Callable[[list[tuple[str, str]]], Optional[str]]] = None, +) -> Iterator[tuple[str, list]]: + handler = type( + "Handler", + (_Recorder,), + {"seen": [], "status": status, "trace_id": staticmethod(trace_id)}, + ) # The default listen backlog (5) refuses bursts of concurrent connections. server_class = type("Server", (ThreadingHTTPServer,), {"request_queue_size": 128}) server = server_class(("127.0.0.1", 0), handler) diff --git a/tests/unit/test_trace_continued.py b/tests/unit/test_trace_continued.py new file mode 100644 index 0000000..05b33e3 --- /dev/null +++ b/tests/unit/test_trace_continued.py @@ -0,0 +1,661 @@ +"""The warning when the API did not continue the trace the SDK sent. + +The local servers answer like the Fish Audio gateway: a request with exactly +one valid ``traceparent`` continues its trace, anything else gets a new one, +and the trace ID used comes back in ``x-fish-trace-id``. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import logging +import re +import secrets +import subprocess +import sys +import textwrap +import threading +import warnings +from typing import TYPE_CHECKING, Any, Callable + +import httpx +import pytest +from httpx_ws import WebSocketUpgradeError +from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, +) + +import fishaudio +from fishaudio import AsyncFishAudio, FishAudio, RequestOptions +from fishaudio.core import tracing +from fishaudio.exceptions import AuthenticationError, ServerError + +from .realtime_server import SESSION_STARTED, RealtimeServer +from .test_asr_realtime import SESSION_DONE +from .test_header_provider import TRACE_A, recording_server, values + +if TYPE_CHECKING: + from collections.abc import Iterator + + from .realtime_server import Connection + +TRACE_A_ID = TRACE_A.split("-")[1] +OTHER_ID = "0af7651916cd43dd8448eb211c80319c" +SECRET_VALUE = "not-a-traceparent-s3cr3t" + +_W3C = re.compile(r"00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}") + + +def gateway(headers: list[tuple[str, str]]) -> str: + """The trace ID the gateway uses: the one sent, if exactly one valid + traceparent arrived, else a new one.""" + sent = values(headers, "traceparent") + if len(sent) == 1: + match = _W3C.fullmatch(sent[0]) + if match and int(match.group(1), 16) and int(match.group(2), 16): + return match.group(1) + return secrets.token_hex(16) + + +def ws_gateway(headers: list[tuple[str, str]]) -> list[tuple[str, str]]: + return [("x-fish-trace-id", gateway(headers))] + + +def provide(value: str) -> Callable[[], dict[str, str]]: + return lambda: {"traceparent": value} + + +@pytest.fixture(autouse=True) +def fresh_process_state(monkeypatch): + """Each test starts as a process that has not warned yet.""" + monkeypatch.setattr(tracing, "_warned", False) + + +@contextlib.contextmanager +def recorded() -> Iterator[list[warnings.WarningMessage]]: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + yield caught + + +def trace_warnings(caught: list[warnings.WarningMessage]) -> list[str]: + return [ + str(w.message) + for w in caught + if issubclass(w.category, fishaudio.TraceNotContinuedWarning) + ] + + +class DuplicatingTransport(httpx.BaseTransport): + """Adds a second traceparent, like an instrumentation that appends.""" + + def __init__(self) -> None: + self._inner = httpx.HTTPTransport() + + def handle_request(self, request: httpx.Request) -> httpx.Response: + request.headers = httpx.Headers( + [*request.headers.multi_items(), ("traceparent", TRACE_A)] + ) + return self._inner.handle_request(request) + + def close(self) -> None: + self._inner.close() + + +# Every HTTP path type: plain, streamed, multipart, and each failing. +SYNC_CALLS: dict[str, Callable[[FishAudio], Any]] = { + "json": lambda c: c.account.get_credits(), + "list": lambda c: c.voices.list(), + "multipart": lambda c: c.asr.transcribe(audio=b"\x00\x01"), + "bytes": lambda c: c.tts.convert(text="hi"), + "stream": lambda c: c.tts.stream(text="hi").collect(), +} + + +async def _astream(c: AsyncFishAudio) -> Any: + return await (await c.tts.stream(text="hi")).collect() + + +ASYNC_CALLS: dict[str, Callable[[AsyncFishAudio], Any]] = { + "json": lambda c: c.account.get_credits(), + "list": lambda c: c.voices.list(), + "multipart": lambda c: c.asr.transcribe(audio=b"\x00\x01"), + "bytes": lambda c: c.tts.convert(text="hi"), + "stream": _astream, +} + + +class TestHTTP: + @pytest.mark.parametrize("status", [200, 401, 500]) + @pytest.mark.parametrize("call", list(SYNC_CALLS)) + def test_continued_trace_no_warning(self, call, status): + with recording_server(status, gateway) as (url, seen), recorded() as caught: + client = FishAudio( + api_key="k", base_url=url, header_provider=provide(TRACE_A) + ) + with contextlib.suppress(AuthenticationError, ServerError): + SYNC_CALLS[call](client) + client.close() + assert values(seen[0][1], "traceparent") == [TRACE_A] + assert trace_warnings(caught) == [] + + @pytest.mark.parametrize("status", [200, 401, 500]) + @pytest.mark.parametrize("call", list(SYNC_CALLS)) + def test_not_continued_warns_sync(self, call, status): + with recording_server(status, gateway) as (url, seen), recorded() as caught: + client = FishAudio( + api_key="k", + base_url=url, + header_provider=provide(TRACE_A), + httpx_client=httpx.Client( + base_url=url, transport=DuplicatingTransport() + ), + ) + with contextlib.suppress(AuthenticationError, ServerError): + SYNC_CALLS[call](client) + client.close() + assert values(seen[0][1], "traceparent") == [TRACE_A, TRACE_A] + (message,) = trace_warnings(caught) + assert f"sent trace id {TRACE_A_ID}" in message + assert re.search(r"the API used [0-9a-f]{32}\)", message) + assert "two traceparent headers" in message + assert "https://docs.fish.audio/api-reference/observability" in message + # It names the caller's line, not the SDK's. + (warning,) = [w for w in caught if "Fish Audio" in str(w.message)] + assert warning.filename == __file__ + + @pytest.mark.parametrize("status", [200, 401, 500]) + @pytest.mark.parametrize("call", list(ASYNC_CALLS)) + async def test_async(self, call, status): + with recording_server(status, gateway) as (url, _), recorded() as caught: + matching = AsyncFishAudio( + api_key="k", base_url=url, header_provider=provide(TRACE_A) + ) + with contextlib.suppress(AuthenticationError, ServerError): + await ASYNC_CALLS[call](matching) + await matching.close() + assert trace_warnings(caught) == [] + + # A traceparent on a custom httpx client counts as sent by the SDK. + other_trace = f"00-{'1' * 32}-{'2' * 16}-01" + with ( + recording_server(status, lambda _: OTHER_ID) as (url, _), + recorded() as caught, + ): + other = AsyncFishAudio( + api_key="k", + base_url=url, + header_provider=None, + httpx_client=httpx.AsyncClient( + base_url=url, headers={"traceparent": other_trace} + ), + ) + with contextlib.suppress(AuthenticationError, ServerError): + await ASYNC_CALLS[call](other) + await other.close() + (message,) = trace_warnings(caught) + assert f"sent trace id {'1' * 32}" in message + assert f"the API used {OTHER_ID}" in message + + def test_once_across_many_calls_and_threads(self): + with recording_server(200, gateway) as (url, seen), recorded() as caught: + client = FishAudio( + api_key="k", + base_url=url, + header_provider=provide(TRACE_A), + httpx_client=httpx.Client( + base_url=url, transport=DuplicatingTransport() + ), + ) + barrier = threading.Barrier(16) + + def call() -> None: + barrier.wait() + for _ in range(5): + client.account.get_credits() + client.tts.convert(text="hi") + + threads = [threading.Thread(target=call) for _ in range(16)] + for t in threads: + t.start() + for t in threads: + t.join() + client.close() + assert len(seen) == 160 + assert len(trace_warnings(caught)) == 1 + + async def test_once_across_many_tasks(self): + with recording_server(200, lambda _: OTHER_ID) as (url, seen): + client = AsyncFishAudio( + api_key="k", base_url=url, header_provider=provide(TRACE_A) + ) + with recorded() as caught: + await asyncio.gather( + *(client.account.get_credits() for _ in range(32)), + *(_astream(client) for _ in range(8)), + ) + await client.close() + assert len(seen) == 40 + assert len(trace_warnings(caught)) == 1 + + def test_per_call_header_is_checked(self): + with ( + recording_server(200, lambda _: OTHER_ID) as (url, _), + recorded() as caught, + ): + client = FishAudio(api_key="k", base_url=url, header_provider=None) + client.account.get_credits( + request_options=RequestOptions( + additional_headers={"traceparent": TRACE_A} + ) + ) + client.close() + assert len(trace_warnings(caught)) == 1 + + def test_missing_response_header_no_warning(self): + with recording_server(200, None) as (url, _), recorded() as caught: + client = FishAudio( + api_key="k", base_url=url, header_provider=provide(TRACE_A) + ) + client.account.get_credits() + client.tts.stream(text="hi").collect() + client.close() + assert trace_warnings(caught) == [] + + @pytest.mark.parametrize("received", ["", "abc", "not-a-trace-id-at-all", "x" * 32]) + def test_response_header_that_is_not_a_trace_id_is_ignored(self, received): + with ( + recording_server(200, lambda _: received) as (url, _), + recorded() as caught, + ): + client = FishAudio( + api_key="k", base_url=url, header_provider=provide(TRACE_A) + ) + client.account.get_credits() + client.close() + assert trace_warnings(caught) == [] + + def test_nothing_sent_no_check(self): + with ( + recording_server(200, lambda _: OTHER_ID) as (url, _), + recorded() as caught, + ): + client = FishAudio(api_key="k", base_url=url, header_provider=None) + client.account.get_credits() + client.close() + assert trace_warnings(caught) == [] + assert tracing._warned is False + + def test_case_of_the_response_id_does_not_matter(self): + with ( + recording_server(200, lambda _: TRACE_A_ID.upper()) as (url, _), + recorded() as caught, + ): + client = FishAudio( + api_key="k", base_url=url, header_provider=provide(TRACE_A) + ) + client.account.get_credits() + client.close() + assert trace_warnings(caught) == [] + + @pytest.mark.parametrize( + "sent", + [ + SECRET_VALUE, + TRACE_A.upper(), # W3C requires lowercase + f"00-{'0' * 32}-00f067aa0ba902b7-01", # all-zero trace ID + f"00-{TRACE_A_ID}-{'0' * 16}-01", # all-zero parent ID + f"ff-{TRACE_A_ID}-00f067aa0ba902b7-01", # version ff + f"{TRACE_A}-extra", # version 00 has exactly four fields + ], + ) + def test_invalid_sent_value_warns_without_echoing_it(self, sent): + with recording_server(200, gateway) as (url, _), recorded() as caught: + client = FishAudio(api_key="k", base_url=url, header_provider=provide(sent)) + client.account.get_credits() + client.close() + (message,) = trace_warnings(caught) + assert "not a valid W3C traceparent" in message + assert sent not in message + assert SECRET_VALUE not in message + assert "sent trace id" not in message + + def test_future_version_with_more_fields_is_valid(self): + sent = f"01-{TRACE_A_ID}-00f067aa0ba902b7-01-more" + with ( + recording_server(200, lambda _: TRACE_A_ID) as (url, _), + recorded() as caught, + ): + client = FishAudio(api_key="k", base_url=url, header_provider=provide(sent)) + client.account.get_credits() + client.close() + assert trace_warnings(caught) == [] + + +class TestWarningsAsErrors: + @pytest.mark.parametrize("status", [200, 500]) + def test_simplefilter_error_does_not_fail_the_request(self, status, caplog): + with recording_server(status, lambda _: OTHER_ID) as (url, _): + client = FishAudio( + api_key="k", base_url=url, header_provider=provide(TRACE_A) + ) + with warnings.catch_warnings(), caplog.at_level(logging.WARNING): + warnings.simplefilter("error") + if status == 200: + assert client.account.get_credits().credit is not None + else: + # The API's own error, not the warning. + with pytest.raises(ServerError): + client.account.get_credits() + client.close() + # The message is not lost: it is logged instead. + assert [ + r.levelno for r in caplog.records if "Fish Audio did not" in r.message + ] == [logging.WARNING] + + async def test_simplefilter_error_async_and_websocket(self): + server = RealtimeServer( + lambda conn: None, + reject_status=401, + response_headers=lambda _: [("x-fish-trace-id", OTHER_ID)], + ) + try: + client = AsyncFishAudio( + api_key="k", base_url=server.url, header_provider=provide(TRACE_A) + ) + + async def audio(): + yield b"\x00\x00" + + with warnings.catch_warnings(): + warnings.simplefilter("error") + # The handshake's own failure, not the warning. + with pytest.raises((WebSocketUpgradeError, AuthenticationError)): + async for _ in client.asr.stream_websocket(audio()): + pass + await client.close() + finally: + server.close() + assert tracing._warned is True + + def test_python_dash_w_error(self): + with recording_server(200, lambda _: OTHER_ID) as (url, seen): + script = textwrap.dedent( + f""" + from fishaudio import FishAudio + client = FishAudio( + api_key="k", + base_url={url!r}, + header_provider=lambda: {{"traceparent": {TRACE_A!r}}}, + ) + client.account.get_credits() + client.account.get_credits() + print("ok") + """ + ) + result = subprocess.run( + [sys.executable, "-W", "error", "-c", script], + capture_output=True, + text=True, + timeout=60, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "ok" + assert len(seen) == 2 + assert result.stderr.count("Fish Audio did not continue the trace") == 1 + + def test_filterable_by_category(self): + with recording_server(200, lambda _: OTHER_ID) as (url, _): + client = FishAudio( + api_key="k", base_url=url, header_provider=provide(TRACE_A) + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + warnings.filterwarnings( + "ignore", category=fishaudio.TraceNotContinuedWarning + ) + client.account.get_credits() + client.close() + assert caught == [] + + +# -- WebSocket handshakes --------------------------------------------------- + + +def tts_script(conn: Connection) -> None: + while conn.recv().get("event") != "stop": + pass + conn.send({"event": "finish", "reason": "stop"}) + + +def stt_script(conn: Connection) -> None: + conn.recv() + conn.send(SESSION_STARTED) + conn.recv_until("audio_done") + conn.send(SESSION_DONE) + conn.close(1000, "done") + + +def sync_tts(client: FishAudio) -> None: + list(client.tts.stream_websocket(iter(["hi"]))) + + +def sync_stt(client: FishAudio) -> None: + list(client.asr.stream_websocket(iter([b"\x00\x00"]))) + + +async def async_tts(client: AsyncFishAudio) -> None: + async def text(): + yield "hi" + + async for _ in client.tts.stream_websocket(text()): + pass + + +async def async_stt(client: AsyncFishAudio) -> None: + async def audio(): + yield b"\x00\x00" + + async for _ in client.asr.stream_websocket(audio()): + pass + + +SCRIPTS = {"tts": tts_script, "stt": stt_script} +SYNC_WS = {"tts": sync_tts, "stt": sync_stt} +ASYNC_WS = {"tts": async_tts, "stt": async_stt} + + +def ws_server( + kind: str, refused: bool, response_headers: Any = ws_gateway +) -> RealtimeServer: + return RealtimeServer( + (lambda conn: None) if refused else SCRIPTS[kind], + reject_status=401 if refused else None, + response_headers=response_headers, + ) + + +@pytest.mark.parametrize("refused", [False, True], ids=["accepted", "refused"]) +@pytest.mark.parametrize("kind", ["tts", "stt"]) +class TestWebSocket: + def run_sync(self, kind, refused, header_provider, **server_options) -> Connection: + server = ws_server(kind, refused, **server_options) + try: + client = FishAudio( + api_key="k", base_url=server.url, header_provider=header_provider + ) + if refused: + with pytest.raises((WebSocketUpgradeError, AuthenticationError)): + SYNC_WS[kind](client) + else: + SYNC_WS[kind](client) + client.close() + return server.stop() + finally: + server.close() + + async def run_async( + self, kind, refused, header_provider, **server_options + ) -> Connection: + server = ws_server(kind, refused, **server_options) + try: + client = AsyncFishAudio( + api_key="k", base_url=server.url, header_provider=header_provider + ) + if refused: + with pytest.raises((WebSocketUpgradeError, AuthenticationError)): + await ASYNC_WS[kind](client) + else: + await ASYNC_WS[kind](client) + await client.close() + return await asyncio.get_running_loop().run_in_executor(None, server.stop) + finally: + server.close() + + def test_sync_continued(self, kind, refused): + with recorded() as caught: + conn = self.run_sync(kind, refused, provide(TRACE_A)) + assert values(conn.header_list, "traceparent") == [TRACE_A] + assert trace_warnings(caught) == [] + + def test_sync_not_continued(self, kind, refused): + with recorded() as caught: + self.run_sync(kind, refused, provide(SECRET_VALUE)) + (message,) = trace_warnings(caught) + assert "not a valid W3C traceparent" in message + assert SECRET_VALUE not in message + + def test_sync_no_response_header(self, kind, refused): + with recorded() as caught: + self.run_sync(kind, refused, provide(TRACE_A), response_headers=None) + assert trace_warnings(caught) == [] + + async def test_async_continued(self, kind, refused): + with recorded() as caught: + conn = await self.run_async(kind, refused, provide(TRACE_A)) + assert values(conn.header_list, "traceparent") == [TRACE_A] + assert trace_warnings(caught) == [] + + async def test_async_not_continued(self, kind, refused): + with recorded() as caught: + await self.run_async( + kind, + refused, + provide(TRACE_A), + response_headers=lambda _: [("x-fish-trace-id", OTHER_ID)], + ) + (message,) = trace_warnings(caught) + assert f"sent trace id {TRACE_A_ID}" in message + assert f"the API used {OTHER_ID}" in message + + +# -- With opentelemetry-instrumentation-httpx ------------------------------- + + +@pytest.fixture +def instrumented(): + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + instrumentor = HTTPXClientInstrumentor() + instrumentor.instrument(tracer_provider=provider) + yield provider + instrumentor.uninstrument() + provider.shutdown() + + +class TestHTTPXInstrumentation: + """The instrumentation replaces the default provider's traceparent with + its client span's, in the same trace: the API continues it, no warning.""" + + def test_http_sync(self, instrumented): + tracer = instrumented.get_tracer("t") + with recording_server(200, gateway) as (url, seen), recorded() as caught: + client = FishAudio(api_key="k", base_url=url) + with tracer.start_as_current_span("outer") as outer: + for call in SYNC_CALLS.values(): + call(client) + client.close() + trace_id = f"{outer.get_span_context().trace_id:032x}" + for _, headers in seen: + (sent,) = values(headers, "traceparent") + assert sent.split("-")[1] == trace_id + # Replaced by the instrumentation's own span. + assert sent.split("-")[2] != f"{outer.get_span_context().span_id:016x}" + assert trace_warnings(caught) == [] + + async def test_http_async(self, instrumented): + tracer = instrumented.get_tracer("t") + with recording_server(500, gateway) as (url, seen), recorded() as caught: + client = AsyncFishAudio(api_key="k", base_url=url) + with tracer.start_as_current_span("outer"): + for call in ASYNC_CALLS.values(): + with pytest.raises(ServerError): + await call(client) + await client.close() + assert len(seen) == len(ASYNC_CALLS) + assert trace_warnings(caught) == [] + + @pytest.mark.parametrize("kind", ["tts", "stt"]) + def test_handshakes_sync(self, instrumented, kind): + tracer = instrumented.get_tracer("t") + server = ws_server(kind, refused=False) + try: + with recorded() as caught: + client = FishAudio(api_key="k", base_url=server.url) + with tracer.start_as_current_span("outer") as outer: + SYNC_WS[kind](client) + client.close() + conn = server.stop() + finally: + server.close() + (sent,) = values(conn.header_list, "traceparent") + assert sent.split("-")[1] == f"{outer.get_span_context().trace_id:032x}" + assert trace_warnings(caught) == [] + + @pytest.mark.parametrize("kind", ["tts", "stt"]) + async def test_handshakes_async(self, instrumented, kind): + tracer = instrumented.get_tracer("t") + server = ws_server(kind, refused=False) + try: + with recorded() as caught: + client = AsyncFishAudio(api_key="k", base_url=server.url) + with tracer.start_as_current_span("outer"): + await ASYNC_WS[kind](client) + await client.close() + conn = await asyncio.get_running_loop().run_in_executor(None, server.stop) + finally: + server.close() + assert len(values(conn.header_list, "traceparent")) == 1 + assert trace_warnings(caught) == [] + + +def test_exported(): + assert issubclass(fishaudio.TraceNotContinuedWarning, UserWarning) + assert "TraceNotContinuedWarning" in fishaudio.__all__ + + +def test_flag_is_not_a_one_per_location_filter(): + """Two different call sites still give one warning per process.""" + sent = [TRACE_A] + response = httpx.Response(200, headers={"x-fish-trace-id": OTHER_ID}) + with recorded() as caught: + tracing.check_trace_continued(sent, response) + tracing.check_trace_continued(sent, response) + assert len(trace_warnings(caught)) == 1 + + +def test_never_raises_on_odd_inputs(): + tracing.check_trace_continued([TRACE_A], object()) + tracing.check_trace_continued([TRACE_A], None) + assert tracing.sent_traceparents(object()) == [] + assert tracing._warned is False + + +def test_traceparent_trace_id(): + assert tracing.traceparent_trace_id(f" {TRACE_A}\t") == TRACE_A_ID + assert tracing.traceparent_trace_id(TRACE_A.upper()) is None From bfdd2df5703e46418f0a751538492569674eb48f Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:27:34 -0800 Subject: [PATCH 4/7] fix: name the caller's code, not asyncio, in the trace warning on async paths The async realtime handshake is checked inside a task, so the first frame outside the SDK was asyncio's. Skip asyncio frames too, and fall back to this module when no caller frame is on the stack. Co-Authored-By: Claude Fable 5.2 --- src/fishaudio/core/tracing.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/fishaudio/core/tracing.py b/src/fishaudio/core/tracing.py index 5a2dfa0..441f2ad 100644 --- a/src/fishaudio/core/tracing.py +++ b/src/fishaudio/core/tracing.py @@ -187,17 +187,27 @@ def _warn_once(sent_id: Optional[str], received: str) -> None: def _stacklevel() -> int: - """The stack level of the first frame outside the SDK, for warnings.warn, - so the warning names the caller's line. Level 1 is ``_warn_once``.""" + """The stack level for warnings.warn: the first frame outside the SDK, so + the warning names the caller's line. Level 1 is ``_warn_once``. + + The async realtime handshake is checked in a task the SDK starts, where no + caller frame is on the stack; the warning then names this module instead of + a line inside asyncio. + """ level = 2 frame = sys._getframe(2) # The caller of _warn_once, at level 2. while frame is not None: module = frame.f_globals.get("__name__", "") - if not (module.startswith("fishaudio.") or module == "contextlib"): - break + if not ( + module.startswith("fishaudio.") + or module == "contextlib" + or module == "asyncio" + or module.startswith("asyncio.") + ): + return level frame = frame.f_back level += 1 - return level + return 1 @contextlib.contextmanager From 05dd6ed59935151659e73deaa503228e41ef83a7 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:01:34 -0800 Subject: [PATCH 5/7] fix: validate provider header values against RFC 9110 and correct the tracing notes Header provider values now follow one rule: RFC 9110 section 5.5 field values, ASCII only. A value is empty, or visible ASCII (0x21-0x7E) with spaces or tabs only between characters. - Every accepted value is accepted by httpx/h11 and reaches the server unchanged. Every rejected value raises the SDK's own ValueError before anything is sent, naming the header and the kind of problem (non-ASCII, line break, control character, leading or trailing whitespace), never the value. No UnicodeEncodeError or httpx.LocalProtocolError from a provider value reaches the caller any more, and h11 no longer echoes such a value. - Stricter than h11 on purpose for DEL and 0x01-0x1F: invalid per the RFC, and a server or proxy may reject them. - Reserved names and names already set are skipped before their value is checked: an ignored header no longer raises. - Tests: the reviewer's table on HTTP and both WebSocket handshakes, sync and async; every byte 0x00-0xFF at the start, middle and end of a value on HTTP (sync, async) and both handshakes. Tracing notes: - The SDK itself adds only traceparent; an HTTP instrumentation adds what its propagators send (by default tracestate and baggage too), with or without this SDK. - TraceNotContinuedWarning and the README no longer name an auto-instrumentation plus a header provider as a cause: the httpx instrumentation replaces the header. The warning now names the case it sees: more than one traceparent, a value the API does not accept (it continues one lowercase version-00 traceparent only), or a valid value that something after the SDK (a custom transport, an event hook or a proxy) added to or replaced. Part of FISH-2233. Co-Authored-By: Claude Fable 5.2 --- README.md | 21 +- src/fishaudio/client.py | 16 +- src/fishaudio/core/client_wrapper.py | 61 ++++- src/fishaudio/core/tracing.py | 68 +++-- tests/unit/test_header_values.py | 362 +++++++++++++++++++++++++++ tests/unit/test_trace_continued.py | 43 +++- 6 files changed, 528 insertions(+), 43 deletions(-) create mode 100644 tests/unit/test_header_values.py diff --git a/README.md b/README.md index d73df4c..a5bb8f0 100644 --- a/README.md +++ b/README.md @@ -333,8 +333,8 @@ both WebSockets. **OpenTelemetry: on by default.** If your app uses OpenTelemetry, the SDK sends the current trace ID to Fish Audio in a `traceparent` header so you can find your -requests in Fish Audio's traces. It sends no other trace data (no `baggage`, no -`tracestate`). To turn this off, pass `header_provider=None`: +requests in Fish Audio's traces. The SDK itself adds only `traceparent` (no `baggage`, +no `tracestate`). To turn this off, pass `header_provider=None`: ```python client = FishAudio(header_provider=None) @@ -343,7 +343,9 @@ client = FishAudio(header_provider=None) It needs no extra package: without `opentelemetry-api`, or without an active span, nothing is sent. With `httpx` instrumentation (`opentelemetry-instrumentation-httpx`, or `opentelemetry-instrument`) the instrumentation replaces this header with its own -client span's, so each request still carries one `traceparent` in one trace. +client span's, so each request still carries one `traceparent` in one trace. The +instrumentation also adds whatever its propagators are configured to send (by default +`tracestate` and `baggage` too), with or without this SDK. **Any other tracing system.** Pass your own `header_provider`. The SDK calls it for every request and every WebSocket handshake, right before sending, on the thread @@ -403,7 +405,10 @@ Rules: Per-call headers and headers on your own `httpx_client` win over it. - An exception it raises fails the call, unchanged, before anything is sent. A result that is not a mapping of `str` to `str` (or `None` values, which are skipped) raises - `TypeError`; a value with line breaks raises `ValueError`. + `TypeError`. A value must be empty or visible ASCII characters, with spaces or tabs + only between them (RFC 9110); anything else (non-ASCII, control characters, line breaks, + leading or trailing whitespace) raises `ValueError`, which names the header but never + shows the value. Ignored names are skipped before their value is checked. - It runs once per request, synchronously, so keep it fast and free of I/O. With `AsyncFishAudio` it runs on the event loop. - Streams connect when you start iterating them; the provider runs then. @@ -411,9 +416,11 @@ Rules: **If your trace is not continued.** Every response names the trace Fish Audio used (`x-fish-trace-id`). When the SDK sent a `traceparent` and the API used a different trace, the SDK issues one `fishaudio.TraceNotContinuedWarning` per process, with both -trace IDs. The usual cause is two `traceparent` headers on one request (an HTTP -auto-instrumentation plus a `header_provider`: keep only one) or a value that is not a -valid W3C `traceparent`. It never fails a request; to silence it, use +trace IDs and the cause it points to: either the value sent is not one the API accepts +(exactly one lowercase version-`00` `traceparent`; uppercase hex, other versions or +extra fields start a new trace), or the value was valid and something after the SDK (a +custom transport, an event hook or a proxy) added a second `traceparent` or replaced it +with one from another trace. It never fails a request; to silence it, use `warnings.filterwarnings("ignore", category=fishaudio.TraceNotContinuedWarning)`. ## Resources diff --git a/src/fishaudio/client.py b/src/fishaudio/client.py index 58d22ea..baf3147 100644 --- a/src/fishaudio/client.py +++ b/src/fishaudio/client.py @@ -65,7 +65,9 @@ def __init__( None. The default, ``opentelemetry_headers``, sends the current OpenTelemetry span as ``traceparent`` when your app uses OpenTelemetry, so you can find your requests in Fish Audio's - traces; it sends no other trace data. Pass None to turn this + traces; the SDK adds no other trace data (an HTTP + instrumentation, if you use one, adds what its propagators + send). Pass None to turn this off, or your own function to replace it. It runs on the thread (sync client) or in the task (async client) that makes the call, so it can read ``contextvars`` and the current OpenTelemetry span; keep it fast and free of I/O. @@ -73,7 +75,9 @@ def __init__( ``User-Agent``, ``Content-Type``, WebSocket handshake headers), per-call ``additional_headers`` and headers on ``httpx_client`` win over it. An exception it raises fails the call, unchanged, - before anything is sent. If a response shows that Fish Audio + before anything is sent, as does a ``ValueError`` for a value + that is not visible ASCII with spaces or tabs only between + characters (the error never shows the value). If a response shows that Fish Audio did not continue the ``traceparent`` the SDK sent, the SDK issues one ``TraceNotContinuedWarning`` per process. See the README's "Tracing" section. @@ -180,7 +184,9 @@ def __init__( None. The default, ``opentelemetry_headers``, sends the current OpenTelemetry span as ``traceparent`` when your app uses OpenTelemetry, so you can find your requests in Fish Audio's - traces; it sends no other trace data. Pass None to turn this + traces; the SDK adds no other trace data (an HTTP + instrumentation, if you use one, adds what its propagators + send). Pass None to turn this off, or your own function to replace it. It runs on the thread (sync client) or in the task (async client) that makes the call, so it can read ``contextvars`` and the current OpenTelemetry span; keep it fast and free of I/O. @@ -188,7 +194,9 @@ def __init__( ``User-Agent``, ``Content-Type``, WebSocket handshake headers), per-call ``additional_headers`` and headers on ``httpx_client`` win over it. An exception it raises fails the call, unchanged, - before anything is sent. If a response shows that Fish Audio + before anything is sent, as does a ``ValueError`` for a value + that is not visible ASCII with spaces or tabs only between + characters (the error never shows the value). If a response shows that Fish Audio did not continue the ``traceparent`` the SDK sent, the SDK issues one ``TraceNotContinuedWarning`` per process. See the README's "Tracing" section. diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 1e379fe..83681f5 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -163,8 +163,39 @@ def _caller_user_agent( # RFC 9110 token characters, for header names. _HEADER_NAME = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+") -# Control characters other than horizontal tab may not appear in a header value. -_FORBIDDEN_IN_VALUE = re.compile(r"[\x00-\x08\x0a-\x1f\x7f]") + +# A header value the SDK accepts from a header provider: RFC 9110 section 5.5 +# field-value, restricted to ASCII. It is empty, or visible ASCII characters +# (0x21-0x7E) with spaces and tabs only between them, never at either end. +# +# Every value this accepts is also accepted by the transport (httpx encodes +# header values as ASCII; h11 allows the same shape) and reaches the server +# unchanged. It is deliberately stricter than h11 in one respect: h11 also +# sends DEL (0x7F) and the control characters 0x01-0x08, 0x0B, 0x0C and +# 0x0E-0x1F, which RFC 9110 does not allow in a field value and which a server +# or proxy may reject. obs-text (0x80-0xFF) is not allowed either: httpx +# cannot encode it, and RFC 9110 says new values should not use it. +_FIELD_VALUE = re.compile(r"(?:[\x21-\x7e](?:[ \t]*[\x21-\x7e])*)?") +_CONTROL = re.compile(r"[\x00-\x08\x0a-\x1f\x7f]") + + +def _value_problem(value: str) -> Optional[str]: + """What is wrong with a header value, as a kind of problem, or None. + + The result never contains the value or any part of it: a header value + may be a credential. + """ + if _FIELD_VALUE.fullmatch(value): + return None + if not value.isascii(): + return "it contains a non-ASCII character" + if "\r" in value or "\n" in value: + return "it contains a line break" + if _CONTROL.search(value): + return "it contains a control character" + # Only visible ASCII, spaces and tabs are left, so a space or tab is at + # one end (or the value is nothing but spaces and tabs). + return "it has leading or trailing whitespace" def _is_reserved(name: str) -> bool: @@ -178,8 +209,15 @@ def _provided_headers( """Call ``provider`` and return the headers it may add to a request. ``taken`` are the names the request already has (any casing): they win - over the provider, as do the reserved names. An exception raised by the - provider reaches the caller unchanged, before anything is sent. + over the provider, as do the reserved names. Those names are ignored + before their values are looked at, so an invalid value under them does + not raise. An exception raised by the provider reaches the caller + unchanged, before anything is sent. + + Every value kept is accepted by the transport and sent unchanged. A value + that is not (see ``_FIELD_VALUE``) raises ``ValueError`` before anything + is sent; the error names the header and the kind of problem, never the + value, which may be a credential. """ if provider is None: return {} @@ -205,13 +243,18 @@ def _provided_headers( raise ValueError( f"header_provider returned an invalid header name {name!r}" ) - if _FORBIDDEN_IN_VALUE.search(value): - # The value is not echoed: it may be a credential. - raise ValueError( - f"header_provider returned an invalid value for header {name!r}" - ) if _is_reserved(name) or name.lower() in taken_names: continue + problem = _value_problem(value) + if problem is not None: + # Only the name (a validated token) and the kind of problem: the + # value is not echoed, as it may be a credential. + raise ValueError( + f"header_provider returned an invalid value for header {name!r}: " + f"{problem}. A header value must be visible ASCII characters, " + "with spaces or tabs only between them (RFC 9110). " + "The value is not shown." + ) # One spelling per name: a later one replaces an earlier one. for existing in [n for n in headers if n.lower() == name.lower()]: del headers[existing] diff --git a/src/fishaudio/core/tracing.py b/src/fishaudio/core/tracing.py index 441f2ad..b3c9d9a 100644 --- a/src/fishaudio/core/tracing.py +++ b/src/fishaudio/core/tracing.py @@ -47,10 +47,13 @@ def opentelemetry_headers() -> Optional[dict[str, str]]: installed, or no span is active (also when the API is installed but no OpenTelemetry SDK is configured), it returns None and no header is sent. - It sends ``traceparent`` only, built from the span's IDs and flags. It - sends no ``baggage``, which can carry application data, and no - ``tracestate``, and it does not use the configured propagator, because - Fish Audio reads the W3C ``traceparent`` only. + It returns ``traceparent`` only, built from the span's IDs and flags: + no ``baggage``, which can carry application data, and no ``tracestate``. + It does not use the configured propagator, because Fish Audio reads the + W3C ``traceparent`` only. This covers what the SDK adds; an HTTP + instrumentation such as ``opentelemetry-instrumentation-httpx``, if you + use one, adds whatever its propagators are configured to send (by + default also ``tracestate`` and ``baggage``), with or without this SDK. It never fails a request: an error inside OpenTelemetry is logged at debug level and no header is sent. @@ -150,33 +153,60 @@ def check_trace_continued(sent: Sequence[str], response: Any) -> None: if not isinstance(received, str) or not _TRACE_ID.fullmatch(received.strip()): return received = received.strip().lower() - sent_ids = [traceparent_trace_id(value) for value in sent] - if len(sent_ids) == 1 and sent_ids[0] == received: + if len(sent) == 1 and traceparent_trace_id(sent[0]) == received: return - sent_id = next((trace_id for trace_id in sent_ids if trace_id), None) - _warn_once(sent_id, received) + _warn_once(_mismatch_cause(sent), received) except Exception: logger.debug("Could not check the trace ID of the response", exc_info=True) -def _warn_once(sent_id: Optional[str], received: str) -> None: +def _api_trace_id(value: str) -> Optional[str]: + """The trace ID of ``value`` if the API accepts it as a traceparent: a + valid W3C traceparent of version 00, lowercase, with exactly four fields. + Otherwise None.""" + if not value.strip(" \t").startswith("00-"): + return None + return traceparent_trace_id(value) + + +def _mismatch_cause(sent: Sequence[str]) -> tuple[str, str]: + """What the SDK sent, and the cause of the mismatch it points to. + + Only a trace ID or a count is ever included: never a header value as + sent, which may be anything a header provider returned. + """ + if len(sent) > 1: + return ( + f"{len(sent)} traceparent headers", + "The API continues a trace only when a request carries exactly " + "one traceparent.", + ) + sent_id = _api_trace_id(sent[0]) + if sent_id is None: + return ( + "the traceparent it sent is not one the API accepts", + "The API continues only a lowercase version-00 W3C traceparent, " + "00-<32 hex trace id>-<16 hex parent id>-<2 hex flags>; any other " + "value starts a new trace.", + ) + return ( + f"sent trace id {sent_id}", + "The value the SDK sent is valid, so something on the request path " + "after the SDK (a custom httpx transport, an event hook or a proxy) " + "added a second traceparent or replaced it with one from another trace.", + ) + + +def _warn_once(cause: tuple[str, str], received: str) -> None: global _warned with _warned_lock: if _warned: return _warned = True - # Only the two trace IDs are included: never a header value as sent. - sent_part = ( - f"sent trace id {sent_id}" - if sent_id is not None - else "the traceparent it sent is not a valid W3C traceparent" - ) + sent_part, explanation = cause message = ( f"Fish Audio did not continue the trace this SDK sent ({sent_part}; " - f"the API used {received}). Usual causes: the request carried two " - "traceparent headers (an HTTP auto-instrumentation plus a header " - "provider; use only one), or the value is not a valid W3C traceparent. " - f"See {OBSERVABILITY_DOCS}" + f"the API used {received}). {explanation} See {OBSERVABILITY_DOCS}" ) try: warnings.warn(message, TraceNotContinuedWarning, stacklevel=_stacklevel()) diff --git a/tests/unit/test_header_values.py b/tests/unit/test_header_values.py new file mode 100644 index 0000000..e846633 --- /dev/null +++ b/tests/unit/test_header_values.py @@ -0,0 +1,362 @@ +"""Header provider values: what the SDK accepts is what the transport sends. + +The rule is RFC 9110 section 5.5, ASCII only: a value is empty, or visible +ASCII characters (0x21-0x7E) with spaces and tabs only between them. + +- Every value the SDK accepts reaches the server unchanged. +- Every value it rejects raises the SDK's own ``ValueError`` before anything + is sent, naming the header and the kind of problem, never the value: no + ``UnicodeEncodeError`` or ``httpx.LocalProtocolError`` reaches the caller. +- Names the provider may not set, and names already set, are ignored before + their value is looked at. + +Checked against real local servers, on HTTP and on both WebSocket +handshakes, sync and async. +""" + +from __future__ import annotations + +from typing import Any, Callable, Optional + +import pytest +from httpx_ws import WebSocketUpgradeError + +from fishaudio import AsyncFishAudio, FishAudio, RequestOptions +from fishaudio.exceptions import AuthenticationError + +from .test_header_provider import ( + TRACE_A, + TRACE_B, + recording_server, + refusing_ws_server, + values, +) + +Provider = Callable[[], dict[str, str]] +Headers = list[tuple[str, str]] + + +class NothingSent(Exception): + """The call raised before any request reached the server.""" + + def __init__(self, error: BaseException): + super().__init__(repr(error)) + self.error = error + + +# Each sender makes one call with ``provider`` and returns the headers the +# server received, or raises NothingSent with the call's exception. + + +def http_sync(provider: Provider, options: Optional[RequestOptions] = None) -> Headers: + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url, header_provider=provider) + try: + client.tts.convert(text="hi", request_options=options) + except Exception as error: + assert seen == [] + raise NothingSent(error) from error + finally: + client.close() + (request,) = seen + return request[1] + + +async def http_async( + provider: Provider, options: Optional[RequestOptions] = None +) -> Headers: + with recording_server() as (url, seen): + client = AsyncFishAudio( + api_key="test-key", base_url=url, header_provider=provider + ) + try: + await client.account.get_credits(request_options=options) + except Exception as error: + assert seen == [] + raise NothingSent(error) from error + finally: + await client.close() + (request,) = seen + return request[1] + + +def _ws_result(server: Any, error: BaseException) -> Headers: + """The handshake headers, if the server saw the handshake (it refuses + every one after recording it), else NothingSent.""" + if isinstance(error, (WebSocketUpgradeError, AuthenticationError)): + conn = server.stop() + return conn.header_list + server.close() + assert server.connection is None + raise NothingSent(error) from error + + +def ws_sync(kind: str) -> Callable[..., Headers]: + def send(provider: Provider, options: Optional[RequestOptions] = None) -> Headers: + with refusing_ws_server() as server: + client = FishAudio( + api_key="test-key", base_url=server.url, header_provider=provider + ) + try: + if kind == "tts": + list( + client.tts.stream_websocket( + iter(["hi"]), request_options=options + ) + ) + else: + list( + client.asr.stream_websocket( + iter([b"\x00\x00"]), request_options=options + ) + ) + except Exception as error: + return _ws_result(server, error) + finally: + client.close() + raise AssertionError("the server refuses every handshake") + + return send + + +def ws_async(kind: str) -> Callable[..., Any]: + async def send( + provider: Provider, options: Optional[RequestOptions] = None + ) -> Headers: + async def text(): + yield "hi" + + async def audio(): + yield b"\x00\x00" + + with refusing_ws_server() as server: + client = AsyncFishAudio( + api_key="test-key", base_url=server.url, header_provider=provider + ) + try: + if kind == "tts": + async for _ in client.tts.stream_websocket( + text(), request_options=options + ): + pass + else: + async for _ in client.asr.stream_websocket( + audio(), request_options=options + ): + pass + except Exception as error: + return _ws_result(server, error) + finally: + await client.close() + raise AssertionError("the server refuses every handshake") + + return send + + +SENDERS: dict[str, Callable[..., Any]] = { + "http-sync": http_sync, + "http-async": http_async, + "ws-tts-sync": ws_sync("tts"), + "ws-tts-async": ws_async("tts"), + "ws-asr-sync": ws_sync("asr"), + "ws-asr-async": ws_async("asr"), +} + + +async def send(transport: str, provider: Provider, **kwargs: Any) -> Headers: + result = SENDERS[transport](provider, **kwargs) + if transport.endswith("-async"): + result = await result + return result + + +def assert_sdk_error( + error: BaseException, name: str, value: str, kind: str, *, strict: bool = True +) -> None: + """The SDK's own ValueError, naming the header and the kind of problem. + + ``strict``: the message has no character of the value other than those of + the name. A space is allowed: the message is prose, and a value with a + space at one end is one of the rejected kinds. For values made of common + letters (``café``), ``strict=False`` checks that the value is not echoed + and that none of its characters outside visible ASCII is in the message. + """ + assert type(error) is ValueError, repr(error) # not UnicodeEncodeError + message = str(error) + assert repr(name) in message + assert kind in message + if strict: + leaked = set(value) - set(name) - {" "} + else: + assert repr(value) not in message + leaked = {c for c in value if not "!" <= c <= "~"} - {" "} + assert not [c for c in leaked if c in message], (repr(value), message) + + +SENT = "sent" +IGNORED = "ignored" + +# The gateway owner's table, plus the neighbouring cases. +TABLE = [ + ("x-name", "café", "a non-ASCII character"), + ("x-name", " a", "leading or trailing whitespace"), + ("x-name", "a ", "leading or trailing whitespace"), + ("x-name", "\ta", "leading or trailing whitespace"), + ("x-name", " ", "leading or trailing whitespace"), + ("x-name", "a\x7fb", "a control character"), + ("x-name", "a\x01b", "a control character"), + ("x-name", "a\x00b", "a control character"), + ("x-name", "a\r\nb", "a line break"), + ("x-name", "a\nInjected: yes", "a line break"), + ("Authorization", "a\r\nb", IGNORED), + ("Authorization", "café", IGNORED), + ("x-name", "a \t b", SENT), + ("x-name", "", SENT), + ("x-name", "!~", SENT), +] + + +@pytest.mark.parametrize("transport", list(SENDERS)) +@pytest.mark.parametrize("name, value, expected", TABLE) +async def test_reviewer_table(transport, name, value, expected): + provider = lambda: {name: value, "traceparent": TRACE_A} # noqa: E731 + if expected in (SENT, IGNORED): + headers = await send(transport, provider) + assert values(headers, "traceparent") == [TRACE_A] + if expected == SENT: + assert values(headers, name) == [value] + else: + assert values(headers, name) == ["Bearer test-key"] + return + with pytest.raises(NothingSent) as info: + await send(transport, provider) + assert_sdk_error(info.value.error, name, value, expected, strict=False) + assert "Injected" not in str(info.value.error) + + +@pytest.mark.parametrize("transport", list(SENDERS)) +async def test_names_already_set_are_ignored_whatever_their_value(transport): + """A reserved name, or one a per-call header sets, with an illegal value: + no error, and the provider's value is not sent.""" + provider = lambda: { # noqa: E731 + "Authorization": "x\r\nInjected: yes", + "model": "\x00", + "User-Agent": "café", + "Sec-WebSocket-Key": " x ", + "traceparent": "bad\nvalue", + } + headers = await send( + transport, + provider, + options=RequestOptions(additional_headers={"TraceParent": TRACE_B}), + ) + assert values(headers, "traceparent") == [TRACE_B] + assert values(headers, "authorization") == ["Bearer test-key"] + assert values(headers, "injected") == [] + + +# Guarantee A, byte by byte: the SDK is never laxer than the transport. + +PROBE_NAME = "x-probe" +POSITIONS = { + "start": lambda c: f"{c}QZ", + "middle": lambda c: f"Q{c}Z", + "end": lambda c: f"QZ{c}", +} +PROBES = [ + (b, position, build(chr(b))) + for b in range(256) + for position, build in POSITIONS.items() +] + + +def rule_accepts(b: int, position: str) -> bool: + """The rule, stated independently of the SDK's code.""" + if 0x21 <= b <= 0x7E: + return True + return b in (0x20, 0x09) and position == "middle" + + +def _check_probes(results: list[tuple[int, str, str, Any]]) -> None: + for b, position, value, outcome in results: + if isinstance(outcome, NothingSent): + assert not rule_accepts(b, position), (hex(b), position) + assert_sdk_error(outcome.error, PROBE_NAME, value, "it ") + else: + assert rule_accepts(b, position), (hex(b), position) + # Exactly the value, byte for byte, once. + assert values(outcome, PROBE_NAME) == [value], (hex(b), position) + + +def test_every_byte_http_sync(): + results = [] + with recording_server() as (url, seen): + current: dict[str, str] = {} + client = FishAudio( + api_key="test-key", base_url=url, header_provider=lambda: current + ) + for b, position, value in PROBES: + current = {PROBE_NAME: value} + before = len(seen) + try: + client.account.get_credits() + except Exception as error: + assert len(seen) == before, (hex(b), position) # nothing sent + results.append((b, position, value, NothingSent(error))) + else: + assert len(seen) == before + 1 + results.append((b, position, value, seen[-1][1])) + client.close() + _check_probes(results) + + +async def test_every_byte_http_async(): + results = [] + with recording_server() as (url, seen): + current: dict[str, str] = {} + client = AsyncFishAudio( + api_key="test-key", base_url=url, header_provider=lambda: current + ) + for b, position, value in PROBES: + current = {PROBE_NAME: value} + before = len(seen) + try: + await client.account.get_credits() + except Exception as error: + assert len(seen) == before, (hex(b), position) + results.append((b, position, value, NothingSent(error))) + else: + assert len(seen) == before + 1 + results.append((b, position, value, seen[-1][1])) + await client.close() + _check_probes(results) + + +@pytest.mark.parametrize("kind", ["tts", "asr"]) +def test_every_byte_websocket_handshake(kind): + send_ws = ws_sync(kind) + results = [] + for b, position, value in PROBES: + try: + headers = send_ws(lambda: {PROBE_NAME: value}) + except NothingSent as outcome: + results.append((b, position, value, outcome)) + else: + results.append((b, position, value, headers)) + _check_probes(results) + + +def test_default_opentelemetry_provider_output_passes(): + """The default provider's output always satisfies the rule.""" + from opentelemetry.sdk.trace import TracerProvider + + tracer = TracerProvider().get_tracer("t") + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + with tracer.start_as_current_span("s") as span: + client.account.get_credits() + context = span.get_span_context() + client.close() + assert values(seen[0][1], "traceparent") == [ + f"00-{context.trace_id:032x}-{context.span_id:016x}-01" + ] diff --git a/tests/unit/test_trace_continued.py b/tests/unit/test_trace_continued.py index 05b33e3..1b771a1 100644 --- a/tests/unit/test_trace_continued.py +++ b/tests/unit/test_trace_continued.py @@ -91,7 +91,8 @@ def trace_warnings(caught: list[warnings.WarningMessage]) -> list[str]: class DuplicatingTransport(httpx.BaseTransport): - """Adds a second traceparent, like an instrumentation that appends.""" + """Adds a second traceparent after the SDK, like a custom transport, an + event hook or a proxy could.""" def __init__(self) -> None: self._inner = httpx.HTTPTransport() @@ -162,7 +163,9 @@ def test_not_continued_warns_sync(self, call, status): (message,) = trace_warnings(caught) assert f"sent trace id {TRACE_A_ID}" in message assert re.search(r"the API used [0-9a-f]{32}\)", message) - assert "two traceparent headers" in message + assert "The value the SDK sent is valid" in message + assert "added a second traceparent or replaced it" in message + assert "instrumentation" not in message assert "https://docs.fish.audio/api-reference/observability" in message # It names the caller's line, not the SDK's. (warning,) = [w for w in caught if "Fish Audio" in str(w.message)] @@ -319,7 +322,8 @@ def test_invalid_sent_value_warns_without_echoing_it(self, sent): client.account.get_credits() client.close() (message,) = trace_warnings(caught) - assert "not a valid W3C traceparent" in message + assert "the traceparent it sent is not one the API accepts" in message + assert "lowercase version-00 W3C traceparent" in message assert sent not in message assert SECRET_VALUE not in message assert "sent trace id" not in message @@ -335,6 +339,37 @@ def test_future_version_with_more_fields_is_valid(self): client.close() assert trace_warnings(caught) == [] + def test_future_version_not_continued_is_not_one_the_api_accepts(self): + """The API continues version 00 only: a valid later version that gets + a new trace is reported as a value the API does not accept.""" + sent = f"01-{TRACE_A_ID}-00f067aa0ba902b7-01-more" + with recording_server(200, gateway) as (url, _), recorded() as caught: + client = FishAudio(api_key="k", base_url=url, header_provider=provide(sent)) + client.account.get_credits() + client.close() + (message,) = trace_warnings(caught) + assert "the traceparent it sent is not one the API accepts" in message + assert TRACE_A_ID not in message.split("the API used")[0] + + def test_more_than_one_sent_is_counted(self): + other = f"00-{'1' * 32}-{'2' * 16}-01" + with recording_server(200, gateway) as (url, seen), recorded() as caught: + client = FishAudio( + api_key="k", + base_url=url, + header_provider=None, + httpx_client=httpx.Client( + base_url=url, + headers=[("traceparent", TRACE_A), ("traceparent", other)], + ), + ) + client.account.get_credits() + client.close() + assert values(seen[0][1], "traceparent") == [TRACE_A, other] + (message,) = trace_warnings(caught) + assert "(2 traceparent headers;" in message + assert "exactly one traceparent" in message + class TestWarningsAsErrors: @pytest.mark.parametrize("status", [200, 500]) @@ -526,7 +561,7 @@ def test_sync_not_continued(self, kind, refused): with recorded() as caught: self.run_sync(kind, refused, provide(SECRET_VALUE)) (message,) = trace_warnings(caught) - assert "not a valid W3C traceparent" in message + assert "not one the API accepts" in message assert SECRET_VALUE not in message def test_sync_no_response_header(self, kind, refused): From 01c7c0c983fa2f48f5ff63d0a8d8f2f99d165c95 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:32:52 -0800 Subject: [PATCH 6/7] fix: honour OpenTelemetry suppression, run async STT provider in the caller's task, and state trace mismatches as facts - opentelemetry_headers follows the controls the httpx instrumentation honours: suppress_instrumentation() / suppress_http_instrumentation() (also without opentelemetry-instrumentation installed, via the API's context keys), OTEL_PYTHON_HTTPX_EXCLUDED_URLS / OTEL_PYTHON_EXCLUDED_URLS against the full request URL (the SDK exposes it to the provider through a context variable), and the configured propagators (it now injects with them and keeps traceparent only). - AsyncFishAudio.asr.stream_websocket builds the handshake headers in the task that iterates, before the session task takes the connection; its trace warning is issued from that task, so it names the caller's line. - The trace warning now reads "The trace this SDK sent is not the one Fish Audio used" and uses response.request to tell a value changed in this process (for example replaced by opentelemetry-instrumentation-httpx) from one that left unchanged. - Header value problems are three kinds in a fixed order: a control character (CR, LF, NUL, DEL included), a non-ASCII character, leading or trailing whitespace. - README: per-method provider timing, the OpenTelemetry controls, per-call removal, and the warning causes. Co-Authored-By: Claude Fable 5.2 --- README.md | 57 +++- src/fishaudio/client.py | 52 ++-- src/fishaudio/core/client_wrapper.py | 71 +++-- src/fishaudio/core/tracing.py | 318 +++++++++++++++---- src/fishaudio/exceptions.py | 8 +- src/fishaudio/resources/asr.py | 4 +- src/fishaudio/resources/asr_realtime.py | 38 ++- src/fishaudio/resources/tts.py | 8 +- tests/unit/test_header_provider.py | 198 ++++++++++++ tests/unit/test_header_values.py | 10 +- tests/unit/test_opentelemetry_default.py | 379 ++++++++++++++++++++++- tests/unit/test_trace_continued.py | 166 +++++++++- tests/unit/test_tts_realtime.py | 4 +- 13 files changed, 1156 insertions(+), 157 deletions(-) diff --git a/README.md b/README.md index a5bb8f0..db66d3f 100644 --- a/README.md +++ b/README.md @@ -341,7 +341,21 @@ client = FishAudio(header_provider=None) ``` It needs no extra package: without `opentelemetry-api`, or without an active span, -nothing is sent. With `httpx` instrumentation (`opentelemetry-instrumentation-httpx`, +nothing is sent. It follows the OpenTelemetry settings that keep the `httpx` +instrumentation from sending trace context, and sends nothing where they apply: +- inside `suppress_instrumentation()` or `suppress_http_instrumentation()` (from + `opentelemetry.instrumentation.utils`). This is also how to send no `traceparent` + on one call; +- for a URL matched by `OTEL_PYTHON_HTTPX_EXCLUDED_URLS` (or, when that is not set, + `OTEL_PYTHON_EXCLUDED_URLS`): comma-separated regular expressions searched in the + full request URL, such as `https://api.fish.audio/v1/tts` or + `https://api.fish.audio/v1/tts/live` for the TTS WebSocket. The SDK makes the URL + known to it while it calls the header provider, so this also works when your own + provider calls `opentelemetry_headers()`; called anywhere else, it checks no URL; +- when the configured propagators (`OTEL_PROPAGATORS`) write no `traceparent`, for + example `none`, or `b3` alone. + +With `httpx` instrumentation (`opentelemetry-instrumentation-httpx`, or `opentelemetry-instrument`) the instrumentation replaces this header with its own client span's, so each request still carries one `traceparent` in one trace. The instrumentation also adds whatever its propagators are configured to send (by default @@ -349,7 +363,8 @@ instrumentation also adds whatever its propagators are configured to send (by de **Any other tracing system.** Pass your own `header_provider`. The SDK calls it for every request and every WebSocket handshake, right before sending, on the thread -(`FishAudio`) or in the task (`AsyncFishAudio`) that makes the call. It takes no +(`FishAudio`) or in the task (`AsyncFishAudio`) that sends it: the one that makes the +call, or for a WebSocket stream the one that starts iterating it. It takes no arguments, so read your current span or request inside it, and returns the headers to add, or `None`. It replaces the OpenTelemetry default; to keep both: @@ -390,7 +405,9 @@ client = FishAudio(header_provider=my_trace_headers) **No tracing.** Nothing to do, and nothing is sent. For one call, pass headers with `request_options`, on HTTP and WebSocket methods alike. -They win over the provider: +They win over the provider (an empty value is sent empty; there is no per-call way to +remove a header, so to send no `traceparent` from the OpenTelemetry default on one +call, make the call inside `suppress_http_instrumentation()`): ```python from fishaudio import RequestOptions @@ -406,21 +423,37 @@ Rules: - An exception it raises fails the call, unchanged, before anything is sent. A result that is not a mapping of `str` to `str` (or `None` values, which are skipped) raises `TypeError`. A value must be empty or visible ASCII characters, with spaces or tabs - only between them (RFC 9110); anything else (non-ASCII, control characters, line breaks, - leading or trailing whitespace) raises `ValueError`, which names the header but never + only between them (RFC 9110); anything else raises `ValueError`, which names the + header and the first problem that applies (a control character, CR, LF, NUL and DEL + included; then a non-ASCII character; then leading or trailing whitespace) but never shows the value. Ignored names are skipped before their value is checked. - It runs once per request, synchronously, so keep it fast and free of I/O. With `AsyncFishAudio` it runs on the event loop. -- Streams connect when you start iterating them; the provider runs then. +- When it runs, so which span or context it sees: + - `tts.stream()` and `tts.stream_with_timestamps()` send their request before they + return the stream (`AsyncFishAudio`: when you `await` them), so the provider runs + then, not when you iterate. Enter your span before the call. + - `tts.stream_websocket()` and `asr.stream_websocket()` connect when you start + iterating, so the provider runs then, in the thread or task that iterates. + - Every other method sends its request during the call. **If your trace is not continued.** Every response names the trace Fish Audio used (`x-fish-trace-id`). When the SDK sent a `traceparent` and the API used a different -trace, the SDK issues one `fishaudio.TraceNotContinuedWarning` per process, with both -trace IDs and the cause it points to: either the value sent is not one the API accepts -(exactly one lowercase version-`00` `traceparent`; uppercase hex, other versions or -extra fields start a new trace), or the value was valid and something after the SDK (a -custom transport, an event hook or a proxy) added a second `traceparent` or replaced it -with one from another trace. It never fails a request; to silence it, use +trace, the SDK issues one `fishaudio.TraceNotContinuedWarning` per process: "The trace +this SDK sent is not the one Fish Audio used", with both trace IDs and what the SDK +can tell about the cause: +- the value sent is not one the API accepts (exactly one lowercase version-`00` + `traceparent`; uppercase hex, other versions or extra fields start a new trace); +- the value was valid but changed in this process after the SDK set it, as httpx's + record of the request shows. `opentelemetry-instrumentation-httpx` does this when you + send your own `traceparent` while the current OpenTelemetry span is in another trace: + it replaces your value with its own span's. A custom transport or an event hook can + do the same; +- the value was valid and still on the request when httpx handed it to the transport: + it was replaced after that point (a transport that sends a modified copy, a proxy), + or the API did not continue it. + +It never fails a request; to silence it, use `warnings.filterwarnings("ignore", category=fishaudio.TraceNotContinuedWarning)`. ## Resources diff --git a/src/fishaudio/client.py b/src/fishaudio/client.py index baf3147..3d8b99a 100644 --- a/src/fishaudio/client.py +++ b/src/fishaudio/client.py @@ -65,22 +65,28 @@ def __init__( None. The default, ``opentelemetry_headers``, sends the current OpenTelemetry span as ``traceparent`` when your app uses OpenTelemetry, so you can find your requests in Fish Audio's - traces; the SDK adds no other trace data (an HTTP - instrumentation, if you use one, adds what its propagators - send). Pass None to turn this - off, or your own function to replace it. It runs on the thread (sync client) or in the task (async - client) that makes the call, so it can read ``contextvars`` and - the current OpenTelemetry span; keep it fast and free of I/O. + traces, except where OpenTelemetry's own settings keep trace + context off a request (``suppress_instrumentation()``, + ``suppress_http_instrumentation()``, the excluded-URL variables, + propagators that write no ``traceparent``); the SDK adds no + other trace data (an HTTP instrumentation, if you use one, adds + what its propagators send). Pass None to turn this off, or your + own function to replace it. It runs on the thread (sync client) + or in the task (async client) that sends the request: the one + that makes the call, or for a WebSocket stream the one that + starts iterating it. So it can read ``contextvars`` and the + current OpenTelemetry span; keep it fast and free of I/O. Headers the SDK sets (``Authorization``, ``model``, ``User-Agent``, ``Content-Type``, WebSocket handshake headers), per-call ``additional_headers`` and headers on ``httpx_client`` win over it. An exception it raises fails the call, unchanged, before anything is sent, as does a ``ValueError`` for a value that is not visible ASCII with spaces or tabs only between - characters (the error never shows the value). If a response shows that Fish Audio - did not continue the ``traceparent`` the SDK sent, the SDK - issues one ``TraceNotContinuedWarning`` per process. See the - README's "Tracing" section. + characters (the error never shows the value). If a response + shows that Fish Audio used another trace than the + ``traceparent`` the SDK sent, the SDK issues one + ``TraceNotContinuedWarning`` per process. See the README's + "Tracing" section. """ self._client_wrapper = ClientWrapper( api_key=api_key, @@ -184,22 +190,28 @@ def __init__( None. The default, ``opentelemetry_headers``, sends the current OpenTelemetry span as ``traceparent`` when your app uses OpenTelemetry, so you can find your requests in Fish Audio's - traces; the SDK adds no other trace data (an HTTP - instrumentation, if you use one, adds what its propagators - send). Pass None to turn this - off, or your own function to replace it. It runs on the thread (sync client) or in the task (async - client) that makes the call, so it can read ``contextvars`` and - the current OpenTelemetry span; keep it fast and free of I/O. + traces, except where OpenTelemetry's own settings keep trace + context off a request (``suppress_instrumentation()``, + ``suppress_http_instrumentation()``, the excluded-URL variables, + propagators that write no ``traceparent``); the SDK adds no + other trace data (an HTTP instrumentation, if you use one, adds + what its propagators send). Pass None to turn this off, or your + own function to replace it. It runs on the thread (sync client) + or in the task (async client) that sends the request: the one + that makes the call, or for a WebSocket stream the one that + starts iterating it. So it can read ``contextvars`` and the + current OpenTelemetry span; keep it fast and free of I/O. Headers the SDK sets (``Authorization``, ``model``, ``User-Agent``, ``Content-Type``, WebSocket handshake headers), per-call ``additional_headers`` and headers on ``httpx_client`` win over it. An exception it raises fails the call, unchanged, before anything is sent, as does a ``ValueError`` for a value that is not visible ASCII with spaces or tabs only between - characters (the error never shows the value). If a response shows that Fish Audio - did not continue the ``traceparent`` the SDK sent, the SDK - issues one ``TraceNotContinuedWarning`` per process. See the - README's "Tracing" section. + characters (the error never shows the value). If a response + shows that Fish Audio used another trace than the + ``traceparent`` the SDK sent, the SDK issues one + ``TraceNotContinuedWarning`` per process. See the README's + "Tracing" section. """ self._client_wrapper = AsyncClientWrapper( api_key=api_key, diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 83681f5..06c1aab 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -21,7 +21,7 @@ ) from .request_options import RequestOptions -from .tracing import check_trace_continued, sent_traceparents +from .tracing import check_trace_continued, request_url, sent_traceparents def _api_error(status: int, message: str, body: Optional[str] = None) -> APIError: @@ -182,17 +182,18 @@ def _caller_user_agent( def _value_problem(value: str) -> Optional[str]: """What is wrong with a header value, as a kind of problem, or None. - The result never contains the value or any part of it: a header value - may be a credential. + Three kinds, and for a value with several, the first that applies: a + control character (CR, LF, NUL and DEL included), then a non-ASCII + character, then leading or trailing whitespace. Every Fish Audio SDK + names them the same way. The result never contains the value or any part + of it: a header value may be a credential. """ if _FIELD_VALUE.fullmatch(value): return None - if not value.isascii(): - return "it contains a non-ASCII character" - if "\r" in value or "\n" in value: - return "it contains a line break" if _CONTROL.search(value): return "it contains a control character" + if not value.isascii(): + return "it contains a non-ASCII character" # Only visible ASCII, spaces and tabs are left, so a space or tab is at # one end (or the value is nothing but spaces and tabs). return "it has leading or trailing whitespace" @@ -304,9 +305,20 @@ def get_headers( return headers def _prepare_request_kwargs( - self, request_options: Optional[RequestOptions], kwargs: dict[str, Any] + self, + request_options: Optional[RequestOptions], + kwargs: dict[str, Any], + method: str = "GET", + path: Optional[str] = None, ) -> None: """Prepare request kwargs by merging headers, timeout, and query params.""" + # Add query params override if provided + if request_options and request_options.additional_query_params: + params = kwargs.get("params", {}) + if isinstance(params, dict): + params.update(request_options.additional_query_params) + kwargs["params"] = params + # Merge headers headers = self.get_headers( request_options.additional_headers if request_options else None @@ -325,24 +337,36 @@ def _prepare_request_kwargs( # httpx client, win over it. (A retry loop added here later must call # this once per attempt.) client = getattr(self, "_client", None) - merged.update( - _provided_headers( - self.header_provider, - [*merged, *(client.headers.keys() if client is not None else [])], + if self.header_provider is not None: + token = request_url.set( + self._request_url(method, path, kwargs.get("params")) ) - ) + try: + provided = _provided_headers( + self.header_provider, + [*merged, *(client.headers.keys() if client is not None else [])], + ) + finally: + request_url.reset(token) + merged.update(provided) kwargs["headers"] = merged # Apply timeout override if provided if request_options and request_options.timeout is not None: kwargs["timeout"] = httpx.Timeout(request_options.timeout) - # Add query params override if provided - if request_options and request_options.additional_query_params: - params = kwargs.get("params", {}) - if isinstance(params, dict): - params.update(request_options.additional_query_params) - kwargs["params"] = params + def _request_url( + self, method: str, path: Optional[str], params: Any + ) -> Optional[str]: + """The full URL httpx will send a request to, as an HTTP client + instrumentation sees it; None if it cannot be worked out.""" + client = getattr(self, "_client", None) + if client is None or path is None: + return None + try: + return str(client.build_request(method, path, params=params).url) + except Exception: + return None def traceparents_sent(self, headers: Mapping[str, str]) -> list[str]: """The ``traceparent`` values a request with ``headers`` carries, as @@ -353,7 +377,7 @@ def traceparents_sent(self, headers: Mapping[str, str]) -> list[str]: return sent_traceparents(headers, getattr(client, "headers", None)) def websocket_kwargs( - self, model: str, request_options: Optional[RequestOptions] + self, path: str, model: str, request_options: Optional[RequestOptions] ) -> dict[str, Any]: """Headers and query parameters for a WebSocket handshake. @@ -363,7 +387,8 @@ def websocket_kwargs( set with ``WebSocketOptions``. """ kwargs: dict[str, Any] = {"headers": {"model": model}} - self._prepare_request_kwargs(request_options, kwargs) + # The handshake is an HTTP GET; httpx-ws sends it to this URL. + self._prepare_request_kwargs(request_options, kwargs, "GET", path) kwargs.pop("timeout", None) return kwargs @@ -420,7 +445,7 @@ def request( Raises: APIError: On non-2xx responses """ - self._prepare_request_kwargs(request_options, kwargs) + self._prepare_request_kwargs(request_options, kwargs, method, path) sent = self.traceparents_sent(kwargs["headers"]) if stream: @@ -516,7 +541,7 @@ async def request( Raises: APIError: On non-2xx responses """ - self._prepare_request_kwargs(request_options, kwargs) + self._prepare_request_kwargs(request_options, kwargs, method, path) sent = self.traceparents_sent(kwargs["headers"]) if stream: diff --git a/src/fishaudio/core/tracing.py b/src/fishaudio/core/tracing.py index b3c9d9a..c2d6623 100644 --- a/src/fishaudio/core/tracing.py +++ b/src/fishaudio/core/tracing.py @@ -1,15 +1,17 @@ -"""Trace context: the default header provider, and the check that the API -continued the trace the SDK sent.""" +"""Trace context: the default header provider, and the check that the trace +the SDK sent is the one the API used.""" from __future__ import annotations import contextlib +import contextvars import logging +import os import re import sys import threading import warnings -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, Callable, Optional from httpx_ws import WebSocketUpgradeError @@ -22,38 +24,133 @@ logger = logging.getLogger(__name__) -# The OpenTelemetry API's get_current_span, imported on first use: None until -# then, False when the API is not installed (not retried on every request). -_get_current_span: Any = None +class _OpenTelemetry: + """The parts of OpenTelemetry the default provider uses, imported on first + use. Each optional package is looked up once, not on every request.""" -def _current_span_getter() -> Any: - global _get_current_span - if _get_current_span is None: + def __init__(self) -> None: + from opentelemetry import context, propagate + + self.inject: Callable[[dict[str, str]], None] = propagate.inject + self.get_value: Callable[[str], object] = context.get_value + self.is_http_instrumentation_enabled: Optional[Callable[[], bool]] = None + try: + # opentelemetry-instrumentation: the check every OpenTelemetry + # HTTP client instrumentation makes before it injects headers. + from opentelemetry.instrumentation.utils import ( + is_http_instrumentation_enabled, + ) + except ImportError: + pass + else: + self.is_http_instrumentation_enabled = is_http_instrumentation_enabled + # Without that package, the same check on the API's own context keys + # (the SDK's span and metric exporters set the first one). + self.suppress_keys = [ + key + for key in ( + getattr(context, "_SUPPRESS_INSTRUMENTATION_KEY", None), + "suppress_instrumentation", + getattr(context, "_SUPPRESS_HTTP_INSTRUMENTATION_KEY", None), + ) + if key is not None + ] + self.get_excluded_urls: Callable[[str], Any] = _get_excluded_urls try: - from opentelemetry.trace import get_current_span + # opentelemetry-util-http: how instrumentations read + # OTEL_PYTHON__EXCLUDED_URLS and OTEL_PYTHON_EXCLUDED_URLS. + from opentelemetry.util.http import get_excluded_urls except ImportError: - _get_current_span = False + pass else: - _get_current_span = get_current_span - return _get_current_span + self.get_excluded_urls = get_excluded_urls + + def suppressed(self) -> bool: + if self.is_http_instrumentation_enabled is not None: + return not self.is_http_instrumentation_enabled() + return any(self.get_value(key) for key in self.suppress_keys) + + def excluded(self, url: str) -> bool: + return bool(self.get_excluded_urls("HTTPX").url_disabled(url)) + + +class _ExcludeList: + """``opentelemetry.util.http.ExcludeList``, for when that package is absent.""" + + def __init__(self, patterns: list[str]) -> None: + self._regex = re.compile("|".join(patterns)) if patterns else None + + def url_disabled(self, url: str) -> bool: + return self._regex is not None and self._regex.search(url) is not None + + +def _get_excluded_urls(instrumentation: str) -> _ExcludeList: + """``opentelemetry.util.http.get_excluded_urls``, for when that package is + absent: the instrumentation's own variable, else the generic one, as a + comma-separated list of regular expressions searched in the URL.""" + value = os.environ.get( + f"OTEL_PYTHON_{instrumentation}_EXCLUDED_URLS", + os.environ.get("OTEL_PYTHON_EXCLUDED_URLS", ""), + ) + return _ExcludeList([p.strip() for p in value.split(",")] if value else []) + + +# None until first use, False when the opentelemetry-api package is not +# installed (not retried on every request). +_otel: Any = None + + +def _opentelemetry() -> Any: + global _otel + if _otel is None: + try: + _otel = _OpenTelemetry() + except ImportError: + _otel = False + return _otel + + +# The URL of the request whose headers the header provider is building, set by +# the SDK around each call of the provider: the default provider checks it +# against the excluded-URL settings. None outside such a call. +request_url: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar( + "fishaudio_request_url", default=None +) def opentelemetry_headers() -> Optional[dict[str, str]]: - """The current OpenTelemetry span as a W3C ``traceparent`` header, or None. + """The current OpenTelemetry trace context as a W3C ``traceparent`` header, + or None. The default ``header_provider`` of ``FishAudio`` and ``AsyncFishAudio``. It needs no dependency: when the ``opentelemetry-api`` package is not installed, or no span is active (also when the API is installed but no OpenTelemetry SDK is configured), it returns None and no header is sent. - It returns ``traceparent`` only, built from the span's IDs and flags: + It follows the OpenTelemetry settings that keep an HTTP client + instrumentation such as ``opentelemetry-instrumentation-httpx`` from + sending trace context, and returns None where they apply: + + - inside ``suppress_instrumentation()`` or + ``suppress_http_instrumentation()`` (``opentelemetry.instrumentation.utils``), + also without that package installed; + - for a request whose URL matches ``OTEL_PYTHON_HTTPX_EXCLUDED_URLS`` (or, + when that is not set, ``OTEL_PYTHON_EXCLUDED_URLS``): comma-separated + regular expressions, searched in the full URL as the instrumentation + sees it, such as ``https://api.fish.audio/v1/tts``. The SDK makes the + URL known to it while it calls the header provider, so this also works + inside a provider of your own that calls it; called anywhere else, it + does not know the URL and checks no exclusion; + - when the configured propagators (``OTEL_PROPAGATORS``, + ``opentelemetry.propagate.set_global_textmap``) do not write a + ``traceparent``, for example ``none`` or ``b3`` alone. + + It returns ``traceparent`` only, as the configured propagators write it: no ``baggage``, which can carry application data, and no ``tracestate``. - It does not use the configured propagator, because Fish Audio reads the - W3C ``traceparent`` only. This covers what the SDK adds; an HTTP - instrumentation such as ``opentelemetry-instrumentation-httpx``, if you - use one, adds whatever its propagators are configured to send (by - default also ``tracestate`` and ``baggage``), with or without this SDK. + This covers what the SDK adds; an HTTP instrumentation, if you use one, + adds whatever its propagators are configured to send (by default also + ``tracestate`` and ``baggage``), with or without this SDK. It never fails a request: an error inside OpenTelemetry is logged at debug level and no header is sent. @@ -62,19 +159,23 @@ def opentelemetry_headers() -> Optional[dict[str, str]]: FishAudio(header_provider=lambda: {**(opentelemetry_headers() or {}), **mine()}) """ - get_current_span = _current_span_getter() - if not get_current_span: + otel = _opentelemetry() + if not otel: return None try: - context = get_current_span().get_span_context() - if not context.is_valid: + if otel.suppressed(): return None - return { - "traceparent": f"00-{context.trace_id:032x}-{context.span_id:016x}" - f"-{int(context.trace_flags):02x}" - } + url = request_url.get() + if url is not None and otel.excluded(url): + return None + carrier: dict[str, str] = {} + otel.inject(carrier) + values = [v for k, v in carrier.items() if k.lower() == "traceparent"] + if len(values) != 1 or not isinstance(values[0], str): + return None + return {"traceparent": values[0]} except Exception: - logger.debug("Could not read the current OpenTelemetry span", exc_info=True) + logger.debug("Could not read the OpenTelemetry trace context", exc_info=True) return None @@ -134,7 +235,8 @@ def sent_traceparents( def check_trace_continued(sent: Sequence[str], response: Any) -> None: - """Warn once if ``response`` shows that the API did not continue ``sent``. + """Warn once if ``response`` shows that the API used another trace than + the one in ``sent``. ``sent`` are the ``traceparent`` values the SDK put on the request (from ``sent_traceparents``); ``response`` is the HTTP response, or the @@ -142,6 +244,11 @@ def check_trace_continued(sent: Sequence[str], response: Any) -> None: sent, or when the response has no ``x-fish-trace-id`` (another server, a proxy that drops it) or one that is not a trace ID. + The request httpx records on the response (``response.request``) is the + one the transport was handed, with whatever an event hook or an + instrumented transport changed in it; it tells a value changed in this + process from one that left it unchanged. + It never raises into the caller's call path: a failure inside it is logged at debug level, and a warning that the caller's filters turn into an exception (``-W error``) is caught and logged instead. @@ -155,11 +262,22 @@ def check_trace_continued(sent: Sequence[str], response: Any) -> None: received = received.strip().lower() if len(sent) == 1 and traceparent_trace_id(sent[0]) == received: return - _warn_once(_mismatch_cause(sent), received) + _warn_once(_mismatch(sent, _request_traceparents(response), received)) except Exception: logger.debug("Could not check the trace ID of the response", exc_info=True) +def _request_traceparents(response: Any) -> Optional[list[str]]: + """The traceparent values on the request httpx recorded on ``response``, + or None when it has none.""" + try: + headers = response.request.headers + except Exception: # httpx raises RuntimeError when no request is set + return None + values = headers.get_list("traceparent") + return values if all(isinstance(v, str) for v in values) else None + + def _api_trace_id(value: str) -> Optional[str]: """The trace ID of ``value`` if the API accepts it as a traceparent: a valid W3C traceparent of version 00, lowercase, with exactly four fields. @@ -169,45 +287,115 @@ def _api_trace_id(value: str) -> Optional[str]: return traceparent_trace_id(value) -def _mismatch_cause(sent: Sequence[str]) -> tuple[str, str]: - """What the SDK sent, and the cause of the mismatch it points to. +def _describe(values: Sequence[str]) -> str: + """A set of traceparent values, as a trace ID or a count: never a header + value as sent, which may be anything a header provider returned.""" + if not values: + return "no traceparent" + if len(values) > 1: + return f"{len(values)} traceparent headers" + trace_id = _api_trace_id(values[0]) + if trace_id is None: + return "a traceparent the API does not accept" + return f"trace id {trace_id}" + + +_ACCEPTED_FORM = ( + "The API continues a trace only when a request carries exactly one " + "traceparent, and only a lowercase version-00 W3C traceparent, " + "00-<32 hex trace id>-<16 hex parent id>-<2 hex flags>; anything else " + "starts a new trace." +) - Only a trace ID or a count is ever included: never a header value as - sent, which may be anything a header provider returned. - """ - if len(sent) > 1: - return ( - f"{len(sent)} traceparent headers", - "The API continues a trace only when a request carries exactly " - "one traceparent.", + +def _mismatch( + sent: Sequence[str], final: Optional[Sequence[str]], received: str +) -> str: + """The warning's text: what was sent, the trace the API used, and what + the SDK can tell about why they differ.""" + headline = ( + "The trace this SDK sent is not the one Fish Audio used " + f"(sent {_describe(sent)}; the API used {received})." + ) + if len(sent) > 1 or _api_trace_id(sent[0]) is None: + cause = _ACCEPTED_FORM + elif final is None: + cause = ( + "The value the SDK sent is valid, so another traceparent replaced " + "it or was added after the SDK set it, or the API did not continue " + "it. Possible causes: opentelemetry-instrumentation-httpx (it " + "replaces the value with its own span's when the current span is " + "in another trace), a custom httpx transport, an event hook, or a " + "proxy." ) - sent_id = _api_trace_id(sent[0]) - if sent_id is None: - return ( - "the traceparent it sent is not one the API accepts", - "The API continues only a lowercase version-00 W3C traceparent, " - "00-<32 hex trace id>-<16 hex parent id>-<2 hex flags>; any other " - "value starts a new trace.", + elif list(final) != list(sent): + cause = ( + "The value the SDK sent is valid. It was changed in this process " + "after the SDK set it: the request went out with " + f"{_describe(final)}." ) - return ( - f"sent trace id {sent_id}", - "The value the SDK sent is valid, so something on the request path " - "after the SDK (a custom httpx transport, an event hook or a proxy) " - "added a second traceparent or replaced it with one from another trace.", - ) + if len(final) == 1 and _api_trace_id(final[0]) is not None: + cause += ( + " opentelemetry-instrumentation-httpx does this when the " + "current OpenTelemetry span is in another trace: it replaces " + "the value with its own span's, in that trace. A custom httpx " + "transport or an event hook can do the same." + ) + else: + cause += ( + " A custom httpx transport or an event hook can do this. " + + _ACCEPTED_FORM + ) + else: + cause = ( + "The value the SDK sent is valid and was still on the request " + "when httpx handed it to the transport. So it was replaced, or a " + "second traceparent added, after that point (for example by a " + "custom transport that sends a modified copy, or by a proxy), or " + "the API did not continue it." + ) + return f"{headline} {cause} See {OBSERVABILITY_DOCS}" + + +# While set, a mismatch found in this context is queued here instead of being +# issued, for the caller's task to issue (``issue_deferred``): the async +# realtime speech-to-text handshake runs in a task the SDK starts, where no +# caller frame is on the stack for the warning to name. +_deferred: contextvars.ContextVar[Optional[list[str]]] = contextvars.ContextVar( + "fishaudio_deferred_trace_warnings", default=None +) + + +@contextlib.contextmanager +def deferring_warnings(queue: list[str]) -> Iterator[None]: + """Queue the trace warnings of tasks started in this block in ``queue``.""" + token = _deferred.set(queue) + try: + yield + finally: + _deferred.reset(token) -def _warn_once(cause: tuple[str, str], received: str) -> None: +def issue_deferred(queue: list[str]) -> None: + """Issue the warnings queued in ``queue``, naming the caller's code.""" + while queue: + _issue(queue.pop(0)) + + +def _warn_once(message: str) -> None: global _warned with _warned_lock: if _warned: return _warned = True - sent_part, explanation = cause - message = ( - f"Fish Audio did not continue the trace this SDK sent ({sent_part}; " - f"the API used {received}). {explanation} See {OBSERVABILITY_DOCS}" - ) + queue = _deferred.get() + if queue is not None: + queue.append(message) + return + _issue(message) + + +def _issue(message: str) -> None: try: warnings.warn(message, TraceNotContinuedWarning, stacklevel=_stacklevel()) except Exception: @@ -218,14 +406,14 @@ def _warn_once(cause: tuple[str, str], received: str) -> None: def _stacklevel() -> int: """The stack level for warnings.warn: the first frame outside the SDK, so - the warning names the caller's line. Level 1 is ``_warn_once``. + the warning names the caller's line. Level 1 is ``_issue``. - The async realtime handshake is checked in a task the SDK starts, where no - caller frame is on the stack; the warning then names this module instead of - a line inside asyncio. + Should no caller frame be on the stack (a task the SDK starts that does + not defer its warnings), the warning names this module instead of a line + inside asyncio. """ level = 2 - frame = sys._getframe(2) # The caller of _warn_once, at level 2. + frame = sys._getframe(2) # The caller of _issue, at level 2. while frame is not None: module = frame.f_globals.get("__name__", "") if not ( diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index d3e9c80..65e0762 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -114,12 +114,16 @@ def __init__(self, dependency: str, install_command: str): class TraceNotContinuedWarning(UserWarning): - """Fish Audio did not continue the trace the SDK sent. + """The trace Fish Audio used for a request is not the one the SDK sent. Issued at most once per process, when a request carried a ``traceparent`` the SDK added (from the default OpenTelemetry provider, your ``header_provider``, per-call headers or your httpx client's headers) and - the ``x-fish-trace-id`` in the response names a different trace. It never + the ``x-fish-trace-id`` in the response names a different trace. The + message gives both trace IDs and what the SDK can tell about the cause: a + value the API does not accept, a value changed in this process after the + SDK set it (for example by ``opentelemetry-instrumentation-httpx``), or a + value still on the request when httpx handed it to the transport. It never fails a request, also when warnings are turned into errors. Silence it with ``warnings.filterwarnings("ignore", category=TraceNotContinuedWarning)``. """ diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index e570792..bc8c725 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -35,7 +35,7 @@ def _connect_ws( ws_kwargs: dict, ): """Open the realtime STT WebSocket and check its handshake's trace ID.""" - handshake = wrapper.websocket_kwargs(model, request_options) + handshake = wrapper.websocket_kwargs(REALTIME_PATH, model, request_options) return checked_websocket( connect_ws(REALTIME_PATH, client=wrapper.client, **handshake, **ws_kwargs), wrapper.traceparents_sent(handshake["headers"]), @@ -49,7 +49,7 @@ def _aconnect_ws( ws_kwargs: dict, ): """Open the async realtime STT WebSocket and check its handshake's trace ID.""" - handshake = wrapper.websocket_kwargs(model, request_options) + handshake = wrapper.websocket_kwargs(REALTIME_PATH, model, request_options) return achecked_websocket( aconnect_ws(REALTIME_PATH, client=wrapper.client, **handshake, **ws_kwargs), wrapper.traceparents_sent(handshake["headers"]), diff --git a/src/fishaudio/resources/asr_realtime.py b/src/fishaudio/resources/asr_realtime.py index a36413c..afb9de3 100644 --- a/src/fishaudio/resources/asr_realtime.py +++ b/src/fishaudio/resources/asr_realtime.py @@ -23,6 +23,7 @@ from fishaudio.core._ws_utils import drain_reader, interrupt_writes from fishaudio.core.client_wrapper import _api_error +from fishaudio.core.tracing import deferring_warnings, issue_deferred from fishaudio.exceptions import ASRRealtimeError, WebSocketError from fishaudio.types.asr_realtime import ( ASRAgentSpeakingEvent, @@ -485,12 +486,15 @@ def __init__(self, error: Optional[BaseException] = None) -> None: async def _run_session( link: _AsyncLink, events: asyncio.Queue[Union[ASRRealtimeEvent, _End]], - connect: Callable[[], AbstractAsyncContextManager[AsyncWebSocketSession]], + connection: AbstractAsyncContextManager[AsyncWebSocketSession], config: bytes, audio_stream: AsyncIterable[Union[bytes, ASRRealtimeControl]], ) -> None: """Run one session from connect to close, inside a single task. + ``connection`` is created by the consumer's task, so the handshake's + headers (and the header provider) come from the task that iterates. + httpx-ws keeps an anyio task group open for the lifetime of the connection, and a task group must be exited by the task that entered it. An async generator cannot promise that: when the consumer leaves ``async for`` early, @@ -501,7 +505,7 @@ async def _run_session( sender: Optional[asyncio.Task[None]] = None error: Optional[BaseException] = None try: - async with connect() as ws: + async with connection as ws: try: try: await ws.send_bytes(config) @@ -621,6 +625,7 @@ def __init__( self._getter: Optional[asyncio.Future[Union[ASRRealtimeEvent, _End]]] = None self._reading = False self._finished = False + self._trace_warnings: list[str] = [] def __aiter__(self) -> AsyncASRRealtimeStream: return self @@ -629,18 +634,29 @@ async def __anext__(self) -> ASRRealtimeEvent: if self._finished: raise StopAsyncIteration if self._events is None: + # Created here, in the task that iterates, so the handshake headers + # (and the header provider) see this task and its context; an error + # building them is raised here, before anything is sent. + try: + connection = self._connect() + except BaseException: + self._finished = True + raise # The session task must not reference this object: it is cancelled, # and the connection closed, when the stream is garbage collected. self._events = asyncio.Queue(_EVENT_QUEUE_SIZE) - self._task = asyncio.create_task( - _run_session( - self._link, - self._events, - self._connect, - self._config, - self._audio_stream, + # A trace warning from the handshake is issued here, by this task, + # so that it names the caller's code rather than the session task. + with deferring_warnings(self._trace_warnings): + self._task = asyncio.create_task( + _run_session( + self._link, + self._events, + connection, + self._config, + self._audio_stream, + ) ) - ) if self._reading: # Events have one order and one reader. Two reads waiting together # would be handed the same event, so refuse the second, as Python @@ -653,6 +669,7 @@ async def __anext__(self) -> ASRRealtimeEvent: item = await self._next_item() finally: self._reading = False + issue_deferred(self._trace_warnings) if item is None: # closed by aclose() while waiting self._finished = True raise StopAsyncIteration @@ -712,6 +729,7 @@ async def aclose(self) -> None: if self._task is not None: self._task.cancel() await asyncio.wait({self._task}) + issue_deferred(self._trace_warnings) def __del__(self) -> None: if getattr(self, "_getter", None) is not None: diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index e9e03fe..f79171b 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -567,7 +567,9 @@ def text_generator(): ws: WebSocketSession # Built here, when iteration opens the connection, so the header # provider sees the caller's context of that moment. - handshake = self._client.websocket_kwargs(model, request_options) + handshake = self._client.websocket_kwargs( + "/v1/tts/live", model, request_options + ) with checked_websocket( connect_ws( "/v1/tts/live", @@ -1039,7 +1041,9 @@ async def text_generator(): ws: AsyncWebSocketSession # Built here, when iteration opens the connection, so the header # provider sees the caller's context of that moment. - handshake = self._client.websocket_kwargs(model, request_options) + handshake = self._client.websocket_kwargs( + "/v1/tts/live", model, request_options + ) async with achecked_websocket( aconnect_ws( "/v1/tts/live", diff --git a/tests/unit/test_header_provider.py b/tests/unit/test_header_provider.py index 039f507..9a49cb8 100644 --- a/tests/unit/test_header_provider.py +++ b/tests/unit/test_header_provider.py @@ -598,3 +598,201 @@ async def audio(): finally: for server in servers: server.close() + + +class TestCallerTask: + """The provider runs in the caller's task (async) or thread (sync), on + every WebSocket: a provider that looks request data up by + ``asyncio.current_task()`` or by thread finds it.""" + + async def test_async_handshakes_run_in_the_iterating_task(self): + by_task: dict[Any, str] = {} + + def task_keyed() -> dict[str, Optional[str]]: + return {"traceparent": by_task[asyncio.current_task()]} + + async def text(): + yield "hi" + + async def audio(): + yield b"\x00\x00" + + async def tts(client: AsyncFishAudio) -> None: + async for _ in client.tts.stream_websocket(text()): + pass + + async def stt(client: AsyncFishAudio) -> None: + async for _ in client.asr.stream_websocket(audio()): + pass + + for open_stream in (tts, stt): + with refusing_ws_server() as server: + client = AsyncFishAudio( + api_key="test-key", base_url=server.url, header_provider=task_keyed + ) + + async def request() -> None: + by_task[asyncio.current_task()] = TRACE_A + await open_stream(client) # noqa: B023 + + with pytest.raises((WebSocketUpgradeError, AuthenticationError)): + await asyncio.create_task(request()) + await client.close() + conn = server.stop() + assert values(conn.header_list, "traceparent") == [TRACE_A], open_stream + + def test_sync_handshakes_run_on_the_iterating_thread(self): + by_thread: dict[int, str] = {} + + def thread_keyed() -> dict[str, Optional[str]]: + return {"traceparent": by_thread[threading.get_ident()]} + + for open_stream in ( + lambda c: list(c.tts.stream_websocket(iter(["hi"]))), + lambda c: list(c.asr.stream_websocket(iter([b"\x00\x00"]))), + ): + with refusing_ws_server() as server: + client = FishAudio( + api_key="test-key", + base_url=server.url, + header_provider=thread_keyed, + ) + errors: list[BaseException] = [] + + def request() -> None: + by_thread[threading.get_ident()] = TRACE_A + try: + open_stream(client) # noqa: B023 + except BaseException as e: # noqa: BLE001 + errors.append(e) + + thread = threading.Thread(target=request) + thread.start() + thread.join() + client.close() + conn = server.stop() + assert len(errors) == 1 + assert isinstance(errors[0], (WebSocketUpgradeError, AuthenticationError)) + assert values(conn.header_list, "traceparent") == [TRACE_A] + + async def test_async_asr_provider_error_is_raised_in_the_caller_and_ends_the_stream( + self, + ): + def provider() -> dict[str, str]: + assert asyncio.current_task() is caller + raise LookupError("no request") + + async def audio(): + yield b"\x00\x00" + + with refusing_ws_server() as server: + client = AsyncFishAudio( + api_key="test-key", base_url=server.url, header_provider=provider + ) + stream = client.asr.stream_websocket(audio()) + caller = asyncio.current_task() + with pytest.raises(LookupError): + await stream.__anext__() + with pytest.raises(StopAsyncIteration): + await stream.__anext__() + await client.close() + server.close() + assert server.connection is None # nothing was sent + + +class TestWhenTheProviderRuns: + """When each streaming method sends its request, and so calls the + provider: what the README's timing rules state.""" + + def test_sync_http_streams_send_before_returning(self): + with recording_server() as (url, seen): + provider = Counter() + client = FishAudio( + api_key="test-key", base_url=url, header_provider=provider + ) + stream = client.tts.stream(text="hi") + assert provider.calls == 1 and len(seen) == 1 # before iteration + stream.collect() + events = client.tts.stream_with_timestamps(text="hi") + assert provider.calls == 2 and len(seen) == 2 + list(events) + client.close() + assert provider.calls == 2 + + async def test_async_http_streams_send_when_awaited(self): + with recording_server() as (url, seen): + provider = Counter() + client = AsyncFishAudio( + api_key="test-key", base_url=url, header_provider=provider + ) + pending = client.tts.stream(text="hi") + assert provider.calls == 0 # a coroutine: nothing has run yet + stream = await pending + assert provider.calls == 1 and len(seen) == 1 # before iteration + await stream.collect() + pending = client.tts.stream_with_timestamps(text="hi") + assert provider.calls == 1 + events = await pending + assert provider.calls == 2 and len(seen) == 2 + async for _ in events: + pass + await client.close() + + def test_sync_websockets_connect_on_first_iteration(self): + for open_stream in ( + lambda c: c.tts.stream_websocket(iter(["hi"])), + lambda c: c.asr.stream_websocket(iter([b"\x00\x00"])), + ): + with refusing_ws_server() as server: + provider = Counter() + client = FishAudio( + api_key="test-key", base_url=server.url, header_provider=provider + ) + stream = open_stream(client) + assert provider.calls == 0 + with pytest.raises((WebSocketUpgradeError, AuthenticationError)): + next(iter(stream)) + assert provider.calls == 1 + client.close() + server.stop() + + async def test_async_websockets_connect_on_first_iteration(self): + async def text(): + yield "hi" + + async def audio(): + yield b"\x00\x00" + + for open_stream in ( + lambda c: c.tts.stream_websocket(text()), + lambda c: c.asr.stream_websocket(audio()), + ): + with refusing_ws_server() as server: + provider = Counter() + client = AsyncFishAudio( + api_key="test-key", base_url=server.url, header_provider=provider + ) + stream = open_stream(client) + assert provider.calls == 0 + with pytest.raises((WebSocketUpgradeError, AuthenticationError)): + await stream.__aiter__().__anext__() + assert provider.calls == 1 + await client.close() + server.stop() + + +class TestPerCallValues: + def test_an_empty_per_call_value_wins_over_the_provider(self): + """The SDK has no per-call form for "send no such header": an empty + value is sent as given, and the provider does not put its own back.""" + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", + base_url=url, + header_provider=lambda: {"traceparent": TRACE_A}, + ) + client.account.get_credits( + request_options=RequestOptions(additional_headers={"traceparent": ""}) + ) + client.close() + assert values(seen[0][1], "traceparent") == [""] diff --git a/tests/unit/test_header_values.py b/tests/unit/test_header_values.py index e846633..877f88f 100644 --- a/tests/unit/test_header_values.py +++ b/tests/unit/test_header_values.py @@ -206,8 +206,14 @@ def assert_sdk_error( ("x-name", "a\x7fb", "a control character"), ("x-name", "a\x01b", "a control character"), ("x-name", "a\x00b", "a control character"), - ("x-name", "a\r\nb", "a line break"), - ("x-name", "a\nInjected: yes", "a line break"), + ("x-name", "a\r\nb", "a control character"), + ("x-name", "a\nInjected: yes", "a control character"), + ("x-name", "a\rb", "a control character"), + # Several kinds in one value: control, then non-ASCII, then whitespace. + ("x-name", " café\n", "a control character"), + ("x-name", "\x7fé", "a control character"), + ("x-name", " café ", "a non-ASCII character"), + ("x-name", "é ", "a non-ASCII character"), ("Authorization", "a\r\nb", IGNORED), ("Authorization", "café", IGNORED), ("x-name", "a \t b", SENT), diff --git a/tests/unit/test_opentelemetry_default.py b/tests/unit/test_opentelemetry_default.py index ef343c7..474d366 100644 --- a/tests/unit/test_opentelemetry_default.py +++ b/tests/unit/test_opentelemetry_default.py @@ -2,6 +2,7 @@ from __future__ import annotations +import contextlib import subprocess import sys import textwrap @@ -9,16 +10,28 @@ import pytest from httpx_ws import WebSocketUpgradeError -from opentelemetry import trace +from opentelemetry import baggage, propagate, trace +from opentelemetry import context as otel_context +from opentelemetry.baggage.propagation import W3CBaggagePropagator from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor +from opentelemetry.instrumentation.utils import ( + suppress_http_instrumentation, + suppress_instrumentation, +) +from opentelemetry.propagators.composite import CompositePropagator from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( InMemorySpanExporter, ) from opentelemetry.sdk.trace.sampling import ALWAYS_OFF +from opentelemetry.trace import TraceState +from opentelemetry.trace.propagation.tracecontext import ( + TraceContextTextMapPropagator, +) +from opentelemetry.util.http import get_excluded_urls -from fishaudio import AsyncFishAudio, FishAudio, opentelemetry_headers +from fishaudio import AsyncFishAudio, FishAudio, RequestOptions, opentelemetry_headers from fishaudio.core import tracing from fishaudio.exceptions import AuthenticationError @@ -51,10 +64,10 @@ def tracer_provider(): @pytest.fixture def no_opentelemetry(monkeypatch): """Behave as if the opentelemetry-api package were not installed.""" - monkeypatch.setitem(sys.modules, "opentelemetry.trace", None) # import fails - monkeypatch.setattr(tracing, "_get_current_span", None) + monkeypatch.setitem(sys.modules, "opentelemetry", None) # import fails + monkeypatch.setattr(tracing, "_otel", None) yield - tracing._get_current_span = None + tracing._otel = None def get_credits_headers(client: FishAudio, seen: list) -> list[tuple[str, str]]: @@ -129,10 +142,10 @@ def test_api_absent_sends_nothing(self, no_opentelemetry, tracer_provider): assert values(headers, "traceparent") == [] def test_an_opentelemetry_error_never_fails_the_request(self, monkeypatch): - def broken(): - raise RuntimeError("broken tracer") + def broken(carrier): + raise RuntimeError("broken propagator") - monkeypatch.setattr(tracing, "_get_current_span", broken) + monkeypatch.setattr(tracing._opentelemetry(), "inject", broken) with recording_server() as (url, seen): client = FishAudio(api_key="test-key", base_url=url) headers = get_credits_headers(client, seen) @@ -288,3 +301,353 @@ async def stt(client): self.assert_one_correct_trace( conn.header_list, outer, instrumented.exporter ) + + +# -- The OpenTelemetry controls that keep trace context off a request ------- + + +@pytest.fixture +def fresh_otel(monkeypatch): + """The default provider looks OpenTelemetry up again on first use.""" + monkeypatch.setattr(tracing, "_otel", None) + yield + tracing._otel = None + + +@pytest.fixture +def without_instrumentation_utils(monkeypatch, fresh_otel): + """Behave as if opentelemetry-instrumentation were not installed.""" + monkeypatch.setitem(sys.modules, "opentelemetry.instrumentation.utils", None) + + +@pytest.fixture +def without_util_http(monkeypatch, fresh_otel): + """Behave as if opentelemetry-util-http were not installed.""" + monkeypatch.setitem(sys.modules, "opentelemetry.util.http", None) + + +@pytest.fixture +def no_excluded_urls(monkeypatch): + monkeypatch.delenv("OTEL_PYTHON_HTTPX_EXCLUDED_URLS", raising=False) + monkeypatch.delenv("OTEL_PYTHON_EXCLUDED_URLS", raising=False) + + +def sent_by_default(tracer_provider, block=contextlib.nullcontext) -> list[list[str]]: + """The traceparent values the default provider puts on an HTTP request and + on both WebSocket handshakes, with ``block()`` around the calls.""" + sent = [] + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + with tracer_provider.get_tracer("t").start_as_current_span("s"), block(): + client.account.get_credits() + client.tts.convert(text="hi") + client.close() + sent += [values(headers, "traceparent") for _, headers in seen] + for open_stream in ( + lambda c: list(c.tts.stream_websocket(iter(["hi"]))), + lambda c: list(c.asr.stream_websocket(iter([b"\x00\x00"]))), + ): + server = RealtimeServer(lambda conn: None, reject_status=401) + try: + client = FishAudio(api_key="test-key", base_url=server.url) + with ( + tracer_provider.get_tracer("t").start_as_current_span("s"), + block(), + pytest.raises((WebSocketUpgradeError, AuthenticationError)), + ): + open_stream(client) + client.close() + sent.append(values(server.stop().header_list, "traceparent")) + finally: + server.close() + return sent + + +async def sent_by_default_async(tracer_provider, block) -> list[list[str]]: + """As ``sent_by_default``, with ``AsyncFishAudio``.""" + + async def text(): + yield "hi" + + async def audio(): + yield b"\x00\x00" + + sent = [] + with recording_server() as (url, seen): + client = AsyncFishAudio(api_key="test-key", base_url=url) + with tracer_provider.get_tracer("t").start_as_current_span("s"), block(): + await client.account.get_credits() + await client.tts.convert(text="hi") + await client.close() + sent += [values(headers, "traceparent") for _, headers in seen] + + async def tts(c): + async for _ in c.tts.stream_websocket(text()): + pass + + async def stt(c): + async for _ in c.asr.stream_websocket(audio()): + pass + + for open_stream in (tts, stt): + server = RealtimeServer(lambda conn: None, reject_status=401) + try: + client = AsyncFishAudio(api_key="test-key", base_url=server.url) + with ( + tracer_provider.get_tracer("t").start_as_current_span("s"), + block(), + pytest.raises((WebSocketUpgradeError, AuthenticationError)), + ): + await open_stream(client) + await client.close() + sent.append(values(server.stop().header_list, "traceparent")) + finally: + server.close() + return sent + + +def _set_context_value(key): + """A block that sets an OpenTelemetry context value to True, as the + suppress_* context managers do.""" + + @contextlib.contextmanager + def block(): + token = otel_context.attach(otel_context.set_value(key, True)) + try: + yield + finally: + otel_context.detach(token) + + return block + + +@pytest.mark.usefixtures("no_excluded_urls") +class TestSuppression: + """``suppress_instrumentation()`` and ``suppress_http_instrumentation()`` + keep the default provider's traceparent off every request, as they keep + the httpx instrumentation's off.""" + + def test_control(self, tracer_provider): + sent = sent_by_default(tracer_provider) + assert [len(s) for s in sent] == [1, 1, 1, 1] + + @pytest.mark.parametrize( + "block", [suppress_instrumentation, suppress_http_instrumentation] + ) + def test_sync(self, tracer_provider, block): + assert sent_by_default(tracer_provider, block) == [[], [], [], []] + + @pytest.mark.parametrize( + "block", [suppress_instrumentation, suppress_http_instrumentation] + ) + async def test_async(self, tracer_provider, block): + assert await sent_by_default_async(tracer_provider, block) == [[], [], [], []] + + @pytest.mark.parametrize( + "key", + [ + otel_context._SUPPRESS_INSTRUMENTATION_KEY, + otel_context._SUPPRESS_HTTP_INSTRUMENTATION_KEY, + "suppress_instrumentation", + ], + ) + def test_without_opentelemetry_instrumentation_installed( + self, tracer_provider, without_instrumentation_utils, key + ): + """The same context keys are read from the API itself.""" + assert sent_by_default(tracer_provider) != [[], [], [], []] + assert tracing._opentelemetry().is_http_instrumentation_enabled is None + assert sent_by_default(tracer_provider, _set_context_value(key)) == [ + [], + [], + [], + [], + ] + + def test_also_with_the_httpx_instrumentation(self, instrumented): + """With the instrumentation on, neither adds a traceparent.""" + assert sent_by_default(instrumented, suppress_http_instrumentation) == [ + [], + [], + [], + [], + ] + + def test_is_how_to_send_no_traceparent_on_one_call(self, tracer_provider): + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + with tracer_provider.get_tracer("t").start_as_current_span("s"): + client.account.get_credits() + with suppress_http_instrumentation(): + client.account.get_credits() + client.account.get_credits() + client.close() + assert [len(values(h, "traceparent")) for _, h in seen] == [1, 0, 1] + + +class TestExcludedURLs: + """``OTEL_PYTHON_HTTPX_EXCLUDED_URLS`` (else ``OTEL_PYTHON_EXCLUDED_URLS``): + regular expressions searched in the request's full URL.""" + + @pytest.mark.usefixtures("no_excluded_urls") + def test_httpx_variable(self, tracer_provider, monkeypatch): + monkeypatch.setenv("OTEL_PYTHON_HTTPX_EXCLUDED_URLS", r"/v1/tts") + # account (/wallet/...): sent; tts.convert, the TTS handshake: not; + # the realtime STT handshake (/v1/asr/realtime): sent. + sent = sent_by_default(tracer_provider) + assert [len(s) for s in sent] == [1, 0, 0, 1] + + @pytest.mark.usefixtures("no_excluded_urls") + def test_generic_variable_when_the_httpx_one_is_unset( + self, tracer_provider, monkeypatch + ): + monkeypatch.setenv("OTEL_PYTHON_EXCLUDED_URLS", r"127\.0\.0\.1:\d+/v1/asr/") + assert [len(s) for s in sent_by_default(tracer_provider)] == [1, 1, 1, 0] + monkeypatch.setenv("OTEL_PYTHON_HTTPX_EXCLUDED_URLS", "nothing-matches") + assert [len(s) for s in sent_by_default(tracer_provider)] == [1, 1, 1, 1] + + @pytest.mark.usefixtures("no_excluded_urls") + async def test_async(self, tracer_provider, monkeypatch): + monkeypatch.setenv("OTEL_PYTHON_HTTPX_EXCLUDED_URLS", r"/v1/tts, /wallet/") + sent = await sent_by_default_async(tracer_provider, contextlib.nullcontext) + assert [len(s) for s in sent] == [0, 0, 0, 1] + + @pytest.mark.usefixtures("no_excluded_urls") + def test_matches_the_url_with_its_query(self, tracer_provider, monkeypatch): + monkeypatch.setenv("OTEL_PYTHON_HTTPX_EXCLUDED_URLS", r"\?q=skip") + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + with tracer_provider.get_tracer("t").start_as_current_span("s"): + for q in ("skip", "keep"): + client.account.get_credits( + request_options=RequestOptions(additional_query_params={"q": q}) + ) + client.close() + assert [len(values(h, "traceparent")) for _, h in seen] == [0, 1] + + @pytest.mark.usefixtures("no_excluded_urls") + def test_also_inside_your_own_provider(self, tracer_provider, monkeypatch): + monkeypatch.setenv("OTEL_PYTHON_HTTPX_EXCLUDED_URLS", r"/v1/tts") + with recording_server() as (url, seen): + client = FishAudio( + api_key="test-key", + base_url=url, + header_provider=lambda: { + **(opentelemetry_headers() or {}), + "x-request-id": "r1", + }, + ) + with tracer_provider.get_tracer("t").start_as_current_span("s"): + client.account.get_credits() + client.tts.convert(text="hi") + client.close() + assert [len(values(h, "traceparent")) for _, h in seen] == [1, 0] + assert [values(h, "x-request-id") for _, h in seen] == [["r1"], ["r1"]] + + @pytest.mark.usefixtures("no_excluded_urls") + def test_called_outside_the_sdk_it_knows_no_url(self, tracer_provider, monkeypatch): + monkeypatch.setenv("OTEL_PYTHON_EXCLUDED_URLS", ".*") + with tracer_provider.get_tracer("t").start_as_current_span("s"): + assert opentelemetry_headers() is not None + + @pytest.mark.usefixtures("no_excluded_urls") + def test_without_opentelemetry_util_http_installed( + self, tracer_provider, monkeypatch, without_util_http + ): + monkeypatch.setenv("OTEL_PYTHON_HTTPX_EXCLUDED_URLS", r"/v1/tts") + assert [len(s) for s in sent_by_default(tracer_provider)] == [1, 0, 0, 1] + assert tracing._opentelemetry().get_excluded_urls is tracing._get_excluded_urls + + @pytest.mark.parametrize( + "httpx_value, generic_value", + [ + (None, None), + ("", "x"), + (None, "a, b ,c"), + ("v1/tts,wallet", "x"), + (r"^https://api\.fish\.audio/v1/tts$", None), + ("tts,", None), + ], + ) + def test_fallback_reads_the_variables_as_opentelemetry_util_http_does( + self, monkeypatch, httpx_value, generic_value + ): + for name, value in ( + ("OTEL_PYTHON_HTTPX_EXCLUDED_URLS", httpx_value), + ("OTEL_PYTHON_EXCLUDED_URLS", generic_value), + ): + if value is None: + monkeypatch.delenv(name, raising=False) + else: + monkeypatch.setenv(name, value) + theirs = get_excluded_urls("HTTPX") + ours = tracing._get_excluded_urls("HTTPX") + for url in ( + "https://api.fish.audio/v1/tts", + "https://api.fish.audio/wallet/self/api-credit", + "http://x/a", + "http://x/b?c=1", + "", + ): + assert ours.url_disabled(url) == theirs.url_disabled(url), url + + def test_also_with_the_httpx_instrumentation(self, tracer_provider, monkeypatch): + """Set before the instrumentation is turned on (it reads the variable + then): neither adds a traceparent to an excluded URL.""" + monkeypatch.delenv("OTEL_PYTHON_EXCLUDED_URLS", raising=False) + monkeypatch.setenv("OTEL_PYTHON_HTTPX_EXCLUDED_URLS", r"/v1/tts") + instrumentor = HTTPXClientInstrumentor() + instrumentor.instrument(tracer_provider=tracer_provider) + try: + sent = sent_by_default(tracer_provider) + finally: + instrumentor.uninstrument() + assert [len(s) for s in sent] == [1, 0, 0, 1] + + +class TestPropagators: + """The configured propagators decide whether a traceparent is written.""" + + @pytest.fixture + def textmap(self): + previous = propagate.get_global_textmap() + yield propagate.set_global_textmap + propagate.set_global_textmap(previous) + + def test_none_configured_sends_nothing(self, tracer_provider, textmap): + textmap(CompositePropagator([])) # OTEL_PROPAGATORS=none + with tracer_provider.get_tracer("t").start_as_current_span("s"): + assert opentelemetry_headers() is None + + def test_baggage_alone_sends_nothing(self, tracer_provider, textmap): + textmap(W3CBaggagePropagator()) + with tracer_provider.get_tracer("t").start_as_current_span("s"): + assert opentelemetry_headers() is None + + def test_tracecontext_sends_only_traceparent(self, tracer_provider, textmap): + textmap( + CompositePropagator( + [TraceContextTextMapPropagator(), W3CBaggagePropagator()] + ) + ) + state = TraceState([("vendor", "v")]) + with tracer_provider.get_tracer("t").start_as_current_span("s") as span: + parent = span.get_span_context() + ctx = trace.set_span_in_context( + trace.NonRecordingSpan( + trace.SpanContext( + parent.trace_id, + parent.span_id, + is_remote=False, + trace_flags=parent.trace_flags, + trace_state=state, + ) + ), + baggage.set_baggage("user", "secret"), + ) + token = otel_context.attach(ctx) + try: + headers = opentelemetry_headers() + finally: + otel_context.detach(token) + assert headers == {"traceparent": traceparent_of(span)} diff --git a/tests/unit/test_trace_continued.py b/tests/unit/test_trace_continued.py index 1b771a1..cc71bd9 100644 --- a/tests/unit/test_trace_continued.py +++ b/tests/unit/test_trace_continued.py @@ -1,4 +1,4 @@ -"""The warning when the API did not continue the trace the SDK sent. +"""The warning when the trace the API used is not the one the SDK sent. The local servers answer like the Fish Audio gateway: a request with exactly one valid ``traceparent`` continues its trace, anything else gets a new one, @@ -163,12 +163,19 @@ def test_not_continued_warns_sync(self, call, status): (message,) = trace_warnings(caught) assert f"sent trace id {TRACE_A_ID}" in message assert re.search(r"the API used [0-9a-f]{32}\)", message) + assert message.startswith( + "The trace this SDK sent is not the one Fish Audio used " + f"(sent trace id {TRACE_A_ID}; the API used " + ) assert "The value the SDK sent is valid" in message - assert "added a second traceparent or replaced it" in message + # The transport changed the request object httpx recorded: the SDK + # can tell it happened in this process. + assert "changed in this process" in message + assert "went out with 2 traceparent headers" in message assert "instrumentation" not in message assert "https://docs.fish.audio/api-reference/observability" in message # It names the caller's line, not the SDK's. - (warning,) = [w for w in caught if "Fish Audio" in str(w.message)] + (warning,) = [w for w in caught if "Fish Audio used" in str(w.message)] assert warning.filename == __file__ @pytest.mark.parametrize("status", [200, 401, 500]) @@ -322,7 +329,7 @@ def test_invalid_sent_value_warns_without_echoing_it(self, sent): client.account.get_credits() client.close() (message,) = trace_warnings(caught) - assert "the traceparent it sent is not one the API accepts" in message + assert "(sent a traceparent the API does not accept;" in message assert "lowercase version-00 W3C traceparent" in message assert sent not in message assert SECRET_VALUE not in message @@ -348,7 +355,7 @@ def test_future_version_not_continued_is_not_one_the_api_accepts(self): client.account.get_credits() client.close() (message,) = trace_warnings(caught) - assert "the traceparent it sent is not one the API accepts" in message + assert "(sent a traceparent the API does not accept;" in message assert TRACE_A_ID not in message.split("the API used")[0] def test_more_than_one_sent_is_counted(self): @@ -367,7 +374,7 @@ def test_more_than_one_sent_is_counted(self): client.close() assert values(seen[0][1], "traceparent") == [TRACE_A, other] (message,) = trace_warnings(caught) - assert "(2 traceparent headers;" in message + assert "(sent 2 traceparent headers;" in message assert "exactly one traceparent" in message @@ -389,7 +396,9 @@ def test_simplefilter_error_does_not_fail_the_request(self, status, caplog): client.close() # The message is not lost: it is logged instead. assert [ - r.levelno for r in caplog.records if "Fish Audio did not" in r.message + r.levelno + for r in caplog.records + if "not the one Fish Audio used" in r.message ] == [logging.WARNING] async def test_simplefilter_error_async_and_websocket(self): @@ -441,7 +450,7 @@ def test_python_dash_w_error(self): assert result.returncode == 0, result.stderr assert result.stdout.strip() == "ok" assert len(seen) == 2 - assert result.stderr.count("Fish Audio did not continue the trace") == 1 + assert result.stderr.count("is not the one Fish Audio used") == 1 def test_filterable_by_category(self): with recording_server(200, lambda _: OTHER_ID) as (url, _): @@ -561,7 +570,7 @@ def test_sync_not_continued(self, kind, refused): with recorded() as caught: self.run_sync(kind, refused, provide(SECRET_VALUE)) (message,) = trace_warnings(caught) - assert "not one the API accepts" in message + assert "a traceparent the API does not accept" in message assert SECRET_VALUE not in message def test_sync_no_response_header(self, kind, refused): @@ -669,6 +678,145 @@ async def test_handshakes_async(self, instrumented, kind): assert trace_warnings(caught) == [] +class TestReplacedByTheInstrumentation: + """Your own provider sends trace A while the httpx instrumentation is on + with a current span in trace B: the instrumentation replaces A with its + own span's traceparent, in B, and the API continues B. The warning says + what was sent and what was used, and that the value changed in this + process, without saying the API failed to continue it.""" + + @staticmethod + def assert_replaced(message: str, outer_trace: str) -> None: + assert message.startswith( + "The trace this SDK sent is not the one Fish Audio used " + f"(sent trace id {TRACE_A_ID}; the API used {outer_trace})." + ) + assert "changed in this process" in message + assert f"went out with trace id {outer_trace}" in message + assert "opentelemetry-instrumentation-httpx" in message + assert "did not continue" not in message + + def test_http_sync(self, instrumented): + with recording_server(200, gateway) as (url, seen), recorded() as caught: + client = FishAudio( + api_key="k", base_url=url, header_provider=provide(TRACE_A) + ) + with instrumented.get_tracer("t").start_as_current_span("outer") as outer: + client.account.get_credits() + client.close() + outer_trace = f"{outer.get_span_context().trace_id:032x}" + # The instrumentation really replaced the provider's value. + ((_, headers),) = seen + (sent,) = values(headers, "traceparent") + assert sent.split("-")[1] == outer_trace + (warning,) = [ + w + for w in caught + if issubclass(w.category, fishaudio.TraceNotContinuedWarning) + ] + self.assert_replaced(str(warning.message), outer_trace) + assert warning.filename == __file__ + + async def test_http_async_stream(self, instrumented): + with recording_server(200, gateway) as (url, _), recorded() as caught: + client = AsyncFishAudio( + api_key="k", base_url=url, header_provider=provide(TRACE_A) + ) + with instrumented.get_tracer("t").start_as_current_span("outer") as outer: + await _astream(client) + await client.close() + (message,) = trace_warnings(caught) + self.assert_replaced(message, f"{outer.get_span_context().trace_id:032x}") + + @pytest.mark.parametrize("kind", ["tts", "stt"]) + def test_handshakes_sync(self, instrumented, kind): + server = ws_server(kind, refused=False) + try: + with recorded() as caught: + client = FishAudio( + api_key="k", base_url=server.url, header_provider=provide(TRACE_A) + ) + with instrumented.get_tracer("t").start_as_current_span("o") as outer: + SYNC_WS[kind](client) + client.close() + server.stop() + finally: + server.close() + (message,) = trace_warnings(caught) + self.assert_replaced(message, f"{outer.get_span_context().trace_id:032x}") + + +def test_unchanged_on_the_request_says_so(): + """The value was still on the request httpx handed to the transport: the + cause is after that point, or the API.""" + with ( + recording_server(200, lambda _: OTHER_ID) as (url, _), + recorded() as caught, + ): + client = FishAudio(api_key="k", base_url=url, header_provider=provide(TRACE_A)) + client.account.get_credits() + client.close() + (message,) = trace_warnings(caught) + assert message.startswith( + "The trace this SDK sent is not the one Fish Audio used " + f"(sent trace id {TRACE_A_ID}; the API used {OTHER_ID})." + ) + assert "was still on the request when httpx handed it to the transport" in message + assert "changed in this process" not in message + + +def test_request_not_visible_lists_possible_causes(): + response = httpx.Response(200, headers={"x-fish-trace-id": OTHER_ID}) + with recorded() as caught: + tracing.check_trace_continued([TRACE_A], response) + (message,) = trace_warnings(caught) + assert "Possible causes" in message + assert "opentelemetry-instrumentation-httpx" in message + + +@pytest.mark.parametrize("kind", ["tts", "stt"]) +async def test_async_handshake_warning_names_the_callers_line(kind): + server = ws_server( + kind, refused=False, response_headers=lambda _: [("x-fish-trace-id", OTHER_ID)] + ) + try: + with recorded() as caught: + client = AsyncFishAudio( + api_key="k", base_url=server.url, header_provider=provide(TRACE_A) + ) + await ASYNC_WS[kind](client) + await client.close() + await asyncio.get_running_loop().run_in_executor(None, server.stop) + finally: + server.close() + (warning,) = [ + w for w in caught if issubclass(w.category, fishaudio.TraceNotContinuedWarning) + ] + assert warning.filename == __file__ + + +@pytest.mark.parametrize("kind", ["tts", "stt"]) +def test_sync_handshake_warning_names_the_callers_line(kind): + server = ws_server( + kind, refused=True, response_headers=lambda _: [("x-fish-trace-id", OTHER_ID)] + ) + try: + with recorded() as caught: + client = FishAudio( + api_key="k", base_url=server.url, header_provider=provide(TRACE_A) + ) + with pytest.raises((WebSocketUpgradeError, AuthenticationError)): + SYNC_WS[kind](client) + client.close() + server.stop() + finally: + server.close() + (warning,) = [ + w for w in caught if issubclass(w.category, fishaudio.TraceNotContinuedWarning) + ] + assert warning.filename == __file__ + + def test_exported(): assert issubclass(fishaudio.TraceNotContinuedWarning, UserWarning) assert "TraceNotContinuedWarning" in fishaudio.__all__ diff --git a/tests/unit/test_tts_realtime.py b/tests/unit/test_tts_realtime.py index b4ee996..d64353d 100644 --- a/tests/unit/test_tts_realtime.py +++ b/tests/unit/test_tts_realtime.py @@ -23,7 +23,7 @@ def mock_client_wrapper(mock_api_key): "User-Agent": "fish-audio-python/test", **(additional or {}), } - wrapper.websocket_kwargs = lambda model, request_options=None: { + wrapper.websocket_kwargs = lambda path, model, request_options=None: { "headers": wrapper.get_headers({"model": model}) } return wrapper @@ -42,7 +42,7 @@ def async_mock_client_wrapper(mock_api_key): "User-Agent": "fish-audio-python/test", **(additional or {}), } - wrapper.websocket_kwargs = lambda model, request_options=None: { + wrapper.websocket_kwargs = lambda path, model, request_options=None: { "headers": wrapper.get_headers({"model": model}) } return wrapper From aefa72e12f0732d72b73a5efcd4583b8fb9cc189 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:44:32 -0800 Subject: [PATCH 7/7] fix: send no trace header when OpenTelemetry cannot be loaded as configured Importing opentelemetry.propagate raises ValueError when OTEL_PROPAGATORS names a propagator whose package is not installed. The default provider caught only ImportError, so a deployment-level tracing setting failed tts.convert before anything was sent. Co-Authored-By: Claude Fable 5.2 --- src/fishaudio/core/tracing.py | 7 +++++ tests/unit/test_opentelemetry_default.py | 34 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/fishaudio/core/tracing.py b/src/fishaudio/core/tracing.py index c2d6623..26c292d 100644 --- a/src/fishaudio/core/tracing.py +++ b/src/fishaudio/core/tracing.py @@ -108,6 +108,13 @@ def _opentelemetry() -> Any: _otel = _OpenTelemetry() except ImportError: _otel = False + except Exception: + # OpenTelemetry is installed but cannot be loaded as configured: + # importing opentelemetry.propagate raises ValueError when + # OTEL_PROPAGATORS names a propagator whose package is missing. + # Optional tracing must never fail a request, so send nothing. + logger.debug("OpenTelemetry could not be loaded", exc_info=True) + _otel = False return _otel diff --git a/tests/unit/test_opentelemetry_default.py b/tests/unit/test_opentelemetry_default.py index 474d366..7f37c74 100644 --- a/tests/unit/test_opentelemetry_default.py +++ b/tests/unit/test_opentelemetry_default.py @@ -651,3 +651,37 @@ def test_tracecontext_sends_only_traceparent(self, tracer_provider, textmap): finally: otel_context.detach(token) assert headers == {"traceparent": traceparent_of(span)} + + +class TestOpenTelemetryThatCannotBeLoaded: + """OpenTelemetry is installed but fails to load as configured, for example + OTEL_PROPAGATORS names a propagator whose package is missing (importing + opentelemetry.propagate then raises ValueError). The default provider + must send nothing rather than fail the request.""" + + def test_a_load_error_sends_no_header_and_does_not_raise(self, monkeypatch): + from fishaudio.core import tracing + + def broken(): + raise ValueError("Propagator b3 not found") + + monkeypatch.setattr(tracing, "_otel", None) + monkeypatch.setattr(tracing, "_OpenTelemetry", broken) + assert tracing.opentelemetry_headers() is None + # Not retried on every request. + assert tracing._otel is False + + def test_missing_propagator_package_in_a_fresh_process(self): + import subprocess + import sys + + code = ( + "import os; os.environ['OTEL_PROPAGATORS'] = 'b3'\n" + "from fishaudio.core import tracing\n" + "print(repr(tracing.opentelemetry_headers()))\n" + ) + done = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, check=False + ) + assert done.returncode == 0, done.stderr + assert done.stdout.strip() == "None"