Skip to content

Runtime context fails to detach token #2606

Open

Description

@jha-hitesh

Describe your environment
python 3.7
ujson
sanic==20.9.1
opentelemetry-api==1.9.1
opentelemetry-sdk==1.9.1
opentelemetry-propagator-jaeger==1.9.1
opentelemetry-exporter-jaeger-thrift==1.9.1
opentelemetry-instrumentation==0.28b1
opentelemetry-exporter-otlp-proto-http==1.10.0

Steps to reproduce
i have used the opentelemetry-instrumentation to create a middleware for sanic web framework, this middleware allows to trace a request, all seems good but sometimes the error Failed to detach context comes randomly for some request.

What is the expected behavior?
instead of Failed to detach context error , original exception should be logged as exception so that the actual issue can be debugged with proper stacktrace etc.
opentelemetry-python/opentelemetry-api/src/opentelemetry/context/init.py line

here instead of

except Exception:  # pylint: disable=broad-except
        logger.error("Failed to detach context")

it should be

except Exception as e:  # pylint: disable=broad-except
        logger.error(e)

What is the actual behavior?
getting Failed to detach context error message instead of original message.

Additional context

Activity

  1. added
    bug
    on Apr 15, 2022
  2. kasium commented on Jun 1, 2022

    @kasium
    Contributor

    I have the same request. Maybe the code could also be changed to

    except Exception as e:  # pylint: disable=broad-except
            logger.exception("Failed to detach context")

    Is a PR possible?

  3. lzchen commented on Jun 7, 2022

    @lzchen
    Contributor

    @jha-hitesh
    Any idea why the detaching the context would be throwing an exception? We wouldn't want an instrumentation to error out on detaching the context anyways. Maybe make the change locally in the context to debug this. Changing the try except to be not as generic could be a separate issue.

  4. sihrc commented on Jun 16, 2022

    @sihrc

    @lzchen

    Traceback (most recent call last):
      File "/project/.venv/lib/python3.10/site-packages/opentelemetry/context/__init__.py", line 153, in detach
        _RUNTIME_CONTEXT.detach(token)  # type: ignore
      File "/project/.venv/lib/python3.10/site-packages/opentelemetry/context/contextvars_context.py", line 56, in detach
        self._current_context.reset(token)  # type: ignore
    ValueError: <Token var=<ContextVar name='current_context' default={} at 0x7fa9ac2df380> at 0x7fa9ac341780> was created in a different Context

    This kind of exception :)

  5. lzchen commented on Jun 16, 2022

    @lzchen
    Contributor

    @sihrc
    Does this not seem like the instrumentation itself has a bug in it? (in which detach is actually called incorrectly)

  6. kasium commented on Jun 20, 2022

    @kasium
    Contributor

    @lzchen I'm not able to change this locally. Would you accept an exception which changes the log from error to exception?

  7. lzchen commented on Jun 20, 2022

    @lzchen
    Contributor

    @kasium
    Feel free to submit a pr :)

  8. srikanthccv commented on Jun 25, 2022

    @srikanthccv
    Member

    This is fixed in #2774

  9. junli-lyft commented on Aug 12, 2022

    @junli-lyft

    @lzchen

    Traceback (most recent call last):
      File "/project/.venv/lib/python3.10/site-packages/opentelemetry/context/__init__.py", line 153, in detach
        _RUNTIME_CONTEXT.detach(token)  # type: ignore
      File "/project/.venv/lib/python3.10/site-packages/opentelemetry/context/contextvars_context.py", line 56, in detach
        self._current_context.reset(token)  # type: ignore
    ValueError: <Token var=<ContextVar name='current_context' default={} at 0x7fa9ac2df380> at 0x7fa9ac341780> was created in a different Context

    This kind of exception :)

    Hi @sihrc, are you able to root cause this issue and fix it? I am having this exception and not sure how to fix it.
    I traceback.print_stack() the call stack:

    File "/opt/homebrew/Cellar/python-bundle-arm64/0.0.0/brew/opt/python38/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 890, in _bootstrap
        self._bootstrap_inner()
      File "/opt/homebrew/Cellar/python-bundle-arm64/0.0.0/brew/opt/python38/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner
        self.run()
      File "/opt/homebrew/Cellar/python-bundle-arm64/0.0.0/brew/opt/python38/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run
        self._target(*self._args, **self._kwargs)
      File "/Users/junli/.cache/lyftvenv/v/hello-world/tmp58xgye3z/lib/python3.8/site-packages/opentelemetry/sdk/trace/export/__init__.py", line 268, in worker
        self._export(flush_request)
      File "/Users/junli/.cache/lyftvenv/v/hello-world/tmp58xgye3z/lib/python3.8/site-packages/opentelemetry/sdk/trace/export/__init__.py", line 333, in _export
        self._export_batch()
      File "/Users/junli/.cache/lyftvenv/v/hello-world/tmp58xgye3z/lib/python3.8/site-packages/opentelemetry/sdk/trace/export/__init__.py", line 361, in _export_batch
        detach(token)
      File "/Users/junli/.cache/lyftvenv/v/hello-world/tmp58xgye3z/lib/python3.8/site-packages/opentelemetry/context/__init__.py", line 67, in wrapper
        return func(*args, **kwargs)  # type: ignore[misc]
      File "/Users/junli/.cache/lyftvenv/v/hello-world/tmp58xgye3z/lib/python3.8/site-packages/opentelemetry/context/__init__.py", line 159, in detach
    

    But I am not sure how to troubleshoot further. Any ideas?

  10. eliatcodecov commented on Aug 12, 2022

    @eliatcodecov

    I'm having a similar issue to @junli-lyft regarding hitting this exception in detach and cannot seem to reliably reproduce in development. I would love some insight on how to address this, but in my case this issue appears to occur when _RUNTIME_CONTEXT is None.

    Is it an actual error for _RUNTIME_CONTEXT to be None ? If so, how can we troubleshoot this further? If None is a valid state for the _RUNTIME_CONTEXT should detach account for that before throwing the exception?

  11. changed the title [-]Raise Original Exception instead of Failed to detach context[/-] [+]Runtime context fails to detach token[/+] on Aug 12, 2022
  12. srikanthccv commented on Aug 12, 2022

    @srikanthccv
    Member

    Since this appears to be an issue for multiple users, I am going to re-open this with a different title. The original issue was about showing the exception with a log instead of a simple message.

    Is it an actual error for _RUNTIME_CONTEXT to be None ?

    Yes, _RUNTIME_CONTEXT should never be None.

  13. srikanthccv commented on Aug 12, 2022

    @srikanthccv
    Member

    Do any of you use tornado/gevent/eventlet in your applications?

  14. 13 remaining items

  15. ethervoid commented on Dec 5, 2023

    @ethervoid

    We have the same issue using dramatiq. We're using opentelemetry-python with gunicorn and threads and we don't have any issues but with dramatiq and a middleware similar to this one we're suffering this issue

  16. jgibo commented on Apr 22, 2024

    @jgibo

    Are you using any of gevent/eventlet/tornado etc...?

    @srikanthccv, I'm actively getting this issue with a tornado app. python3.11, tornado 6.3.2. Why do you ask?

  17. alexmojaki commented on May 3, 2024

    @alexmojaki
    Contributor

    I've run into this. I can reproduce it with the script below. I've tried my absolute best to reduce it to a minimal example but it's very weird and sensitive. Even running this code in a Docker container removes the error. Here's the script:

    import openai
    from opentelemetry import context
    
    import logfire
    
    logfire.configure(
        token='LCyjlJqNbFXqVmQ6lZVLKwxSrPJmKWgXmZG0rJpkS0c4'
        # Uncommenting this removes the error:
        # send_to_logfire=False
        # This might be because sending to logfire adds a thread for a BatchSpanProcessor.
    )
    
    
    class MyStream:
        def __iter__(self):
            # Replacing self._it with a plain variable removes the error,
            # probably because it affects garbage collection.
            self._it = self.stream()
            for item in self._it:
                yield item
    
            # Replacing the above loop with this removes the error.
            # yield from self._it
    
        def stream(self):
            with logfire.span('streaming'):
                yield 1
                yield 2
    
    
    def patched_post(*_, **__):
        # Removing this line removes the error. It returns None.
        context.get_value('foo')
        return MyStream()
    
    
    # Uncommenting this removes the error, whether or not you keep the same line above within the function.
    # context.get_value('foo')
    
    # You DON'T need to fill in a real API key here.
    client = openai.Client(api_key='...')
    client.post = patched_post
    
    # Uncommenting this removes the error, as does messing with the create method in various ways.
    # client.chat.completions.create = patched_post
    
    # Extracting the result of this method call into a global variable removes the error,
    # because it means the generator will only be garbage collected on shutdown.
    for _ in client.chat.completions.create(model=1, messages=1, stream=1):
        # This is critical - it ensures that the `stream()` generator is left suspended when garbage collected.
        break

    And the error output:

    Failed to detach context
    Traceback (most recent call last):
      File "test.py", line 27, in stream
        yield 1
    GeneratorExit
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/home/alex/work/logfire/.venv/lib/python3.12/site-packages/opentelemetry/context/__init__.py", line 163, in detach
        _RUNTIME_CONTEXT.detach(token)  # type: ignore
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/alex/work/logfire/.venv/lib/python3.12/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 0x7f1ffc906430> at 0x7f1ffc730780> was created in a different Context
    

    To run this code you will need to pip install logfire openai. You may or may not get the error. For what it's worth, here's some versions:

    openai==1.23.3
    logfire==0.28.3
    Python 3.12.3 (main, Apr 15 2024, 18:25:56) [Clang 17.0.6 ]
    Ubuntu 22.04.4 LTS
    

    The essential part is that a context is attached in a generator which never completes properly, so the generator exits when it's garbaged collected and that's when detaching the context tries and fails. I don't know why it fails, I'm guessing garbage collections happens 'in a different context'? It seems like a CPython bug.

  18. sylvainmouquet commented on May 9, 2024

    @sylvainmouquet

    another example, the error occured when the reset is done in a async/await function :

    import contextvars
    import asyncio
    
    var = contextvars.ContextVar('var')
    var.set('spam')
    token_ok_1 = var.set(1)
    token_ok_2 = var.set(1)
    token_ko = var.set(1)
    
    async def main_ko():
        try:
            var.reset(token_ko)
        except Exception as e:
            print('KO')
            raise e
    
    def main_ok():
        var.reset(token_ok_2)
        
    if __name__ == "__main__":
        var.reset(token_ok_1)
        main_ok()
        asyncio.run(main_ko())
    

    result :

    python3 error.py
    KO
    Traceback (most recent call last):
     ...
      File "app/error.py", line 14, in main
        raise e
      File "app/error.py", line 11, in main
        var.reset(token_ko)
        ~~~~~~~~~^^^^^^^^^^
    ValueError: <Token var=<ContextVar name='var' at 0x10026e5c0> at 0x1002b3140> was created in a different Context
    
    
  19. alexmojaki commented on May 9, 2024

    @alexmojaki
    Contributor

    @sylvainmouquet that example can be reduced to:

    import asyncio
    import contextvars
    
    var = contextvars.ContextVar('var')
    token = var.set(1)
    
    
    async def main():
        var.reset(token)
    
    
    asyncio.run(main())

    Here the error message makes sense. The token was created when calling var.set(1) globally before starting an async event loop, then we're trying to reset inside an async context.

  20. alexmojaki commented on May 9, 2024

    @alexmojaki
    Contributor

    Here's a good repro:

    import asyncio
    
    from opentelemetry import context, trace
    
    
    async def gen():
        token = context.attach(trace.set_span_in_context('span'))
        try:
            yield 1
            yield 2
        finally:
            context.detach(token)
    
    
    async def main():
        async for i in gen():
            print(i)
            break
    
    
    asyncio.run(main())

    The error isn't there if you remove the break or make gen a non-async generator. So while #2606 (comment) shows that it can happen in sync code, it's much easier to reproduce with async generators.

  21. sylvainmouquet commented on May 12, 2024

    @sylvainmouquet

    When using a generator, the solution is to use async with contextlib.aclosing(gen()) as agen: as explained here:
    python/cpython#118944

  22. alexmojaki commented on May 12, 2024

    @alexmojaki
    Contributor

    Here's a minimal repro without async:

    import threading
    
    from opentelemetry import context, trace
    
    
    class Foo:
        pass
    
    
    def gen(_foo):
        token = context.attach(trace.set_span_in_context('span'))
        try:
            yield 1
            yield 2
        finally:
            context.detach(token)
    
    
    def main():
        # Create a circular reference to delay garbage collection
        foo = Foo()
        foo.gen = gen(foo)
    
        for _ in foo.gen:
            # Leave the generator suspended
            break
    
    
    threading.Thread(target=main).start()
  23. sylvainmouquet commented on May 12, 2024

    @sylvainmouquet

    there is the function closing :

    ...
    with contextlib.closing(gen(foo)) as agen:
         for _ in agen:
    ...
    
  24. alexmojaki commented on May 12, 2024

    @alexmojaki
    Contributor

    The problem is that OTEL SDKs can typically only add spans to iterators to instrument them, they can't ensure/require that the code creating/using those spans closes/finishes the iterators.

    For example, consider this code in opentelemetry-instrumentation-wsgi:

    def _end_span_after_iterating(iterable, span, token):
        try:
            with trace.use_span(span):
                yield from iterable
        finally:
            close = getattr(iterable, "close", None)
            if close:
                close()
            span.end()
            if token is not None:
                context.detach(token)

    Here iterable is the WSGI response. If iteration is not completed (e.g. if the client doesn't read the full response) then it's unclear if/when/how the finally block will end up running. It may depend on how the WSGI server cleans up disconnected clients or Python's garbage collection. This means that the span may remain open for an unpredictable amount of time, and detaching the token may log the error in this thread.

  25. enrico-stauss commented on Oct 10, 2024

    @enrico-stauss

    This issue just came up for me. I'm executing asyncio.run() on an async func of mine that executes a LlamaIndex Workflow which applies LlamaIndex instrumentation logic. I can see if I'm able to come up with an MWE for this, but do you have an idea at what point I should start digging in order to debug this?
    This is the token that cannot be detached:
    image

    And the callstack:
    image

    Thanks and kind regards

  26. alexmojaki commented on Oct 10, 2024

    @alexmojaki
    Contributor

    Ensure that the body of with trace.use_span/tracer.start_as_current_span/logfire.span never directly contains a yield. See https://logfire.pydantic.dev/docs/guides/advanced/generators/

  27. Lyndon-prequel commented on May 12, 2025

    @Lyndon-prequel

    I ran into this issue too.  To make it easier for others to figure out if they're affected, I created a common reliability enumeration (CRE). You can preview the rule here or run it against your logs here.

  28. rtpg commented on Oct 20, 2025

    @rtpg

    I would like to point out that I hit this with the Django plugin, and here's my fix. I believe that other plugins might have the same issue.

    The short version is that if you have code that is doing manual __enter__ and __exit__ you might also be facing this issue (similarly with attach/detach code in general).

    open-telemetry/opentelemetry-python-contrib#3848

    Part of the reason this stuff is so mystifying in the stack traces is that in these cases it's garbage collection that will often end up triggering finally blocks, so your traces are not really reliable in undrestanding the source of the issue.

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

    bug

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions