Skip to content

Conversation

@Ray0907
Copy link

@Ray0907 Ray0907 commented Jan 3, 2026

Summary

Fix ValueError crash when using concurrent Runner.run() calls with asyncio.gather().

Problem:
When multiple Runner.run() calls execute concurrently, the ContextVar.reset(token) operation can fail with:
ValueError: <Token ...> was created in a different Context
This forces users to disable tracing (tracing_disabled=True) as a workaround, losing all observability.

Solution:
Add defensive fallback mechanism:

  1. Store the previous trace/span value before setting a new one
  2. Catch ValueError when reset() fails due to context mismatch
  3. Fall back to set(prev_value) to restore the previous state
  4. Log a warning to inform users about the concurrent execution impact

Changes:

  • src/agents/tracing/scope.py: Add fallback handling in reset_current_span() and reset_current_trace()
  • src/agents/tracing/traces.py: Store _prev_trace in NoOpTrace and TraceImpl
  • src/agents/tracing/spans.py: Store _prev_span in NoOpSpan and SpanImpl

Test plan

  • All existing tracing tests pass (30 tests)
  • Verified type checking with mypy
  • The fix is defensive and backward compatible - normal execution path unchanged

Issue number

#2246

Checks

  • I've added new tests (if relevant)
  • I've added/updated the relevant documentation
  • I've run make lint and make format
  • I've made sure tests pass

…tion

  Add fallback for ValueError when resetting trace/span context in
  concurrent Runner.run() scenarios. Prevents crashes while preserving
  tracing functionality.
@seratch
Copy link
Member

seratch commented Jan 6, 2026

Thanks for sharing this idea! I think #2260 can resolve this in a stabler way, so we'll have the per-run config enhancement instead.

@seratch
Copy link
Member

seratch commented Jan 6, 2026

Closing this in favor of #2260; thanks again for taking the time to send this!

@seratch seratch closed this Jan 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants