Title: Using isolation scopes with multiple depths of generators causes Token was created in different Context error · Issue #4925 · getsentry/sentry-python · GitHub
Open Graph Title: Using isolation scopes with multiple depths of generators causes Token was created in different Context error · Issue #4925 · getsentry/sentry-python
X Title: Using isolation scopes with multiple depths of generators causes Token was created in different Context error · Issue #4925 · getsentry/sentry-python
Description: How do you use Sentry? Sentry Saas (sentry.io) Version 2.33.2 Steps to Reproduce #!/usr/bin/env python3 """ Minimal reproduction case for Sentry isolation_scope + async generator bug. Bug: Using sentry_sdk.isolation_scope() as a context ...
Open Graph Description: How do you use Sentry? Sentry Saas (sentry.io) Version 2.33.2 Steps to Reproduce #!/usr/bin/env python3 """ Minimal reproduction case for Sentry isolation_scope + async generator bug. Bug: Using se...
X Description: How do you use Sentry? Sentry Saas (sentry.io) Version 2.33.2 Steps to Reproduce #!/usr/bin/env python3 """ Minimal reproduction case for Sentry isolation_scope + async generator bug...
Opengraph URL: https://github.com/getsentry/sentry-python/issues/4925
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Using isolation scopes with multiple depths of generators causes Token was created in different Context error","articleBody":"### How do you use Sentry?\n\nSentry Saas (sentry.io)\n\n### Version\n\n2.33.2\n\n### Steps to Reproduce\n\n```python\n#!/usr/bin/env python3\n\"\"\"\nMinimal reproduction case for Sentry isolation_scope + async generator bug.\n\nBug: Using sentry_sdk.isolation_scope() as a context manager around an async\ngenerator that yields causes \"Token was created in a different Context\" error\nwhen the generator exits early (via break, exception, or garbage collection).\n\"\"\"\n\nimport asyncio\nimport sentry_sdk\nfrom sentry_sdk.integrations.asyncio import AsyncioIntegration\n\n\nasync def inner_generator():\n \"\"\"Simple async generator that yields values\"\"\"\n for i in range(3):\n print(f\" Inner generator yielding: {i}\")\n yield i\n\n\nasync def problematic_async_generator():\n \"\"\"\n This pattern causes the context error.\n The isolation_scope wraps yield statements in an async generator.\n \"\"\"\n with sentry_sdk.isolation_scope() as scope:\n scope.set_user({\"id\": \"test-user-123\"})\n scope.set_tag(\"example\", \"value\")\n\n async for value in inner_generator():\n # THIS YIELD INSIDE ISOLATION_SCOPE IS THE PROBLEM\n yield value\n\n\nasync def main():\n print(\"Reproducing Sentry isolation_scope + async generator bug\\n\")\n print(\"=\" * 60)\n\n # Initialize Sentry\n sentry_sdk.init(\n dsn=None, # No DSN needed to reproduce\n integrations=[AsyncioIntegration()],\n debug=True,\n )\n\n print(\"Test 1: Normal completion (works fine)\")\n print(\"-\" * 40)\n async for val in problematic_async_generator():\n print(f\"Received: {val}\")\n print(\"✅ No error when generator completes normally\\n\")\n\n print(\"Test 2: Early exit with break (causes error)\")\n print(\"-\" * 40)\n async for val in problematic_async_generator():\n print(f\"Received: {val}\")\n if val == 1:\n print(\"Breaking early...\")\n break # This causes the context error\n\n # Give time for error to appear in output\n await asyncio.sleep(0.1)\n print(\"\\n❌ Error appears above: 'Token was created in a different Context'\")\n\n print(\"\\n\" + \"=\" * 60)\n print(\"The error happens because:\")\n print(\"1. isolation_scope() saves the current context when entering\")\n print(\"2. The async generator suspends/resumes across context boundaries\")\n print(\"3. When exiting early, cleanup happens in a different context\")\n print(\"4. Python's contextvars raises ValueError\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n```\n\n### Expected Result\n\nNot to crash\n\n### Actual Result\n\n```\nTest 2: Early exit with break (causes error)\n----------------------------------------\n Inner generator yielding: 0\nReceived: 0\n Inner generator yielding: 1\nReceived: 1\nBreaking early...\nTask exception was never retrieved\nfuture: \u003cTask finished name='coroutine without __name__ (Sentry-wrapped)' coro=\u003cpatch_asyncio.\u003clocals>._sentry_task_factory.\u003clocals>._task_with_sentry_span_creation() done, defined at /Users/ntindle/Library/Caches/pypoetry/virtualenvs/autogpt-platform-backend-90-hPFvq-py3.12/lib/python3.12/site-packages/sentry_sdk/integrations/asyncio.py:42> exception=ValueError(\"\u003cToken var=\u003cContextVar name='current_scope' default=None at 0x1033a7790> at 0x109af7300> was created in a different Context\")>\nTraceback (most recent call last):\n File \"/Users/ntindle/Library/Caches/pypoetry/virtualenvs/autogpt-platform-backend-90-hPFvq-py3.12/lib/python3.12/site-packages/sentry_sdk/scope.py\", line 1755, in isolation_scope\n yield new_isolation_scope\n File \"/Users/ntindle/code/agpt/AutoGPT/main/autogpt_platform/backend/./sentry_bug_repro.py\", line 33, in problematic_async_generator\n yield value\nGeneratorExit\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File \"/Users/ntindle/Library/Caches/pypoetry/virtualenvs/autogpt-platform-backend-90-hPFvq-py3.12/lib/python3.12/site-packages/sentry_sdk/integrations/asyncio.py\", line 55, in _task_with_sentry_span_creation\n reraise(*_capture_exception())\n File \"/Users/ntindle/Library/Caches/pypoetry/virtualenvs/autogpt-platform-backend-90-hPFvq-py3.12/lib/python3.12/site-packages/sentry_sdk/utils.py\", line 1751, in reraise\n raise value\n File \"/Users/ntindle/Library/Caches/pypoetry/virtualenvs/autogpt-platform-backend-90-hPFvq-py3.12/lib/python3.12/site-packages/sentry_sdk/integrations/asyncio.py\", line 53, in _task_with_sentry_span_creation\n result = await coro\n ^^^^^^^^^^\n File \"/Users/ntindle/code/agpt/AutoGPT/main/autogpt_platform/backend/./sentry_bug_repro.py\", line 27, in problematic_async_generator\n with sentry_sdk.isolation_scope() as scope:\n File \"/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/contextlib.py\", line 158, in __exit__\n self.gen.throw(value)\n File \"/Users/ntindle/Library/Caches/pypoetry/virtualenvs/autogpt-platform-backend-90-hPFvq-py3.12/lib/python3.12/site-packages/sentry_sdk/scope.py\", line 1760, in isolation_scope\n _current_scope.reset(current_token)\nValueError: \u003cToken var=\u003cContextVar name='current_scope' default=None at 0x1033a7790> at 0x109af7300> was created in a different Context\n\n❌ Error appears above: 'Token was created in a different Context'\n```\n\n### Workaround\nSave the scope user and tags, then manually catch the error in the generator using capture_exception, then set the tags using scope._tags = previous\n","author":{"url":"https://github.com/ntindle","@type":"Person","name":"ntindle"},"datePublished":"2025-10-15T01:16:08Z","url":"https://github.com/getsentry/sentry-python/issues/4925"}
| 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:551df32d-c02e-570b-45da-7ca95392bc1d |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | DAA8:BF84:3618FC:489033:6B0089C3 |
| html-safe-nonce | 2072f336a9b7a5659930c595b08cdf3188b391c4c2f77566b13cb926ecd318d7 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEQUE4OkJGODQ6MzYxOEZDOjQ4OTAzMzo2QjAwODlDMyIsInZpc2l0b3JfaWQiOiI4NzIxMjkyMzI0NTQ3NjI3NDU5IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 9cb5ff53b357c7c80d94adcfb332b3ca691fa7b9bbfe77d0ef8a80588e96bee1 |
| hovercard-subject-tag | issue:3516005754 |
| 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/4925/issue_layout |
| twitter:image | https://opengraph.githubassets.com/c104e32c4312fc879d153ad73b9fd337b75ea906a827228ca1ddc7224187ce15/getsentry/sentry-python/issues/4925 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/c104e32c4312fc879d153ad73b9fd337b75ea906a827228ca1ddc7224187ce15/getsentry/sentry-python/issues/4925 |
| og:image:alt | How do you use Sentry? Sentry Saas (sentry.io) Version 2.33.2 Steps to Reproduce #!/usr/bin/env python3 """ Minimal reproduction case for Sentry isolation_scope + async generator bug. Bug: Using se... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | ntindle |
| hostname | github.com |
| expected-hostname | github.com |
| None | 4d3d8e50f02c1d7bf86d5acfa1d3bfe9366abd6528a6b429eb07a168429d2b61 |
| 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 | db758f8e02b8257935fb03edf81a3e76eb3abd11 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width