diff --git a/pyproject.toml b/pyproject.toml index 561a5a45..1935ed72 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -72,9 +72,10 @@ exclude = ["tests/"] testpaths = ["tests"] python_files = "test_*.py" python_functions = "test_*" -addopts = "-ra --strict-markers" +addopts = "-ra --strict-markers --dist loadgroup" markers = [ "asyncio: mark a test as a coroutine that should be run by pytest-asyncio", + "xdist_group: mark a test to run in a specific sequential group for isolation", ] [tool.pytest-asyncio] @@ -93,6 +94,7 @@ dev = [ "pytest-asyncio>=0.26.0", "pytest-cov>=6.1.1", "pytest-mock>=3.14.0", + "pytest-xdist>=3.6.1", "respx>=0.20.2", "ruff>=0.12.8", "uv-dynamic-versioning>=0.8.2", diff --git a/src/a2a/utils/telemetry.py b/src/a2a/utils/telemetry.py index c73d2ac9..c8e13ec0 100644 --- a/src/a2a/utils/telemetry.py +++ b/src/a2a/utils/telemetry.py @@ -18,6 +18,16 @@ - Automatic recording of exceptions and setting of span status. - Selective method tracing in classes using include/exclude lists. +Configuration: +- Environment Variable Control: OpenTelemetry instrumentation can be + disabled using the `OTEL_INSTRUMENTATION_A2A_SDK_ENABLED` environment + variable. + + - Default: `true` (tracing enabled when OpenTelemetry is installed) + - To disable: Set `OTEL_INSTRUMENTATION_A2A_SDK_ENABLED=false` + - Case insensitive: 'true', 'True', 'TRUE' all enable tracing + - Any other value disables tracing and logs a debug message + Usage: For a single function: ```python @@ -57,9 +67,11 @@ def internal_method(self): import functools import inspect import logging +import os from collections.abc import Callable from typing import TYPE_CHECKING, Any +from typing_extensions import Self if TYPE_CHECKING: @@ -74,11 +86,33 @@ def internal_method(self): from opentelemetry.trace import SpanKind as _SpanKind from opentelemetry.trace import StatusCode + otel_installed = True + except ImportError: logger.debug( 'OpenTelemetry not found. Tracing will be disabled. ' 'Install with: \'pip install "a2a-sdk[telemetry]"\'' ) + otel_installed = False + +ENABLED_ENV_VAR = 'OTEL_INSTRUMENTATION_A2A_SDK_ENABLED' +INSTRUMENTING_MODULE_NAME = 'a2a-python-sdk' +INSTRUMENTING_MODULE_VERSION = '1.0.0' + +# Check if tracing is enabled via environment variable +env_value = os.getenv(ENABLED_ENV_VAR, 'true') +otel_enabled = env_value.lower() == 'true' + +# Log when tracing is explicitly disabled via environment variable +if otel_installed and not otel_enabled: + logger.debug( + 'A2A OTEL instrumentation disabled via environment variable ' + '%s=%r. Tracing will be disabled.', + ENABLED_ENV_VAR, + env_value, + ) + +if not otel_installed or not otel_enabled: class _NoOp: """A no-op object that absorbs all tracing calls when OpenTelemetry is not installed.""" @@ -86,7 +120,7 @@ class _NoOp: def __call__(self, *args: Any, **kwargs: Any) -> Any: return self - def __enter__(self) -> '_NoOp': + def __enter__(self) -> Self: return self def __exit__(self, *args: object, **kwargs: Any) -> None: @@ -99,12 +133,9 @@ def __getattr__(self, name: str) -> Any: _SpanKind = _NoOp() # type: ignore StatusCode = _NoOp() # type: ignore -SpanKind = _SpanKind +SpanKind = _SpanKind # type: ignore __all__ = ['SpanKind'] -INSTRUMENTING_MODULE_NAME = 'a2a-python-sdk' -INSTRUMENTING_MODULE_VERSION = '1.0.0' - def trace_function( # noqa: PLR0915 func: Callable | None = None, diff --git a/tests/utils/test_telemetry.py b/tests/utils/test_telemetry.py index eae96b19..a43bf1fa 100644 --- a/tests/utils/test_telemetry.py +++ b/tests/utils/test_telemetry.py @@ -1,6 +1,8 @@ import asyncio +import importlib +import sys -from collections.abc import Generator +from collections.abc import Callable, Generator from typing import Any, NoReturn from unittest import mock @@ -30,6 +32,32 @@ def patch_trace_get_tracer( yield +@pytest.fixture +def reload_telemetry_module( + monkeypatch: pytest.MonkeyPatch, +) -> Generator[Callable[[str | None], Any], None, None]: + """Fixture to handle telemetry module reloading with env var control.""" + + def _reload(env_value: str | None = None) -> Any: + if env_value is None: + monkeypatch.delenv( + 'OTEL_INSTRUMENTATION_A2A_SDK_ENABLED', raising=False + ) + else: + monkeypatch.setenv( + 'OTEL_INSTRUMENTATION_A2A_SDK_ENABLED', env_value + ) + + sys.modules.pop('a2a.utils.telemetry', None) + module = importlib.import_module('a2a.utils.telemetry') + return module + + yield _reload + + # Cleanup to ensure other tests aren't affected by a "poisoned" sys.modules + sys.modules.pop('a2a.utils.telemetry', None) + + def test_trace_function_sync_success(mock_span: mock.MagicMock) -> None: @trace_function def foo(x, y): @@ -198,3 +226,43 @@ def foo(self) -> str: assert obj.foo() == 'foo' assert hasattr(obj.foo, '__wrapped__') assert hasattr(obj, 'x') + + +@pytest.mark.xdist_group(name='telemetry_isolation') +@pytest.mark.parametrize( + 'env_value,expected_tracing', + [ + (None, True), # Default: env var not set, tracing enabled + ('true', True), # Explicitly enabled + ('True', True), # Case insensitive + ('false', False), # Disabled + ('', False), # Empty string = false + ], +) +def test_env_var_controls_instrumentation( + reload_telemetry_module: Callable[[str | None], Any], + env_value: str | None, + expected_tracing: bool, +) -> None: + """Test OTEL_INSTRUMENTATION_A2A_SDK_ENABLED controls span creation.""" + telemetry_module = reload_telemetry_module(env_value) + + is_noop = type(telemetry_module.trace).__name__ == '_NoOp' + + assert is_noop != expected_tracing + + +@pytest.mark.xdist_group(name='telemetry_isolation') +def test_env_var_disabled_logs_message( + reload_telemetry_module: Callable[[str | None], Any], + caplog: pytest.LogCaptureFixture, +) -> None: + """Test that disabling via env var logs appropriate debug message.""" + with caplog.at_level('DEBUG', logger='a2a.utils.telemetry'): + reload_telemetry_module('false') + + assert ( + 'A2A OTEL instrumentation disabled via environment variable' + in caplog.text + ) + assert 'OTEL_INSTRUMENTATION_A2A_SDK_ENABLED' in caplog.text diff --git a/uv.lock b/uv.lock index 710f1298..8e257c7a 100644 --- a/uv.lock +++ b/uv.lock @@ -77,6 +77,7 @@ dev = [ { name = "pytest-asyncio" }, { name = "pytest-cov" }, { name = "pytest-mock" }, + { name = "pytest-xdist" }, { name = "pyupgrade" }, { name = "respx" }, { name = "ruff" }, @@ -141,6 +142,7 @@ dev = [ { name = "pytest-asyncio", specifier = ">=0.26.0" }, { name = "pytest-cov", specifier = ">=6.1.1" }, { name = "pytest-mock", specifier = ">=3.14.0" }, + { name = "pytest-xdist", specifier = ">=3.6.1" }, { name = "pyupgrade" }, { name = "respx", specifier = ">=0.20.2" }, { name = "ruff", specifier = ">=0.12.8" }, @@ -750,6 +752,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/f4/c6e662dade71f56cd2f3735141b265c3c79293c109549c1e6933b0651ffc/exceptiongroup-1.3.0-py3-none-any.whl", hash = "sha256:4d111e6e0c13d0644cad6ddaa7ed0261a0b36971f6d23e7ec9b4b9097da78a10", size = 16674, upload-time = "2025-05-10T17:42:49.33Z" }, ] +[[package]] +name = "execnet" +version = "2.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/89/780e11f9588d9e7128a3f87788354c7946a9cbb1401ad38a48c4db9a4f07/execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd", size = 166622, upload-time = "2025-11-12T09:56:37.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" }, +] + [[package]] name = "fastapi" version = "0.128.0" @@ -1804,6 +1815,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5a/cc/06253936f4a7fa2e0f48dfe6d851d9c56df896a9ab09ac019d70b760619c/pytest_mock-3.15.1-py3-none-any.whl", hash = "sha256:0a25e2eb88fe5168d535041d09a4529a188176ae608a6d249ee65abc0949630d", size = 10095, upload-time = "2025-09-16T16:37:25.734Z" }, ] +[[package]] +name = "pytest-xdist" +version = "3.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "execnet" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/78/b4/439b179d1ff526791eb921115fca8e44e596a13efeda518b9d845a619450/pytest_xdist-3.8.0.tar.gz", hash = "sha256:7e578125ec9bc6050861aa93f2d59f1d8d085595d6551c2c90b6f4fad8d3a9f1", size = 88069, upload-time = "2025-07-01T13:30:59.346Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ca/31/d4e37e9e550c2b92a9cbc2e4d0b7420a27224968580b5a447f420847c975/pytest_xdist-3.8.0-py3-none-any.whl", hash = "sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88", size = 46396, upload-time = "2025-07-01T13:30:56.632Z" }, +] + [[package]] name = "pyupgrade" version = "3.21.2"