diff --git a/openhands-sdk/openhands/sdk/conversation/base.py b/openhands-sdk/openhands/sdk/conversation/base.py index a49970de5e3..1e50239bd3d 100644 --- a/openhands-sdk/openhands/sdk/conversation/base.py +++ b/openhands-sdk/openhands/sdk/conversation/base.py @@ -14,9 +14,10 @@ from openhands.sdk.llm.llm import LLM from openhands.sdk.llm.message import Message from openhands.sdk.observability.laminar import ( - end_active_span, + RootSpan, + end_root_span, should_enable_observability, - start_active_span, + start_root_span, ) from openhands.sdk.security.analyzer import SecurityAnalyzerBase from openhands.sdk.security.confirmation_policy import ( @@ -118,21 +119,36 @@ class BaseConversation(ABC): def __init__(self) -> None: """Initialize the base conversation with span tracking.""" self._span_ended = False + # Owned root span. The ``observe`` decorator looks up this attribute + # (by name ``_observability_root_span``) on ``self`` at every entry + # point and re-attaches it via ``Laminar.use_span`` so that nested + # spans correctly join the conversation trace even when the method + # is called from a different asyncio task or thread than the one + # that constructed the conversation. + self._observability_root_span: RootSpan | None = None def _start_observability_span(self, session_id: str) -> None: - """Start an observability span if observability is enabled. + """Start a per-conversation observability root span. Args: - session_id: The session ID to associate with the span + session_id: The session ID to associate with the trace """ - if should_enable_observability(): - start_active_span("conversation", session_id=session_id) + if not should_enable_observability(): + return + if self._observability_root_span is not None: + # Idempotent: never start two roots for one conversation. + return + self._observability_root_span = start_root_span( + "conversation", session_id=session_id + ) def _end_observability_span(self) -> None: """End the observability span if it hasn't been ended already.""" - if not self._span_ended and should_enable_observability(): - end_active_span() - self._span_ended = True + if self._span_ended: + return + end_root_span(self._observability_root_span) + self._observability_root_span = None + self._span_ended = True @property @abstractmethod diff --git a/openhands-sdk/openhands/sdk/observability/laminar.py b/openhands-sdk/openhands/sdk/observability/laminar.py index 727069bd46c..e0824840ff6 100644 --- a/openhands-sdk/openhands/sdk/observability/laminar.py +++ b/openhands-sdk/openhands/sdk/observability/laminar.py @@ -1,7 +1,8 @@ +import contextlib import functools import inspect import sys -from collections.abc import Callable +from collections.abc import Callable, Iterator from typing import TYPE_CHECKING, Any, Final, Literal from openhands.sdk.logger import get_logger @@ -9,7 +10,7 @@ if TYPE_CHECKING: - from opentelemetry import trace + pass logger = get_logger(__name__) @@ -168,11 +169,13 @@ def decorator(func: Callable[P, R]) -> Callable[P, R]: async def async_wrapper(*args: P.args, **fkwargs: P.kwargs) -> Any: nonlocal wrapped if wrapped is not None: - return await wrapped(*args, **fkwargs) + with _maybe_use_root_span(args): + return await wrapped(*args, **fkwargs) if not should_enable_observability(): return await func(*args, **fkwargs) wrapped = _build_wrapped(func) - return await wrapped(*args, **fkwargs) + with _maybe_use_root_span(args): + return await wrapped(*args, **fkwargs) return async_wrapper # type: ignore[return-value] @@ -180,11 +183,13 @@ async def async_wrapper(*args: P.args, **fkwargs: P.kwargs) -> Any: def sync_wrapper(*args: P.args, **fkwargs: P.kwargs) -> R: nonlocal wrapped if wrapped is not None: - return wrapped(*args, **fkwargs) + with _maybe_use_root_span(args): + return wrapped(*args, **fkwargs) if not should_enable_observability(): return func(*args, **fkwargs) wrapped = _build_wrapped(func) - return wrapped(*args, **fkwargs) + with _maybe_use_root_span(args): + return wrapped(*args, **fkwargs) return sync_wrapper @@ -220,55 +225,241 @@ def _is_otel_backend_laminar(): return key is not None and key != "" -class SpanManager: - """Manages a stack of active spans and their associated tokens.""" +_ROOT_SPAN_ATTR: Final[str] = "_observability_root_span" - def __init__(self): - self._stack: list[trace.Span] = [] - def start_active_span(self, name: str, session_id: str | None = None) -> None: - """Start a new active span and push it to the stack.""" +class RootSpan: + """A long-lived Laminar span owned by a single object (e.g. a Conversation). + + The span is created via ``Laminar.start_span`` (which does NOT attach the + span to the current OpenTelemetry context). To make the span the parent of + nested ``@observe``-decorated calls, the ``observe`` wrapper in this module + re-attaches the span via ``Laminar.use_span`` at every entry point. This + allows the root span to span across asyncio tasks, threads, and processes + where naive ``contextvars`` propagation breaks down. + + The ``Laminar.start_active_span`` API was previously used for this purpose + but its docstring explicitly warns: + + "ending the started span in a different async context yields + unexpected results. … Use Laminar.start_span + Laminar.use_span + where possible." + + Empirically, ``start_active_span`` produced trace-context loss for ~60% of + conversations (orphan ``conversation.send_message`` / ``conversation.run`` + traces with no ``session_id``), so we switched to the recommended pattern. + """ + + def __init__(self, name: str, session_id: str | None = None) -> None: from lmnr import Laminar - span = Laminar.start_active_span(name) + # ``start_span`` returns a span without attaching it as the current + # OTel context; we'll restore it on every entry point via ``use_span``. + self.span = Laminar.start_span(name) if session_id: - Laminar.set_trace_session_id(session_id) - self._stack.append(span) + # ``set_trace_session_id`` requires an active span; briefly enter + # the span context to apply the session id to the trace metadata. + with contextlib.suppress(Exception): + with Laminar.use_span(self.span): + Laminar.set_trace_session_id(session_id) + self._ended = False + + def end(self) -> None: + if self._ended: + return + self._ended = True + try: + if self.span and self.span.is_recording(): + self.span.end() + except Exception: + logger.debug("Error ending observability root span", exc_info=True) + + +def start_root_span(name: str, session_id: str | None = None) -> RootSpan | None: + """Create a long-lived root span for an owning object. + + Returns ``None`` if observability is not enabled. + """ + if not should_enable_observability(): + return None + try: + return RootSpan(name, session_id=session_id) + except Exception: + logger.debug("Failed to create observability root span", exc_info=True) + return None + + +def end_root_span(root: RootSpan | None) -> None: + """End a previously-started root span. Safe to call with ``None``.""" + if root is None: + return + root.end() + + +@contextlib.contextmanager +def _maybe_use_root_span(args: tuple[Any, ...]) -> Iterator[None]: + """If the first positional arg owns a ``RootSpan``, re-attach it. + + This is what ties ``@observe``-decorated methods (called from arbitrary + asyncio tasks or threads) back to the conversation's long-lived root span. + """ + root = _root_span_from_args(args) + if root is None or root.span is None: + yield + return + try: + from lmnr import Laminar + except Exception: + yield + return + try: + with Laminar.use_span(root.span): + yield + except Exception: + # Never let an observability error break the wrapped function. + logger.debug("use_span failed; calling without parent", exc_info=True) + yield + + +def _root_span_from_args(args: tuple[Any, ...]) -> RootSpan | None: + if not args: + return None + candidate = getattr(args[0], _ROOT_SPAN_ATTR, None) + if isinstance(candidate, RootSpan): + return candidate + return None + + +# --------------------------------------------------------------------------- +# Backwards-compat shims (deprecated). +# --------------------------------------------------------------------------- +# +# Deprecation schedule: deprecated in 1.22.0, scheduled for removal in 1.27.0. +# This matches the SDK's existing 5-minor-version grace window — see +# ``VerificationSettings.confirmation_mode`` (deprecated 1.17.0, removed +# 1.22.0). New code should use ``start_root_span`` / ``end_root_span`` (or +# ``BaseConversation._start_observability_span`` / +# ``_end_observability_span``). +# +# An audit on 2026-05-07 found no callers of these symbols outside the SDK +# itself: 0 hits in OpenHands/OpenHands, 0 in OpenHands/agent-canvas, 0 in +# OpenHands/codescout (only ``maybe_init_laminar`` is used), and 0 elsewhere +# in the OpenHands org via GitHub code search. The shims are kept solely to +# protect any unaudited private/external consumer; they emit a +# ``DeprecationWarning`` so any straggler is alerted before removal. + + +class SpanManager: + """Deprecated single-stack span manager. + + .. deprecated:: 1.22.0 + Will be removed in 1.27.0. The SDK no longer relies on a global stack: + each ``BaseConversation`` owns its own ``RootSpan``, which avoids + cross-conversation collisions when multiple conversations are alive + concurrently. Use ``start_root_span`` / ``end_root_span`` (or + ``BaseConversation._start_observability_span`` / + ``_end_observability_span``) instead. + """ + + def __init__(self) -> None: + self._stack: list[RootSpan] = [] + + def start_active_span(self, name: str, session_id: str | None = None) -> None: + # Literal version strings are required by .github/scripts/check_deprecations.py + from openhands.sdk.utils.deprecation import warn_deprecated + + warn_deprecated( + "SpanManager.start_active_span", + deprecated_in="1.22.0", + removed_in="1.27.0", + details=( + "Use openhands.sdk.observability.laminar.start_root_span and " + "store the returned RootSpan on the owning object." + ), + ) + root = start_root_span(name, session_id=session_id) + if root is not None: + self._stack.append(root) def end_active_span(self) -> None: - """End the most recent active span by popping it from the stack.""" - if not self._stack: - logger.warning("Attempted to end active span, but stack is empty") - return + from openhands.sdk.utils.deprecation import warn_deprecated - try: - span = self._stack.pop() - if span and span.is_recording(): - span.end() - except IndexError: + warn_deprecated( + "SpanManager.end_active_span", + deprecated_in="1.22.0", + removed_in="1.27.0", + details="Use openhands.sdk.observability.laminar.end_root_span.", + ) + if not self._stack: logger.warning("Attempted to end active span, but stack is empty") return + end_root_span(self._stack.pop()) _span_manager: SpanManager | None = None def _get_span_manager() -> SpanManager: + """Internal accessor for the deprecated module-level SpanManager. + + Bypasses ``SpanManager.__init__`` so wiring up the legacy shims doesn't + itself trigger a deprecation warning. + """ global _span_manager if _span_manager is None: - _span_manager = SpanManager() + _span_manager = SpanManager.__new__(SpanManager) + _span_manager._stack = [] return _span_manager def start_active_span(name: str, session_id: str | None = None) -> None: - """Start a new active span using the global span manager.""" - _get_span_manager().start_active_span(name, session_id) + """Deprecated: use ``start_root_span`` with a per-conversation owner. + + .. deprecated:: 1.22.0 + Will be removed in 1.27.0. + """ + from openhands.sdk.utils.deprecation import warn_deprecated + + warn_deprecated( + "openhands.sdk.observability.laminar.start_active_span", + deprecated_in="1.22.0", + removed_in="1.27.0", + details=( + "Use openhands.sdk.observability.laminar.start_root_span and " + "store the returned RootSpan on the owning object (e.g. a " + "Conversation). The @observe decorator will then re-attach the " + "span as the parent of nested calls automatically. The previous " + "global LIFO stack could not safely support multiple concurrent " + "conversations." + ), + ) + # Inline the work to avoid triggering SpanManager's own deprecation warning. + mgr = _get_span_manager() + root = start_root_span(name, session_id=session_id) + if root is not None: + mgr._stack.append(root) def end_active_span() -> None: - """End the most recent active span using the global span manager.""" + """Deprecated: paired with the deprecated ``start_active_span``. + + .. deprecated:: 1.22.0 + Will be removed in 1.27.0. + """ + from openhands.sdk.utils.deprecation import warn_deprecated + + warn_deprecated( + "openhands.sdk.observability.laminar.end_active_span", + deprecated_in="1.22.0", + removed_in="1.27.0", + details="Use openhands.sdk.observability.laminar.end_root_span.", + ) try: - _get_span_manager().end_active_span() + mgr = _get_span_manager() + if not mgr._stack: + logger.warning("Attempted to end active span, but stack is empty") + return + end_root_span(mgr._stack.pop()) except Exception: logger.debug("Error ending active span") pass diff --git a/tests/sdk/conversation/test_base_span_management.py b/tests/sdk/conversation/test_base_span_management.py index f54ee101b34..e70e13d7c80 100644 --- a/tests/sdk/conversation/test_base_span_management.py +++ b/tests/sdk/conversation/test_base_span_management.py @@ -83,11 +83,13 @@ def test_base_conversation_span_management(): patch( "openhands.sdk.conversation.base.should_enable_observability" ) as mock_should_enable, - patch("openhands.sdk.conversation.base.start_active_span") as mock_start_span, - patch("openhands.sdk.conversation.base.end_active_span") as mock_end_span, + patch("openhands.sdk.conversation.base.start_root_span") as mock_start_span, + patch("openhands.sdk.conversation.base.end_root_span") as mock_end_span, ): # Test when observability is enabled mock_should_enable.return_value = True + fake_root = MagicMock(name="root-span") + mock_start_span.return_value = fake_root # Start span conversation._start_observability_span("test-session-id") @@ -95,13 +97,20 @@ def test_base_conversation_span_management(): "conversation", session_id="test-session-id" ) assert conversation._span_ended is False + assert conversation._observability_root_span is fake_root + + # Calling start again is idempotent (already-started conversations + # must not produce a second root span). + conversation._start_observability_span("test-session-id") + assert mock_start_span.call_count == 1 # End span first time conversation._end_observability_span() - mock_end_span.assert_called_once() + mock_end_span.assert_called_once_with(fake_root) assert conversation._span_ended is True + assert conversation._observability_root_span is None - # Try to end span again - should not call end_active_span again + # Try to end span again - should not call end_root_span again conversation._end_observability_span() assert mock_end_span.call_count == 1 # Still only called once assert conversation._span_ended is True @@ -117,21 +126,23 @@ def test_base_conversation_span_management_disabled(): patch( "openhands.sdk.conversation.base.should_enable_observability" ) as mock_should_enable, - patch("openhands.sdk.conversation.base.start_active_span") as mock_start_span, - patch("openhands.sdk.conversation.base.end_active_span") as mock_end_span, + patch("openhands.sdk.conversation.base.start_root_span") as mock_start_span, + patch("openhands.sdk.conversation.base.end_root_span") as mock_end_span, ): # Test when observability is disabled mock_should_enable.return_value = False - # Try to start span - should not call start_active_span + # Try to start span - should not call start_root_span conversation._start_observability_span("test-session-id") mock_start_span.assert_not_called() assert conversation._span_ended is False + assert conversation._observability_root_span is None - # Try to end span - should not call end_active_span + # End is always called (it's a no-op for None) and marks ended. + # The important property is that no observability call is made when + # observability is disabled. conversation._end_observability_span() - mock_end_span.assert_not_called() - assert conversation._span_ended is False + mock_end_span.assert_called_once_with(None) def test_base_conversation_no_span_warnings(caplog): @@ -145,8 +156,8 @@ def test_base_conversation_no_span_warnings(caplog): "openhands.sdk.conversation.base.should_enable_observability", return_value=True, ), - patch("openhands.sdk.conversation.base.start_active_span"), - patch("openhands.sdk.conversation.base.end_active_span"), + patch("openhands.sdk.conversation.base.start_root_span"), + patch("openhands.sdk.conversation.base.end_root_span"), ): # Capture logs at WARNING level with caplog.at_level(logging.WARNING): diff --git a/tests/sdk/observability/test_laminar.py b/tests/sdk/observability/test_laminar.py index 36b2aacb6c9..c415fcfa805 100644 --- a/tests/sdk/observability/test_laminar.py +++ b/tests/sdk/observability/test_laminar.py @@ -1,5 +1,7 @@ """Tests for Laminar observability configuration.""" +import asyncio +import contextvars import inspect import os from unittest.mock import MagicMock, patch @@ -236,3 +238,199 @@ def test_lmnr_force_http_passed_to_laminar(force_http_value, expected_force_http os.environ["LMNR_FORCE_HTTP"] = original_force_http elif "LMNR_FORCE_HTTP" in os.environ: del os.environ["LMNR_FORCE_HTTP"] + + +# --------------------------------------------------------------------------- +# Cross-context root-span propagation +# --------------------------------------------------------------------------- +# +# Regression tests for the orphan-trace bug where ``@observe``-decorated +# methods on a Conversation, when called from a different asyncio task or +# thread than the one that constructed the Conversation, started a fresh +# trace instead of attaching to the conversation's root span. The fix moves +# from ``Laminar.start_active_span`` (which relies on contextvars +# propagation) to ``Laminar.start_span`` + ``Laminar.use_span`` re-attached +# at every entry point. + + +class _DummyOwner: + """Mimics a ``BaseConversation`` for the purposes of the observe wrapper.""" + + def __init__(self, root_span): + from openhands.sdk.observability.laminar import RootSpan + + # Build a RootSpan-like object without invoking real lmnr. + self._observability_root_span = RootSpan.__new__(RootSpan) + self._observability_root_span.span = root_span + self._observability_root_span._ended = False + + +def test_observe_calls_use_span_with_owner_root_span_on_sync(): + """Sync ``@observe``'d methods must re-attach the owner's root span.""" + os.environ["LMNR_PROJECT_API_KEY"] = "test-key" + try: + from lmnr import Laminar # noqa: F401 ensure module is importable + + from openhands.sdk.observability import laminar as lam + + sentinel_span = MagicMock(name="root-span") + used_with: list = [] + + @contextlib_compat() + def fake_use_span(span, *args, **kwargs): + used_with.append(span) + yield span + + with patch.object(Laminar, "use_span", side_effect=fake_use_span): + # Force-enable observability for the duration of this call. + lam._observability_enabled = True + # Stub the lmnr-level ``observe`` so the wrapper just calls through. + with patch("lmnr.observe", lambda **kw: (lambda f: f)): + + @lam.observe(name="conversation.send_message") + def send_message(self, msg: str) -> str: + return f"got {msg}" + + owner = _DummyOwner(sentinel_span) + assert send_message(owner, "hi") == "got hi" + + assert used_with == [sentinel_span], ( + f"expected use_span to be called once with owner's root span, " + f"got {used_with!r}" + ) + finally: + os.environ.pop("LMNR_PROJECT_API_KEY", None) + + +def test_observe_calls_use_span_with_owner_root_span_on_async(): + """Async ``@observe``'d methods must re-attach the owner's root span.""" + os.environ["LMNR_PROJECT_API_KEY"] = "test-key" + try: + from lmnr import Laminar + + from openhands.sdk.observability import laminar as lam + + sentinel_span = MagicMock(name="root-span") + used_with: list = [] + + @contextlib_compat() + def fake_use_span(span, *args, **kwargs): + used_with.append(span) + yield span + + with patch.object(Laminar, "use_span", side_effect=fake_use_span): + lam._observability_enabled = True + with patch("lmnr.observe", lambda **kw: (lambda f: f)): + + @lam.observe(name="conversation.run") + async def run(self) -> str: + return "done" + + owner = _DummyOwner(sentinel_span) + # Run from a fresh, empty contextvars Context to mimic a + # task created outside the conversation's async ancestry. + + async def _call_in_isolated_context(): + new_ctx = contextvars.Context() + return await asyncio.tasks.Task(run(owner), context=new_ctx) + + result = asyncio.run(_call_in_isolated_context()) + assert result == "done" + + assert used_with == [sentinel_span], ( + f"expected use_span to be called once even from an isolated " + f"context, got {used_with!r}" + ) + finally: + os.environ.pop("LMNR_PROJECT_API_KEY", None) + + +def test_two_concurrent_conversations_do_not_collide(): + """Each conversation must own its own root span (no global stack). + + Before the fix, a process-wide ``SpanManager`` LIFO stack meant a second + conversation constructed while the first was alive would corrupt the + first's root span on close. + """ + from openhands.sdk.conversation.base import BaseConversation + + # Bypass ABC instantiation by calling ``BaseConversation.__init__`` on a + # bare ``object``-like instance. We only exercise the span-management + # methods, which are concrete on the base class. + class _BareConvo: + pass + + c1 = _BareConvo() + c2 = _BareConvo() + BaseConversation.__init__(c1) # type: ignore[arg-type] + BaseConversation.__init__(c2) # type: ignore[arg-type] + + # Patch the symbol in the module where it's looked up at call time, and + # force observability on so the shortcut early-return doesn't fire. + from openhands.sdk.conversation import base as base_mod + + with ( + patch.object(base_mod, "should_enable_observability", return_value=True), + patch.object( + base_mod, + "start_root_span", + side_effect=lambda *a, **k: MagicMock(spec_set=["end"]), + ) as mock_start, + ): + BaseConversation._start_observability_span(c1, "session-1") # type: ignore[arg-type] + BaseConversation._start_observability_span(c2, "session-2") # type: ignore[arg-type] + + # Each conversation has its own root span – no shared stack. + assert c1._observability_root_span is not c2._observability_root_span # type: ignore[attr-defined] + + # Closing c2 must NOT end c1's root span. + c2_root = c2._observability_root_span # type: ignore[attr-defined] + c1_root = c1._observability_root_span # type: ignore[attr-defined] + BaseConversation._end_observability_span(c2) # type: ignore[arg-type] + c2_root.end.assert_called_once() + c1_root.end.assert_not_called() + + # And vice versa. + BaseConversation._end_observability_span(c1) # type: ignore[arg-type] + c1_root.end.assert_called_once() + + assert mock_start.call_count == 2 + + +# Tiny shim because we want a generator-based context manager helper that +# also works as a side_effect for patch(). +def contextlib_compat(): + import contextlib + + return contextlib.contextmanager + + +def test_deprecated_shims_emit_warnings(): + """The legacy global-stack API must emit DeprecationWarning so external + callers (none found in the org-wide audit, but still) are alerted before + the 1.27.0 removal. + + We patch ``_current_version`` to ``1.22.0`` because the helper only emits + warnings once the running SDK has reached the ``deprecated_in`` version + (so during 1.21.x development the warnings are silent; they activate the + moment 1.22.0 ships). + """ + from openhands.sdk.observability import laminar as lam + + # Force observability off so the shim's start_root_span returns None and + # we don't reach into a real Laminar SDK. + with ( + patch.object(lam, "should_enable_observability", return_value=False), + patch( + "openhands.sdk.utils.deprecation._current_version", + return_value="1.22.0", + ), + ): + with pytest.warns(DeprecationWarning, match="start_active_span"): + lam.start_active_span("conversation", session_id="sid") + with pytest.warns(DeprecationWarning, match="end_active_span"): + lam.end_active_span() + with pytest.warns(DeprecationWarning, match="SpanManager.start_active_span"): + lam.SpanManager().start_active_span("conversation") + with pytest.warns(DeprecationWarning, match="SpanManager.end_active_span"): + lam.SpanManager().end_active_span()