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
{{ message }}
Repository navigation
ERROR:opentelemetry.context:Failed to detach context #1670
** Please make sure you read the contribution guide and file the issues in the right place. ** Contribution guide.
Describe the bug
We have deployed our agent. and getting this issue -
Traceback (most recent call last):
File "/home/myuser/.local/lib/python3.11/site-packages/opentelemetry/context/init.py", line 155, in detach
_RUNTIME_CONTEXT.detach(token)
File "/home/myuser/.local/lib/python3.11/site-packages/opentelemetry/context/contextvars_context.py", line 53, in detach
self._current_context.reset(token)
ValueError: <Token var=<ContextVar name='current_context' default={} at 0x3e20a81529d0> at 0x3e209c1a1340> was created in a different Context
dependencies list in requirements.txt is as follow:-
Same! It happened with me when i am dynamically create agents and pass them to parallel or sequential agents, because opentelemetry have different contextvar(
Reacted by svelezdevilla, Agata Golebiowska, Mauricio Marzol and pankajGT
what i did was just create a patch in the library that removes the error logging in the exception - i still see the logs of my traces and the code of the agents works fine
--
Please note that this email and all files, information, intents and
effects contained herein, and conveyed hereby, shall be construed as
strictly and absolutely confidential intellectual property of CropIn,
intended solely for use by the addressee. Notwithstanding anything
contained herein, this email shall not be construed to give rise to any
implied contractual relationship between CropIn and/or its representatives
and the recipient/s. In spite of due diligence exercised by CropIn to
ensure that this email and all attachments herewith are free from
viruses/defects, it will be the sole responsibility of the recipient to
proceed with caution, and CropIn and/ or its representatives shall not in
any way be liable for any unforeseen security breach arising thereof. If
this email has reached you in error, or you are not the intended recipient
of such email, you should delete this email along with any attachments from
your system, after notification to the sender. Any unauthorised
dissemination, disclosure and/ or use of the contents of this communication
to anyone for any purpose whatsoever, is strictly prohibited and punishable
in law.
I think this is likely due to with statement over python generator.
My theory so far, is: after with statement (for otel span tracing) is out of scope and tries to restore the otel token back to original one, the current token is no long the previous one, since python generator is not strictly FILO stack.
I'm looking into how to solve this. I'd appreciate if anyone can help with a minimal reproducible agent setup for either Sequential or Parallel Agent.
Significantly, aclosing() supports deterministic cleanup of async generators when they happen to exit early by break or an exception
with contextlib.aclosing (for Python >= 3.10+):
importcontextlibasyncwithcontextlib.aclosing(runner.run_async(...)) asagen:
asyncforeventinagen:
# do your thing# notably, you can use "break" if required, e.g.:ifevent.is_final_response():
# ...break
with a "polyfill" from google.adk (to support Python < 3.10):
Significantly, aclosing() supports deterministic cleanup of async generators when they happen to exit early by break or an exception
with contextlib.aclosing (for Python >= 3.10+):
import contextlib
async with contextlib.aclosing(runner.run_async(...)) as agen:
async for event in agen:
# do your thing
# notably, you can use "break" if required, e.g.:
if event.is_final_response():
# ...
break
with a "polyfill" from google.adk (to support Python < 3.10):
from google.adk.utils.context_utils import Aclosing
async with Aclosing(runner.run_async(...)) as agen:
async for event in agen:
# ...
Right, all three options should be equivalent apart from requiring different Python/ADK versions:
# requires Python >= 3.10importcontextlibasyncwithcontextlib.aclosing(runner.run_async(...)) asagen:
asyncforeventinagen:
# do your thingbreak
# requires ADK >= 1.11.0fromgoogle.adk.utils.context_utilsimportAclosingasyncwithAclosing(runner.run_async(...)) asagen:
asyncforeventinagen:
# do your thingbreak
# works in all Python versions, but is the most verboseagen=runner.run_async(...)
try:
asyncforeventinagen:
# do your thingbreakfinally:
awaitagen.aclose()
I also ran into this issue and tried your proposed fixes @jawoszek (thanks btw!). But I'm running ADK behind a FastAPI endpoint which returns a StreamingResponse (i.e. events emitted by ADK are streamed to the caller of the endpoint). If I implement one of @jawoszek's approaches nothing gets returned. I suspect it's b.c. the stream gets closed too early. Does anyone else have this issue?
The error happens when I remove the finally block. The error also shows up when I remove the run_config=RunConfig(streaming_mode=StreamingMode.SSE) line.
On the other hand, if I keep the finally block in the code the endpoint doesn't return any events (as described previously).
As you've suspected - in your example the event_stream is closed too early (finally is triggered before returning StreamingResponse). The solution would be to have aclosing/aclose in a separate generator, as in my examples above.
Note - I'm thinking that in theory if we pass output of runner.run_async directly to StreamingResponse we shouldn't need any additional closing, as we don't introduce any additional async generators. But in my testing - raw output of runner.run_async doesn't work with StreamingResponse so we need to transform it with additional generator.
Activity
Apollovishwas commentedon Jun 27, 2025
Same Issue, Weirdly, it happens once in a while.
sumitg commentedon Jul 2, 2025
Same! Want to upvote this!
maxbaluev commentedon Jul 9, 2025
Same! It happened with me when i am dynamically create agents and pass them to parallel or sequential agents, because opentelemetry have different contextvar(
paward35 commentedon Jul 16, 2025
+1
svelezdevilla commentedon Jul 17, 2025
Same here...
Happening every time we try using a ParallelAgent with sub_agents created at runtime.
vtwoptwo commentedon Jul 17, 2025
what i did was just create a patch in the library that removes the error logging in the exception - i still see the logs of my traces and the code of the agents works fine
PrakhyathBits commentedon Jul 17, 2025
heinolaubscher commentedon Jul 18, 2025
+1
fix: allows current sub-agent to finish execution before exiting the …
fix: allows current sub-agent to finish execution before exiting the …
fix: allows current sub-agent to finish execution before exiting the …
Jacksunwei commentedon Jul 21, 2025
I think this is likely due to
withstatement over python generator.My theory so far, is: after
withstatement (for otel span tracing) is out of scope and tries to restore the otel token back to original one, the current token is no long the previous one, since python generator is not strictly FILO stack.I'm looking into how to solve this. I'd appreciate if anyone can help with a minimal reproducible agent setup for either Sequential or Parallel Agent.
Thanks for your all's patience!
@jawoszek could you look into this further?
39 remaining items
alexanderad commentedon Sep 27, 2025
So I guess the correct way would be something like this (same thing, just no need for
try/finally, and notably we can keepbreak) as per https://docs.python.org/3/library/contextlib.html#contextlib.aclosingwith
contextlib.aclosing(forPython >= 3.10+):with a "polyfill" from
google.adk(to supportPython < 3.10):weisiang9678 commentedon Sep 30, 2025
thanks for the idea... this solved the issue
jawoszek commentedon Oct 6, 2025
Right, all three options should be equivalent apart from requiring different Python/ADK versions:
schlaepf commentedon Oct 9, 2025
I also ran into this issue and tried your proposed fixes @jawoszek (thanks btw!). But I'm running ADK behind a FastAPI endpoint which returns a
StreamingResponse(i.e. events emitted by ADK are streamed to the caller of the endpoint). If I implement one of @jawoszek's approaches nothing gets returned. I suspect it's b.c. the stream gets closed too early. Does anyone else have this issue?jawoszek commentedon Oct 9, 2025
@schlaepf could you share a snippet of the endpoint code where the break is?
schlaepf commentedon Oct 10, 2025
I don't have a break statement anywhere in my code, but this snippet should illustrate the problem.
The error happens when I remove the
finallyblock. The error also shows up when I remove therun_config=RunConfig(streaming_mode=StreamingMode.SSE)line.On the other hand, if I keep the
finallyblock in the code the endpoint doesn't return any events (as described previously).jawoszek commentedon Oct 18, 2025
@schlaepf apologies for the delay.
Without explicit break I'm not able to easily reproduce. Below works as expected, no detach errors:
Working code without break
I was able to reproduce the detach error if I add a break that triggers the detach error:
Code with break that triggers detach error
Adding try-finally-aclose or aclosing in the generator allows to fix the detach errors:
Code with break and aclose - there are no detach errors
Code with break and aclosing - there are no detach errors
As you've suspected - in your example the
event_streamis closed too early (finallyis triggered before returningStreamingResponse). The solution would be to have aclosing/aclose in a separate generator, as in my examples above.Note - I'm thinking that in theory if we pass output of
runner.run_asyncdirectly toStreamingResponsewe shouldn't need any additional closing, as we don't introduce any additional async generators. But in my testing - raw output ofrunner.run_asyncdoesn't work withStreamingResponseso we need to transform it with additional generator.fix: add workaround for opentelemetry-sdk version conflict
perf(ci): Add pip dependency caching to all workflows (#6)
feat: Install and configure Google ADK (Task 1.0) (#4)
Fix ADK compatibility issues and add Langfuse observability
[imjaroiswebdev/google-adk] Mejoras en generación de CVs y timeouts d…
fix: allows current sub-agent to finish execution before exiting the …
fix: aclose all async generators to fix OTel tracing context
fix: rework parallel_agent.py to always aclose async generators