Repository navigation
Closed
Description
Which component is this bug for?
Traceloop SDK
📜 Description
When I add a @task() decorator to a async generation function. It will trigger a Runtime context fails to detach token error:
Failed to detach context
Traceback (most recent call last):
File "./.venv/lib/python3.10/site-packages/traceloop/sdk/decorators/base.py", line 106, in _ahandle_generator
yield part
GeneratorExit
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./.venv/lib/python3.10/site-packages/opentelemetry/context/__init__.py", line 154, in detach
_RUNTIME_CONTEXT.detach(token)
File "./.venv/lib/python3.10/site-packages/opentelemetry/context/contextvars_context.py", line 50, in detach
self._current_context.reset(token) # type: ignore
ValueError: <Token var=<ContextVar name='current_context' default={} at 0x104f95530> at 0x11608db00> was created in a different Context
This error was triggered by this line of code: https://github.com/traceloop/openllmetry/blob/main/packages/traceloop-sdk/traceloop/sdk/decorators/base.py#L113
I try to comment out this code, it works fine. But I have no idea if it will trigger any other issues.
👟 Reproduction steps
Here is the example code:
import time
from traceloop.sdk import Traceloop
from traceloop.sdk.decorators import task
from opentelemetry.sdk.trace.export import (
ConsoleSpanExporter,
SpanExporter,
)
if __name__ == '__main__':
@task()
async def my_async_generator():
print("Generator started")
time.sleep(1)
yield 1
print("my_async_generator Yielded 1")
time.sleep(2)
yield 2
print("my_async_generator Yielded 2")
time.sleep(3)
yield 3
print("my_async_generator Yielded 3")
# use async gen func
@task()
async def main():
async for value in my_async_generator():
print(f"Processing value: {value}")
break
# run main
import asyncio
span_exporter: SpanExporter = ConsoleSpanExporter()
resource_attributes = {
"service.name": "test_service",
}
Traceloop.init(app_name='test', disable_batch=True, exporter=span_exporter,
resource_attributes=resource_attributes)
asyncio.run(main())
print("function end")
time.sleep(20)👍 Expected behavior
It should have no error log.
👎 Actual Behavior with Screenshots
No
🤖 Python Version
3.10
📃 Provide any additional context for the Bug.
No response
👀 Have you spent some time to check if this bug has been raised before?
- I checked and didn't find similar issue
Are you willing to submit PR?
None
Metadata
Metadata
Assignees
Labels
No labels

Activity
feng-95 commentedon Jul 7, 2025
Hi @mileaage , thanks for your reply. I tried to use await asyncio.sleep() instead of time.sleep(). But I get the same result that return the error:
Failed to detach contextHere is the new code:
elinacse commentedon Sep 16, 2025
Hi @feng-95 ,
I have modified this sample and I am not getting this issue with the updated change .
import time
import asyncio
from traceloop.sdk import Traceloop
from traceloop.sdk.decorators import task
from opentelemetry.sdk.trace.export import (
ConsoleSpanExporter,
SpanExporter,
)
if name == 'main':
Changes Done -
get_first_value() - returns 1 after 1 second
get_second_value() - returns 2 after 2 seconds
get_third_value() - returns 3 after 3 seconds
The code now uses individual async functions with @task decorators instead of an async generator, which completely avoids the context management issues while maintaining the same behavior.
We are good to close the issue now @feng-95 . Thanks !
elinacse commentedon Sep 16, 2025
@nirga Can we close this issue? Thanks !
feng-95 commentedon Sep 17, 2025
Hi @elinacse , thanks for your reply. But the problem is: if we have an async generator function, such as
my_async_generator(), we can not use the @task decorators to generate trace span for this function. We need to change the function which violates our principle of non-intrusive.elinacse commentedon Sep 17, 2025
Hi @feng-95 ,
The problem is not that @task doesn't work with async generators.
The issue is:
The context detachment error occurs when generators are terminated early
Your break statement: This causes the generator to be closed prematurely, The cleanup happens in a different context than where the token was created.
the same sample works fine without break statement .
import time
import asyncio
from traceloop.sdk import Traceloop
from traceloop.sdk.decorators import task
from opentelemetry.sdk.trace.export import (
ConsoleSpanExporter,
SpanExporter,
)
if name == 'main':