From bb785d7b9036e6c684116abe559c25ac011529cb Mon Sep 17 00:00:00 2001 From: openhands Date: Thu, 7 May 2026 21:31:27 +0000 Subject: [PATCH 1/5] Fix orphaned Laminar traces from cross-async-context conversations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Production traces show ~63% of conversations end up split across multiple top-level Laminar traces: 327/520 traces in a 24h sample have top_span_name in {conversation.send_message, conversation.run, litellm.completion} with parent_span_id=00000000…, and 100% of those orphans have empty session_id. Root cause: the SDK starts the conversation root span via Laminar.start_active_span in BaseConversation.__init__ and stores it in a process-global SpanManager LIFO stack. start_active_span attaches the OTel context using contextvars, which only propagates to tasks created *after* the attach, on the *same* thread. When send_message / run / generate_title are invoked from a different asyncio task or thread (e.g. FastAPI handlers, websocket loops, RemoteConversation callers), the @observe-decorated method does not see the conversation as its parent and starts a fresh root trace. The Laminar SDK explicitly warns against this pattern and recommends start_span + use_span instead. A second, related bug: the global LIFO SpanManager corrupts state when multiple Conversations are alive concurrently — closing one pops whichever span happens to be on top. Fix: - Replace the global SpanManager with a per-conversation RootSpan owned by BaseConversation as self._observability_root_span. - Create the root via Laminar.start_span (no implicit context attach). - Have the @observe wrapper inspect the first positional arg for an _observability_root_span attribute and re-attach it via Laminar.use_span at every entry point. Nested @observe and lmnr auto-instrumented spans automatically inherit the right parent. - Apply session_id by briefly entering use_span at construction time so it lands on the trace metadata. - Keep SpanManager / start_active_span / end_active_span as deprecated shims for backwards compatibility. Add three regression tests: - sync entry points re-attach the owner's root span; - async entry points re-attach the owner's root span even when invoked from a freshly-created asyncio.Task with an empty contextvars.Context; - two concurrent conversations get independent root spans and ending one does not affect the other. Co-authored-by: openhands --- .../openhands/sdk/conversation/base.py | 34 +++- .../openhands/sdk/observability/laminar.py | 157 ++++++++++++++--- tests/sdk/observability/test_laminar.py | 165 ++++++++++++++++++ 3 files changed, 322 insertions(+), 34 deletions(-) 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..829888ce830 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 @@ -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,34 +225,136 @@ 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-compatible shims. New code should use ``start_root_span`` / +# ``end_root_span`` (or ``BaseConversation._start_observability_span`` / +# ``_end_observability_span``) instead. +class SpanManager: + """Deprecated single-stack span manager. + + Retained for any external code that may have imported it. Internally 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. + """ + + def __init__(self) -> None: + self._stack: list[RootSpan] = [] + + def start_active_span(self, name: str, session_id: str | None = None) -> None: + 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 - - try: - span = self._stack.pop() - if span and span.is_recording(): - span.end() - except IndexError: - logger.warning("Attempted to end active span, but stack is empty") - return + end_root_span(self._stack.pop()) _span_manager: SpanManager | None = None @@ -261,12 +368,12 @@ def _get_span_manager() -> SpanManager: def start_active_span(name: str, session_id: str | None = None) -> None: - """Start a new active span using the global span manager.""" + """Deprecated: use ``start_root_span`` with a per-conversation owner.""" _get_span_manager().start_active_span(name, session_id) def end_active_span() -> None: - """End the most recent active span using the global span manager.""" + """Deprecated: paired with the deprecated ``start_active_span``.""" try: _get_span_manager().end_active_span() except Exception: diff --git a/tests/sdk/observability/test_laminar.py b/tests/sdk/observability/test_laminar.py index 36b2aacb6c9..7dc4998a855 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,166 @@ 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 openhands.sdk.observability import laminar as lam + + from lmnr import Laminar # noqa: F401 ensure module is importable + + 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 openhands.sdk.observability import laminar as lam + + from lmnr import Laminar + + 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 From a76818dc5e2f53f2d48bc0aeb7a78f8dd687878c Mon Sep 17 00:00:00 2001 From: openhands Date: Thu, 7 May 2026 21:47:06 +0000 Subject: [PATCH 2/5] Update test_base_span_management to new RootSpan API The previous tests patched start_active_span / end_active_span on the base module; those names are still exported (as deprecated shims) but BaseConversation now calls start_root_span / end_root_span. Update the patches and assertions to target the new function names, and add an idempotency assertion: a second _start_observability_span on an already-started conversation must not start a second root span. Co-authored-by: openhands --- .../conversation/test_base_span_management.py | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) 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): From 9bc926ad1c01bbac090772d2e227cf7c05487835 Mon Sep 17 00:00:00 2001 From: openhands Date: Thu, 7 May 2026 21:51:51 +0000 Subject: [PATCH 3/5] Apply pre-commit auto-fixes (ruff format + lint) - Drop now-unused TYPE_CHECKING import of opentelemetry.trace from observability/laminar.py (referenced only by the old SpanManager). - Reorder imports in the new regression tests to satisfy ruff isort. Co-authored-by: openhands --- .../openhands/sdk/observability/laminar.py | 2 +- tests/sdk/observability/test_laminar.py | 22 ++++++++++--------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/openhands-sdk/openhands/sdk/observability/laminar.py b/openhands-sdk/openhands/sdk/observability/laminar.py index 829888ce830..c9b3b870b75 100644 --- a/openhands-sdk/openhands/sdk/observability/laminar.py +++ b/openhands-sdk/openhands/sdk/observability/laminar.py @@ -10,7 +10,7 @@ if TYPE_CHECKING: - from opentelemetry import trace + pass logger = get_logger(__name__) diff --git a/tests/sdk/observability/test_laminar.py b/tests/sdk/observability/test_laminar.py index 7dc4998a855..983c16bbcc2 100644 --- a/tests/sdk/observability/test_laminar.py +++ b/tests/sdk/observability/test_laminar.py @@ -269,10 +269,10 @@ 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 openhands.sdk.observability import laminar as lam - 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 = [] @@ -306,10 +306,10 @@ 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 openhands.sdk.observability import laminar as lam - from lmnr import Laminar + from openhands.sdk.observability import laminar as lam + sentinel_span = MagicMock(name="root-span") used_with: list = [] @@ -369,12 +369,14 @@ class _BareConvo: # 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: + 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] From e37ace5e4a757fc001d7ed8a82b924312f45f04a Mon Sep 17 00:00:00 2001 From: openhands Date: Thu, 7 May 2026 22:20:40 +0000 Subject: [PATCH 4/5] Add formal deprecation schedule for legacy SpanManager / *_active_span shims Audit on 2026-05-07 found *zero* callers of these symbols outside the SDK itself: - 0 hits in OpenHands/OpenHands (grep + GitHub code search) - 0 hits in OpenHands/agent-canvas (TypeScript-only) - 0 hits in OpenHands/codescout (only ``maybe_init_laminar`` is imported) - 0 hits elsewhere in the OpenHands org via GitHub code search The shims are kept solely to protect any unaudited private/external consumer. To make the schedule explicit, every shim now calls ``warn_deprecated`` with: deprecated_in="1.22.0" # this PR ships in 1.22.0 removed_in="1.27.0" # 5-minor-version grace window matches the # SDK's existing precedent for # VerificationSettings.confirmation_mode # (deprecated 1.17.0, removed 1.22.0) The warning is silent during 1.21.x development and activates the moment 1.22.0 ships. ``_get_span_manager`` was tweaked to construct the legacy ``SpanManager`` via ``__new__`` so wiring up the singleton doesn't itself emit a deprecation warning. Adds ``test_deprecated_shims_emit_warnings`` which patches ``_current_version`` to 1.22.0 and asserts each shim emits the expected ``DeprecationWarning``. Co-authored-by: openhands --- .../openhands/sdk/observability/laminar.py | 110 ++++++++++++++++-- tests/sdk/observability/test_laminar.py | 31 +++++ 2 files changed, 129 insertions(+), 12 deletions(-) diff --git a/openhands-sdk/openhands/sdk/observability/laminar.py b/openhands-sdk/openhands/sdk/observability/laminar.py index c9b3b870b75..c5ca821cdea 100644 --- a/openhands-sdk/openhands/sdk/observability/laminar.py +++ b/openhands-sdk/openhands/sdk/observability/laminar.py @@ -330,27 +330,68 @@ def _root_span_from_args(args: tuple[Any, ...]) -> RootSpan | None: return None -# Backwards-compatible shims. New code should use ``start_root_span`` / -# ``end_root_span`` (or ``BaseConversation._start_observability_span`` / -# ``_end_observability_span``) instead. +# --------------------------------------------------------------------------- +# 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. + +_DEPRECATED_IN: Final[str] = "1.22.0" +_REMOVED_IN: Final[str] = "1.27.0" + + class SpanManager: """Deprecated single-stack span manager. - Retained for any external code that may have imported it. Internally 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. + .. 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: + from openhands.sdk.utils.deprecation import warn_deprecated + + warn_deprecated( + "SpanManager.start_active_span", + deprecated_in=_DEPRECATED_IN, + removed_in=_REMOVED_IN, + 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: + from openhands.sdk.utils.deprecation import warn_deprecated + + warn_deprecated( + "SpanManager.end_active_span", + deprecated_in=_DEPRECATED_IN, + removed_in=_REMOVED_IN, + 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 @@ -361,21 +402,66 @@ def end_active_span(self) -> 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: - """Deprecated: use ``start_root_span`` with a per-conversation owner.""" - _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=_DEPRECATED_IN, + removed_in=_REMOVED_IN, + 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: - """Deprecated: paired with the deprecated ``start_active_span``.""" + """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=_DEPRECATED_IN, + removed_in=_REMOVED_IN, + 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/observability/test_laminar.py b/tests/sdk/observability/test_laminar.py index 983c16bbcc2..c415fcfa805 100644 --- a/tests/sdk/observability/test_laminar.py +++ b/tests/sdk/observability/test_laminar.py @@ -403,3 +403,34 @@ 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() From 1253592500aa55cb181271a734bb2443fffa04bd Mon Sep 17 00:00:00 2001 From: openhands Date: Thu, 7 May 2026 22:24:30 +0000 Subject: [PATCH 5/5] Inline deprecated_in/removed_in literals for static check_deprecations.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The repo's .github/scripts/check_deprecations.py walks the AST and only accepts string literals (or date.today()) for deprecated_in / removed_in. The previous commit factored these out to module-level Final[str] constants which the scanner rejects as "Unsupported removed_in expression". Inline the literal strings to satisfy the scanner — the human-readable schedule comment at the top of the shim block still documents the policy. Co-authored-by: openhands --- .../openhands/sdk/observability/laminar.py | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/openhands-sdk/openhands/sdk/observability/laminar.py b/openhands-sdk/openhands/sdk/observability/laminar.py index c5ca821cdea..e0824840ff6 100644 --- a/openhands-sdk/openhands/sdk/observability/laminar.py +++ b/openhands-sdk/openhands/sdk/observability/laminar.py @@ -348,9 +348,6 @@ def _root_span_from_args(args: tuple[Any, ...]) -> RootSpan | None: # protect any unaudited private/external consumer; they emit a # ``DeprecationWarning`` so any straggler is alerted before removal. -_DEPRECATED_IN: Final[str] = "1.22.0" -_REMOVED_IN: Final[str] = "1.27.0" - class SpanManager: """Deprecated single-stack span manager. @@ -368,12 +365,13 @@ 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=_DEPRECATED_IN, - removed_in=_REMOVED_IN, + 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." @@ -388,8 +386,8 @@ def end_active_span(self) -> None: warn_deprecated( "SpanManager.end_active_span", - deprecated_in=_DEPRECATED_IN, - removed_in=_REMOVED_IN, + deprecated_in="1.22.0", + removed_in="1.27.0", details="Use openhands.sdk.observability.laminar.end_root_span.", ) if not self._stack: @@ -424,8 +422,8 @@ def start_active_span(name: str, session_id: str | None = None) -> None: warn_deprecated( "openhands.sdk.observability.laminar.start_active_span", - deprecated_in=_DEPRECATED_IN, - removed_in=_REMOVED_IN, + 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 " @@ -452,8 +450,8 @@ def end_active_span() -> None: warn_deprecated( "openhands.sdk.observability.laminar.end_active_span", - deprecated_in=_DEPRECATED_IN, - removed_in=_REMOVED_IN, + deprecated_in="1.22.0", + removed_in="1.27.0", details="Use openhands.sdk.observability.laminar.end_root_span.", ) try: