Skip to content

Fix Laminar span stack warning in LocalConversation - #1039

Merged
xingyaoww merged 2 commits into
mainfrom
openhands/fix-laminar-span-double-ending
Nov 5, 2025
Merged

xingyaoww merged 2 commits into
mainfrom
openhands/fix-laminar-span-double-ending

Conversation

@jpshackelford

@jpshackelford jpshackelford commented Nov 5, 2025 •

Copy link
Copy Markdown
Member

Summary

Fixes #1038: Prevents double-ending of tracing spans that caused "Attempted to end active span, but stack is empty" warnings during LocalConversation cleanup.

Problem

When running SDK examples (or any code using LocalConversation), warning messages appeared about attempting to end an active span when the stack is empty:

[11/05/25 06:52:13] WARNING  Attempted to end active span, but stack is empty (laminar.py:133)
[11/05/25 06:52:13] WARNING  Attempted to end active span, but stack is empty (laminar.py:133)

Root Cause

The issue was caused by double-ending of tracing spans in the LocalConversation lifecycle:

  1. Span is started in __init__ (line 152) when observability is enabled
  2. Span is ended in run()'s finally block (line 312)
  3. Span is ended again in close() (line 397)
  4. When __del__ calls close() during garbage collection, it tries to end an already-ended span

Solution

Added proper span state tracking to prevent double-ending:

  • Added _span_ended flag to track whether the span has already been ended
  • Check should_enable_observability() before attempting to end spans
  • Prevent double span ending in both run() and close() methods

Changes

Core Fix

  • openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py:
    • Added _span_ended: bool field to track span state
    • Initialize _span_ended = False in __init__
    • Check not self._span_ended and should_enable_observability() before calling end_active_span()
    • Set _span_ended = True after ending span

Tests

  • tests/sdk/conversation/local/test_span_double_ending.py:
    • Added comprehensive test suite to verify the fix
    • Tests both exception and successful run scenarios
    • Verifies no span warnings are produced

Testing

  • ✅ All existing tests continue to pass (65/65)
  • ✅ New tests verify the fix works correctly
  • ✅ No more span warnings in SDK examples
  • ✅ Pre-commit hooks pass (formatting, linting, type checking)

Verification

Before fix:

cd examples/01_standalone_sdk
uv run python 01_hello_world.py
# Output: 2x "Attempted to end active span, but stack is empty" warnings

After fix:

cd examples/01_standalone_sdk  
uv run python 01_hello_world.py
# Output: No span warnings

Impact

  • Severity: Low (warning only, doesn't break functionality)
  • Affects: All examples and code using LocalConversation
  • Backward Compatibility: ✅ No breaking changes
  • Performance: ✅ Minimal overhead (single boolean flag)

@jpshackelford can click here to continue refining the PR


Agent Server images for this PR

• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server

Variants & Base Images

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python amd64, arm64 nikolaik/python-nodejs:python3.12-nodejs22 Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:b4f42ef-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-b4f42ef-python \
  ghcr.io/openhands/agent-server:b4f42ef-python

All tags pushed for this build

ghcr.io/openhands/agent-server:b4f42ef-golang-amd64
ghcr.io/openhands/agent-server:v1.0.0a5_golang_tag_1.21-bookworm_binary-amd64
ghcr.io/openhands/agent-server:b4f42ef-golang-arm64
ghcr.io/openhands/agent-server:v1.0.0a5_golang_tag_1.21-bookworm_binary-arm64
ghcr.io/openhands/agent-server:b4f42ef-java-amd64
ghcr.io/openhands/agent-server:v1.0.0a5_eclipse-temurin_tag_17-jdk_binary-amd64
ghcr.io/openhands/agent-server:b4f42ef-java-arm64
ghcr.io/openhands/agent-server:v1.0.0a5_eclipse-temurin_tag_17-jdk_binary-arm64
ghcr.io/openhands/agent-server:b4f42ef-python-amd64
ghcr.io/openhands/agent-server:v1.0.0a5_nikolaik_s_python-nodejs_tag_python3.12-nodejs22_binary-amd64
ghcr.io/openhands/agent-server:b4f42ef-python-arm64
ghcr.io/openhands/agent-server:v1.0.0a5_nikolaik_s_python-nodejs_tag_python3.12-nodejs22_binary-arm64
ghcr.io/openhands/agent-server:b4f42ef-golang
ghcr.io/openhands/agent-server:b4f42ef-java
ghcr.io/openhands/agent-server:b4f42ef-python

About Multi-Architecture Support

  • Each variant tag (e.g., b4f42ef-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., b4f42ef-python-amd64) are also available if needed

Fixes #1038: Prevents double-ending of tracing spans that caused
'Attempted to end active span, but stack is empty' warnings.

The issue occurred because:
1. Span was started in __init__ when observability is enabled
2. Span was ended in run()'s finally block
3. Span was ended again in close() during cleanup/garbage collection

Changes:
- Added _span_ended flag to track span state
- Check should_enable_observability() before ending spans
- Prevent double span ending in both run() and close() methods

Tests:
- Added comprehensive test suite to verify fix
- All existing tests continue to pass
- No more span warnings in examples

Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

github-actions Bot commented Nov 5, 2025 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/conversation
   base.py64592%95, 100–101, 136, 147
openhands-sdk/openhands/sdk/conversation/impl
   local_conversation.py1754574%139–140, 165, 170, 182, 199, 207–209, 213–214, 266–267, 270, 277, 298–300, 302, 318, 320, 322, 326, 328–330, 332, 334, 340–341, 354–355, 357, 359, 363–366, 384, 392, 394–396, 414, 416
   remote_conversation.py35810371%54–60, 67–70, 99, 106, 114, 116–119, 129, 138, 142–143, 148–151, 186, 200, 217, 228, 237–238, 268, 285, 289–291, 310, 318, 330, 338–341, 344, 349–350, 355–359, 364–368, 373–376, 379, 383–384, 388, 392, 395, 463, 469, 471, 492, 509–510, 516, 526–528, 534, 567, 569, 571–572, 576–577, 586, 594, 599–601, 603, 606, 608–609, 626, 633, 639–640, 648–649, 655–656, 661–662
TOTAL11638536453% 

@jpshackelford

Copy link
Copy Markdown
Member Author

@OpenHands Does this issue exist in any other conversation type?

@openhands-ai

openhands-ai Bot commented Nov 5, 2025

Copy link
Copy Markdown

I'm on it! jpshackelford can track my progress at all-hands.dev

@openhands-ai

openhands-ai Bot commented Nov 5, 2025

Copy link
Copy Markdown

Summary

I investigated whether the Laminar span double-ending issue exists in other conversation types beyond LocalConversation.

Answer: Yes, RemoteConversation has the same issue.

Analysis Results

LocalConversation (Fixed in current PR):

  • ✅ Has _span_ended tracking to prevent double-ending
  • ✅ Checks not self._span_ended and should_enable_observability() before ending spans
  • ✅ Issue resolved

RemoteConversation (Still has the issue):

  • ❌ No span state tracking
  • ❌ Calls end_active_span() unconditionally in close()
  • ❌ __del__ calls close() during garbage collection → double span ending

The Problem Pattern in RemoteConversation

  1. Span started in __init__ (line 516-517)
  2. If close() called explicitly → ends span unconditionally (line 656)
  3. Later __del__ calls close() during garbage collection → tries to end already-ended span
  4. Results in "Attempted to end active span, but stack is empty" warnings

Recommendation

RemoteConversation should implement the same fix as LocalConversation:

  • Add _span_ended: bool field
  • Initialize to False in __init__
  • Check not self._span_ended and should_enable_observability() before calling end_active_span()
  • Set _span_ended = True after ending span

This would prevent the same span warnings when using RemoteConversation instances.

View full conversation

…all conversation types

- Moved span management logic from LocalConversation to BaseConversation
- Added _span_ended tracking and proper observability checks to base class
- Refactored LocalConversation to use base class span management methods
- Refactored RemoteConversation to use base class span management methods
- Eliminates code duplication and ensures consistent span handling
- Fixes span double-ending warnings in both Local and Remote conversations
- Added comprehensive test suite for BaseConversation span management
- All 229 conversation tests passing

Co-authored-by: openhands <openhands@all-hands.dev>

Copy link
Copy Markdown
Member Author

🔄 Improved Solution: Refactored to BaseConversation

After investigating @jpshackelford's question about whether this issue exists in other conversation types, I discovered that RemoteConversation had the same double-ending problem. This led to a much better solution.

🔍 What I Found

RemoteConversation also had the span double-ending issue:

  • It calls end_active_span() unconditionally in its close() method
  • Since __del__ calls close() during garbage collection, this causes the same "Attempted to end active span, but stack is empty" warnings
  • The issue would affect any code using RemoteConversation

🏗️ Better Architecture: Centralized Span Management

Instead of fixing each conversation type individually, I moved the span management logic to BaseConversation:

BaseConversation Changes:

class BaseConversation(ABC):
    def __init__(self):
        self._span_ended = False
        self._start_observability_span()
    
    def _start_observability_span(self):
        if should_enable_observability():
            start_active_span("conversation")
    
    def _end_observability_span(self):
        if not self._span_ended and should_enable_observability():
            end_active_span()
            self._span_ended = True

Conversation Implementations:

  • LocalConversation: Refactored to use self._end_observability_span() instead of direct span calls
  • RemoteConversation: Refactored to use self._end_observability_span() instead of direct span calls
  • Removed duplicate observability imports from both implementations

✅ Benefits of This Approach

  1. Eliminates Code Duplication: Span management logic is centralized in one place
  2. Consistent Behavior: All conversation types now handle spans identically
  3. Future-Proof: Any new conversation implementations automatically inherit correct span management
  4. Maintainable: Changes to span logic only need to be made in BaseConversation
  5. Comprehensive Fix: Addresses the issue in both Local and Remote conversations

🧪 Testing

  • ✅ All 229 conversation tests pass (Local + Remote + Base)
  • ✅ Added comprehensive BaseConversation span management tests
  • ✅ No span warnings in either conversation type
  • ✅ Pre-commit hooks pass (formatting, linting, type checking)

📊 Impact

Before: Only LocalConversation was fixed, RemoteConversation still had the issue
After: Both conversation types (and any future ones) are protected from span double-ending

This refactoring provides a much more robust and maintainable solution that addresses the root cause rather than just the symptoms. 🎯

@openhands-ai

openhands-ai Bot commented Nov 5, 2025

Copy link
Copy Markdown

Looks like there are a few issues preventing this PR from being merged!

  • GitHub Actions are failing:
    • Agent Server

If you'd like me to help, just leave a comment, like

@OpenHands please fix the failing actions on PR #1039 at branch `openhands/fix-laminar-span-double-ending`

Feel free to include any additional details that might help me get this PR into a better state.

You can manage your notification settings

"""

def __init__(self) -> None:
"""Initialize the base conversation with span tracking."""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if this works normally with pydantic validation and serialization/deserialization. It should? But I'm a little unsure about redefining __init__ when we rely on some init/restore magic. 😓

Maybe we could run all examples, including remote, to see all is good? I think we have a new workflow for that... WDYT?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@enyst Looks like tests came back clean.

@enyst

enyst commented Nov 5, 2025

Copy link
Copy Markdown
Member

@OpenHands Do a /codereview-roasted on this PR. Think deeply and follow execution paths, specially regarding conversation factory and agent-server conversation persistence.

When you are done, respond using some markdown, some bold, some headings, bulleted lists, because it's more readable.

@openhands-ai

openhands-ai Bot commented Nov 5, 2025

Copy link
Copy Markdown

I'm on it! enyst can track my progress at all-hands.dev

@enyst enyst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@openhands-ai

openhands-ai Bot commented Nov 5, 2025

Copy link
Copy Markdown

Summary of /codereview-roasted on PR #1039

What I did

  • Reviewed the diff against main and traced execution paths for:
    • Span lifecycle in BaseConversation, LocalConversation, and RemoteConversation
    • Conversation factory selection and parameters
    • Agent-server conversation persistence, event streaming, and cleanup
  • Built and ran tests locally to surface runtime behavior and warnings

Key Findings (high impact)

  • Span lifecycle inconsistency
    • LocalConversation ends the “conversation” span in run() (finally) and again in close() (now guarded). This means subsequent run() calls no longer sit under a conversation-level span. Remote ends only in close().
    • Recommendation: Treat the conversation-level span as the lifetime of the conversation—start in init, end only in close(). If you need per-run spans, nest them (keep the top-level span intact).
  • WebSocket resilience (Remote)
    • The WS loop stops permanently on websockets.exceptions.ConnectionClosed (normal server restarts), losing future events.
    • Recommendation: Retry on ConnectionClosed unless explicitly stopping; keep exponential backoff.
  • Secret handling in WS
    • API key is passed via query parameter. This can leak through logs/proxies.
    • Recommendation: Use extra_headers (e.g., X-Session-API-Key) in websockets.connect instead of query params.
  • Ownership boundary (Remote)
    • RemoteConversation.close() closes workspace.client, which is owned/cached by RemoteWorkspace. This can break other consumers of the same workspace.
    • Recommendation: Do not close the workspace’s httpx.Client in conversation.close(); let the workspace manage it.
  • Cleanup robustness (Local)
    • atexit cleanup triggers RuntimeError when accessing agent.tools_map if Agent wasn’t fully initialized; observed during test runs.
    • Recommendation: Make LocalConversation.close() defensive—guard tools_map access and never throw in atexit.
  • Remote state cache staleness
    • RemoteState._cached_state persists indefinitely unless refreshed by WS events; if WS drops, the cache can go stale silently.
    • Recommendation: Add a TTL or a force_refresh option for critical reads; invalidate on WS reconnect.

Additional Suggestions (lower impact)

  • Compose callbacks safely
    • One bad callback can stop the chain; wrap each cb in try/except and log.
  • Visualizer defaults
    • Local constructor default visualize=True; Remote constructor defaults to False (the factory passes through, so behavior is fine). Consider aligning or documenting the rationale to avoid confusion.
  • RemoteWorkspace URL style
    • Mix of absolute and relative URLs; standardize to reduce subtle bugs.
  • Logging cleanup
    • AgentBase has a duplicated/nested logger.info around filtering; remove duplication for clarity.

Test Signals Observed

  • While running tests, multiple “Exception ignored in atexit callback” errors in LocalConversation.close due to agent.tools_map RuntimeError (Agent not initialized). This reinforces the need to harden cleanup.
  • At least one test failure existed (unrelated to this PR’s changes), but this review focused on conversation lifecycle/factory/persistence paths.

Recommended Next Steps

  • Align span semantics: end conversation-level span only in close() (Local), nest run-level spans if desired.
  • WS: retry on ConnectionClosed; move session key to headers; avoid closing workspace client in conversation.close().
  • Local close(): guard tools_map access; ensure atexit is no-throw.
  • Add TTL/force_refresh to RemoteState cache.
  • Optional tests: WS reconnect behavior, no API key in WS URL, Local close() idempotency when agent init is incomplete.

If you want, I can implement these minimal, targeted changes on this branch.

View full conversation

@xingyaoww
xingyaoww merged commit e5a7efe into main Nov 5, 2025
@xingyaoww
xingyaoww deleted the openhands/fix-laminar-span-double-ending branch November 5, 2025 18:29
StressTestor pushed a commit to StressTestor/software-agent-sdk that referenced this pull request Jun 1, 2026
Co-authored-by: openhands <openhands@all-hands.dev>
simonrosenberg added a commit that referenced this pull request Jun 5, 2026
…6 scoping

Three honest annotations, no behavior change:

- LocalConversation seed: note it runs for *every* agent (regular and ACP),
  not just ACP — it covers callers that skip create_request() (canvas /
  TypeScript and the server-side agent_settings -> create_agent fold) and is
  idempotent with the create_request() lift.
- get_all_secrets_as_env_vars: state that it injects the whole registry and
  that least-privilege scoping is deferred to #1039 task 6.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Laminar Span Stack Warning: Double-ending spans in LocalConversation

4 participants