Title: BUG: in OpenAIAgentsIntegration + AsyncioIntegration: '_context_manager_state' not found · Issue #5067 · getsentry/sentry-python · GitHub
Open Graph Title: BUG: in OpenAIAgentsIntegration + AsyncioIntegration: '_context_manager_state' not found · Issue #5067 · getsentry/sentry-python
X Title: BUG: in OpenAIAgentsIntegration + AsyncioIntegration: '_context_manager_state' not found · Issue #5067 · getsentry/sentry-python
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 ...
Open Graph 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...
X 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...
Opengraph URL: https://github.com/getsentry/sentry-python/issues/5067
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"BUG: in OpenAIAgentsIntegration + AsyncioIntegration: '_context_manager_state' not found","articleBody":"(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)\n\n\n---\n\n\n## Bug Description\n\n`AttributeError: 'Transaction/Profile/Span' object has no attribute '_context_manager_state'` occurs when using `OpenAIAgentsIntegration` with `AsyncioIntegration` when exceptions occur during agent execution.\n\n**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.\n\n## Environment\n\n- **sentry-sdk**: 2.37.0 (latest)\n- **openai-agents**: 0.2.8\n- **Python**: 3.11\n- **Integrations**: `AsyncioIntegration()` + `OpenAIAgentsIntegration()`\n\n## Error Messages\n\nWhen both integrations are enabled and an exception occurs during agent execution:\n\n### Error 1: Profile\n```\n[sentry] ERROR: Internal error in sentry_sdk\nTraceback (most recent call last):\n File \"sentry_sdk/profiler/transaction_profiler.py\", line 376, in __exit__\n scope, old_profile = self._context_manager_state\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\nAttributeError: 'Profile' object has no attribute '_context_manager_state'\n```\n\n### Error 2: Transaction\n```\n[sentry] ERROR: Internal error in sentry_sdk\nTraceback (most recent call last):\n File \"sentry_sdk/tracing.py\", line 423, in __exit__\n scope, old_span = self._context_manager_state\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\nAttributeError: 'Transaction' object has no attribute '_context_manager_state'\n```\n\n### Error 3: Span (production)\n```\n[sentry] ERROR: Internal error in sentry_sdk\nTraceback (most recent call last):\n File \"sentry_sdk/tracing.py\", line 415, in __exit__\n scope, old_span = self._context_manager_state\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\nAttributeError: 'Span' object has no attribute '_context_manager_state'\n```\n\n## Root Cause\n\nThe issue appears to be in `sentry_sdk/integrations/openai_agents/patches/runner.py` at line 41:\n\n```python\ndef _create_run_wrapper(original_func):\n @wraps(original_func)\n async def wrapper(*args, **kwargs):\n with sentry_sdk.isolation_scope():\n agent = args[0]\n with agent_workflow_span(agent):\n result = None\n try:\n result = await original_func(*args, **kwargs)\n return result\n except Exception as exc:\n _capture_exception(exc)\n\n # BUG HERE - Line 41\n current_span = sentry_sdk.get_current_span()\n if current_span is not None and current_span.timestamp is None:\n current_span.__exit__(None, None, None) # ❌ Wrong!\n\n raise exc from None\n\n return wrapper\n```\n\nThe 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`).\n\n**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.\n\n## Minimal Reproduction\n\n```python\n#!/usr/bin/env python\nimport asyncio\nimport os\nimport sys\n\nimport sentry_sdk\nfrom agents import Agent, Runner\nfrom sentry_sdk.integrations.asyncio import AsyncioIntegration\nfrom sentry_sdk.integrations.openai_agents import OpenAIAgentsIntegration\nfrom agents.tool import function_tool\n\n\nasync def main():\n sentry_sdk.init(\n dsn=os.getenv(\"SENTRY_DSN\"),\n environment=\"bug-reproduction\",\n enable_logs=True,\n sample_rate=1.0,\n traces_sample_rate=1.0,\n debug=True,\n integrations=[\n AsyncioIntegration(), # ← Bug only occurs WITH this\n OpenAIAgentsIntegration(),\n ],\n )\n\n @function_tool\n async def broken_tool() -> str:\n \"\"\"A tool that always fails.\"\"\"\n raise RuntimeError(\"Intentional error to trigger bug\")\n\n agent = Agent(\n name=\"Bug Reproduction Agent\",\n instructions=\"You are a test agent. Always use the broken_tool.\",\n tools=[broken_tool],\n model=\"gpt-4o-mini\",\n )\n\n result = await Runner.run(\n starting_agent=agent,\n input=\"Please use the broken_tool\",\n max_turns=3,\n )\n print(f\"[RESULT] {result.final_output}\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n```\n\n### Reproduction Steps\n\n1. Install dependencies: `pip install sentry-sdk openai-agents`\n2. Set `SENTRY_DSN` and `OPENAI_API_KEY` environment variables\n3. Run the script above\n4. Observe the `AttributeError` in debug output\n5. Comment out `AsyncioIntegration()` and re-run - **error disappears**\n\n## Impact\n\n### Severity: HIGH\n\n- ✅ **Confirmed in production** - Multiple users experiencing this\n- ❌ **AI calls not logged in Sentry** - Telemetry data is lost\n- ❌ **Silent failures** - Errors swallowed by `capture_internal_exceptions()`\n- ❌ **Affects all async agent workflows** that encounter errors\n\nThis makes the `OpenAIAgentsIntegration` **unusable in production** when combined with `AsyncioIntegration`, which is commonly needed for async Python applications.\n\n## Workaround\n\nTemporarily disable `AsyncioIntegration`:\n\n```python\nsentry_sdk.init(\n dsn=SENTRY_DSN,\n integrations=[\n # AsyncioIntegration(), # ← Comment out to avoid bug\n OpenAIAgentsIntegration(),\n ],\n)\n```\n\nHowever, this loses valuable async tracing capabilities.\n\n## Proposed Fix\n\nThe fix should address why `AsyncioIntegration` causes spans to be accessed without proper context manager initialization. Possible approaches:\n\n1. **Check for `_context_manager_state` before calling `__exit__`**:\n ```python\n if hasattr(current_span, '_context_manager_state'):\n current_span.__exit__(None, None, None)\n else:\n current_span.finish()\n ```\n\n2. **Always use `finish()` instead of `__exit__`**:\n ```python\n current_span.finish()\n ```\n\n3. **Investigate AsyncioIntegration interaction** - Why does it cause spans to be in an invalid state?\n\n## Additional Notes\n\n- The error is logged but swallowed, so it doesn't crash the application\n- However, it **prevents telemetry data from being sent to Sentry**\n- The bug is timing-sensitive and only occurs when exceptions happen during agent tool execution\n- Production environments with error-prone tools will trigger this constantly\n","author":{"url":"https://github.com/Afstkla","@type":"Person","name":"Afstkla"},"datePublished":"2025-11-04T17:12:44Z","url":"https://github.com/getsentry/sentry-python/issues/5067"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:863a55a6-3c1a-d824-54aa-c4bbf17d0e15 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | CF16:BF84:5F0B12:7F0EB5:6B0092C7 |
| html-safe-nonce | 63bd167233c489e9582509839aa3ff768094d9c14830a0b5fe2babe8aec4ee32 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDRjE2OkJGODQ6NUYwQjEyOjdGMEVCNTo2QjAwOTJDNyIsInZpc2l0b3JfaWQiOiIzODkxMzI0NjM5MjI5NTQ3MjA3IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 74ab71e0bd5c312f424aae1cd549a0c4c578c900bb0bfbcf5879a54ab3f08a4a |
| hovercard-subject-tag | issue:3587498900 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/getsentry/sentry-python/5067/issue_layout |
| twitter:image | https://opengraph.githubassets.com/7d15b16598203d476c05d568b00934162a8d9e3a8997359f772e99b89a0c18f4/getsentry/sentry-python/issues/5067 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/7d15b16598203d476c05d568b00934162a8d9e3a8997359f772e99b89a0c18f4/getsentry/sentry-python/issues/5067 |
| og:image:alt | (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... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | Afstkla |
| hostname | github.com |
| expected-hostname | github.com |
| None | c710a5cb5c47be60abfe6e8410436d409906979dbed614ef09f29c60f5535b08 |
| turbo-cache-control | no-preview |
| go-import | github.com/getsentry/sentry-python git https://github.com/getsentry/sentry-python.git |
| octolytics-dimension-user_id | 1396951 |
| octolytics-dimension-user_login | getsentry |
| octolytics-dimension-repository_id | 137814779 |
| octolytics-dimension-repository_nwo | getsentry/sentry-python |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 137814779 |
| octolytics-dimension-repository_network_root_nwo | getsentry/sentry-python |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | be616a2a6ec1c609d6e002896dff5352d5c5f28b |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width