Skip to content

🐛 Bug Report: Runtime context fails to detach token with Async Generation Function #3061

Closed

Description

@feng-95

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

Image

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

Activity

  1. feng-95 commented on Jul 7, 2025

    @feng-95
    ContributorAuthor

    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 context

    Here is the new code:

    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__':
    
        @task()
        async def my_async_generator():
            print("Generator started")
            await asyncio.sleep(1)
            yield 1
            print("my_async_generator Yielded 1")
    
            await asyncio.sleep(2)
            yield 2
            print("my_async_generator Yielded 2")
    
            await asyncio.sleep(3)
            yield 3
            print("my_async_generator Yielded 3")
    
    
        # 使用异步生成器函数
        @task()
        async def main():
    
            async for value in my_async_generator():
                print(f"Processing value: {value}")
                break
    
    
        # run main
    
        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)
    
    
  2. elinacse commented on Sep 16, 2025

    @elinacse
    Contributor

    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':

    @task()
    async def get_first_value():
        print("Getting first value")
        await asyncio.sleep(1)
        print("get_first_value completed")
        return 1
    
    @task()
    async def get_second_value():
        print("Getting second value")
        await asyncio.sleep(2)
        print("get_second_value completed")
        return 2
    
    @task()
    async def get_third_value():
        print("Getting third value")
        await asyncio.sleep(3)
        print("get_third_value completed")
        return 3
    
    
    @task()
    async def main():
        # Get only the first value (equivalent to breaking after first yield)
        value = await get_first_value()
        print(f"Processing value: {value}")
    
    
    # run main
    
    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")
    

    Changes Done -

    1. Replaced the async generator my_async_generator() with three individual async functions:
      get_first_value() - returns 1 after 1 second
      get_second_value() - returns 2 after 2 seconds
      get_third_value() - returns 3 after 3 seconds
    2. Updated the main function to call get_first_value() instead of using the generator with a break

    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 !

  3. elinacse commented on Sep 16, 2025

    @elinacse
    Contributor

    @nirga Can we close this issue? Thanks !

  4. feng-95 commented on Sep 17, 2025

    @feng-95
    ContributorAuthor

    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.

  5. elinacse commented on Sep 17, 2025

    @elinacse
    Contributor

    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':

    @task()
    async def my_async_generator():
        print("Generator started")
        await asyncio.sleep(1)
        yield 1
        print("my_async_generator Yielded 1")
    
        await asyncio.sleep(2)
        yield 2
        print("my_async_generator Yielded 2")
    
        await asyncio.sleep(3)
        yield 3
        print("my_async_generator Yielded 3")
    
    
    @task()
    async def main():
        # Let the generator complete naturally to avoid context issues
        async for value in my_async_generator():
            print(f"Processing value: {value}")
            # break  # Add break to test the issue
    
    
    # run main
    
    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")
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions