You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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
Reacted by Hasier, Daniel Schiavini, Eric Eastwood, Sindy Li, Soumendra Kumar Sahoo, bogdandm, Marcus Way, jessereich-mcs, Mathieu Pichette, Marcus Robinson and 8 more
@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.
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?
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?
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 ?
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
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:
importopenaifromopentelemetryimportcontextimportlogfirelogfire.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.
)
classMyStream:
def__iter__(self):
# Replacing self._it with a plain variable removes the error,# probably because it affects garbage collection.self._it=self.stream()
foriteminself._it:
yielditem# Replacing the above loop with this removes the error.# yield from self._itdefstream(self):
withlogfire.span('streaming'):
yield1yield2defpatched_post(*_, **__):
# Removing this line removes the error. It returns None.context.get_value('foo')
returnMyStream()
# 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_inclient.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:
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.
Reacted by Shuai Liu, Daniel Robert, Rushabh Doshi, Dinmukhamed Mailibay and Saberwang
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
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.
Reacted by Sylvain MOUQUET, Daniel Robert and Wang Guan
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.
Reacted by Thomas Desrosiers, Bhavik Talaviya , Peter Morrow and rarya10
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:
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.
Reacted by Daniel Robert, Dinmukhamed Mailibay and Wang Guan
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:
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.
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).
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.
Activity
kasium commentedon Jun 1, 2022
I have the same request. Maybe the code could also be changed to
Is a PR possible?
lzchen commentedon Jun 7, 2022
@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.
sihrc commentedon Jun 16, 2022
@lzchen
This kind of exception :)
lzchen commentedon Jun 16, 2022
@sihrc
Does this not seem like the instrumentation itself has a bug in it? (in which
detachis actually called incorrectly)kasium commentedon Jun 20, 2022
@lzchen I'm not able to change this locally. Would you accept an exception which changes the log from
errortoexception?lzchen commentedon Jun 20, 2022
@kasium
Feel free to submit a pr :)
srikanthccv commentedon Jun 25, 2022
This is fixed in #2774
junli-lyft commentedon Aug 12, 2022
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:But I am not sure how to troubleshoot further. Any ideas?
eliatcodecov commentedon Aug 12, 2022
I'm having a similar issue to @junli-lyft regarding hitting this exception in
detachand 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_CONTEXTisNone.Is it an actual error for
_RUNTIME_CONTEXTto beNone? If so, how can we troubleshoot this further? IfNoneis a valid state for the_RUNTIME_CONTEXTshoulddetachaccount for that before throwing the exception?[-]Raise Original Exception instead of Failed to detach context[/-][+]Runtime context fails to detach token[/+]srikanthccv commentedon Aug 12, 2022
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.
Yes,
_RUNTIME_CONTEXTshould never beNone.srikanthccv commentedon Aug 12, 2022
Do any of you use
tornado/gevent/eventletin your applications?13 remaining items
ethervoid commentedon Dec 5, 2023
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
jgibo commentedon Apr 22, 2024
@srikanthccv, I'm actively getting this issue with a tornado app. python3.11, tornado 6.3.2. Why do you ask?
alexmojaki commentedon May 3, 2024
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:
And the error output:
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: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.
sylvainmouquet commentedon May 9, 2024
another example, the error occured when the reset is done in a async/await function :
result :
alexmojaki commentedon May 9, 2024
@sylvainmouquet that example can be reduced to:
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.alexmojaki commentedon May 9, 2024
Here's a good repro:
The error isn't there if you remove the
breakor makegena non-async generator. So while #2606 (comment) shows that it can happen in sync code, it's much easier to reproduce with async generators.sylvainmouquet commentedon May 12, 2024
When using a generator, the solution is to use
async with contextlib.aclosing(gen()) as agen:as explained here:python/cpython#118944
alexmojaki commentedon May 12, 2024
Here's a minimal repro without async:
sylvainmouquet commentedon May 12, 2024
there is the function closing :
alexmojaki commentedon May 12, 2024
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:Here
iterableis 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 thefinallyblock 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.enrico-stauss commentedon Oct 10, 2024
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:
And the callstack:

Thanks and kind regards
alexmojaki commentedon Oct 10, 2024
Ensure that the body of
with trace.use_span/tracer.start_as_current_span/logfire.spannever directly contains ayield. See https://logfire.pydantic.dev/docs/guides/advanced/generators/Lyndon-prequel commentedon May 12, 2025
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.
rtpg commentedon Oct 20, 2025
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
finallyblocks, so your traces are not really reliable in undrestanding the source of the issue.chore(logging): suppress benign OTEL `Failed to detach context` warnings