-
Notifications
You must be signed in to change notification settings - Fork 567
Description
(full disclosure; ticket was created by @claude Code, thought I have personally verified the reproduction code. Using the AsyncioIntegration and OpenAIAgentsIntegration in unison generates at least the transaction error)
Bug Description
AttributeError: 'Transaction/Profile/Span' object has no attribute '_context_manager_state' occurs when using OpenAIAgentsIntegration with AsyncioIntegration when exceptions occur during agent execution.
Critical Finding: The error only occurs when AsyncioIntegration is enabled. Commenting it out prevents the error entirely, suggesting an interaction issue between these two integrations.
Environment
- sentry-sdk: 2.37.0 (latest)
- openai-agents: 0.2.8
- Python: 3.11
- Integrations:
AsyncioIntegration()+OpenAIAgentsIntegration()
Error Messages
When both integrations are enabled and an exception occurs during agent execution:
Error 1: Profile
[sentry] ERROR: Internal error in sentry_sdk
Traceback (most recent call last):
File "sentry_sdk/profiler/transaction_profiler.py", line 376, in __exit__
scope, old_profile = self._context_manager_state
^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Profile' object has no attribute '_context_manager_state'
Error 2: Transaction
[sentry] ERROR: Internal error in sentry_sdk
Traceback (most recent call last):
File "sentry_sdk/tracing.py", line 423, in __exit__
scope, old_span = self._context_manager_state
^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Transaction' object has no attribute '_context_manager_state'
Error 3: Span (production)
[sentry] ERROR: Internal error in sentry_sdk
Traceback (most recent call last):
File "sentry_sdk/tracing.py", line 415, in __exit__
scope, old_span = self._context_manager_state
^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Span' object has no attribute '_context_manager_state'
Root Cause
The issue appears to be in sentry_sdk/integrations/openai_agents/patches/runner.py at line 41:
def _create_run_wrapper(original_func):
@wraps(original_func)
async def wrapper(*args, **kwargs):
with sentry_sdk.isolation_scope():
agent = args[0]
with agent_workflow_span(agent):
result = None
try:
result = await original_func(*args, **kwargs)
return result
except Exception as exc:
_capture_exception(exc)
# BUG HERE - Line 41
current_span = sentry_sdk.get_current_span()
if current_span is not None and current_span.timestamp is None:
current_span.__exit__(None, None, None) # ❌ Wrong!
raise exc from None
return wrapperThe code calls __exit__ directly on a span without ensuring it was used as a context manager. The _context_manager_state attribute is only set by __enter__ (see tracing.py:414).
However, this error only manifests when AsyncioIntegration is also enabled. When AsyncioIntegration is commented out, the error does not occur, suggesting the two integrations have problematic interaction in async contexts.
Minimal Reproduction
#!/usr/bin/env python
import asyncio
import os
import sys
import sentry_sdk
from agents import Agent, Runner
from sentry_sdk.integrations.asyncio import AsyncioIntegration
from sentry_sdk.integrations.openai_agents import OpenAIAgentsIntegration
from agents.tool import function_tool
async def main():
sentry_sdk.init(
dsn=os.getenv("SENTRY_DSN"),
environment="bug-reproduction",
enable_logs=True,
sample_rate=1.0,
traces_sample_rate=1.0,
debug=True,
integrations=[
AsyncioIntegration(), # ← Bug only occurs WITH this
OpenAIAgentsIntegration(),
],
)
@function_tool
async def broken_tool() -> str:
"""A tool that always fails."""
raise RuntimeError("Intentional error to trigger bug")
agent = Agent(
name="Bug Reproduction Agent",
instructions="You are a test agent. Always use the broken_tool.",
tools=[broken_tool],
model="gpt-4o-mini",
)
result = await Runner.run(
starting_agent=agent,
input="Please use the broken_tool",
max_turns=3,
)
print(f"[RESULT] {result.final_output}")
if __name__ == "__main__":
asyncio.run(main())Reproduction Steps
- Install dependencies:
pip install sentry-sdk openai-agents - Set
SENTRY_DSNandOPENAI_API_KEYenvironment variables - Run the script above
- Observe the
AttributeErrorin debug output - Comment out
AsyncioIntegration()and re-run - error disappears
Impact
Severity: HIGH
- ✅ Confirmed in production - Multiple users experiencing this
- ❌ AI calls not logged in Sentry - Telemetry data is lost
- ❌ Silent failures - Errors swallowed by
capture_internal_exceptions() - ❌ Affects all async agent workflows that encounter errors
This makes the OpenAIAgentsIntegration unusable in production when combined with AsyncioIntegration, which is commonly needed for async Python applications.
Workaround
Temporarily disable AsyncioIntegration:
sentry_sdk.init(
dsn=SENTRY_DSN,
integrations=[
# AsyncioIntegration(), # ← Comment out to avoid bug
OpenAIAgentsIntegration(),
],
)However, this loses valuable async tracing capabilities.
Proposed Fix
The fix should address why AsyncioIntegration causes spans to be accessed without proper context manager initialization. Possible approaches:
-
Check for
_context_manager_statebefore calling__exit__:if hasattr(current_span, '_context_manager_state'): current_span.__exit__(None, None, None) else: current_span.finish()
-
Always use
finish()instead of__exit__:current_span.finish()
-
Investigate AsyncioIntegration interaction - Why does it cause spans to be in an invalid state?
Additional Notes
- The error is logged but swallowed, so it doesn't crash the application
- However, it prevents telemetry data from being sent to Sentry
- The bug is timing-sensitive and only occurs when exceptions happen during agent tool execution
- Production environments with error-prone tools will trigger this constantly
Metadata
Metadata
Assignees
Projects
Status