adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

ERROR:opentelemetry.context:Failed to detach context

Open pawan-dream11 opened this issue 1 year ago • 26 comments

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

python-dotenv>=1.0.0 asyncio google-adk==1.4.2 absl-py==2.2.1 cloudpickle==3.1.1 flake8-pyproject==1.2.3 aiohttp==3.10.11 uv==0.7.14 requests>=2.32.3

To Reproduce Steps to reproduce the behavior:

  1. Install above dependencies
  2. Run adk web
  3. Open '....'
  4. See error

Desktop (please complete the following information):

  • Python version(python -V): 13.3
  • ADK version(pip show google-adk): 1.4.2

Model Information: For example, which model is being used. gemini-2.5-pro

pawan-dream11 avatar Jun 26 '25 14:06 pawan-dream11

Same Issue, Weirdly, it happens once in a while.

Apollovishwas avatar Jun 27 '25 07:06 Apollovishwas

Same! Want to upvote this!

sumitg avatar Jul 02 '25 15:07 sumitg

Same! It happened with me when i am dynamically create agents and pass them to parallel or sequential agents, because opentelemetry have different contextvar(

maxbaluev avatar Jul 09 '25 13:07 maxbaluev

+1

paward35 avatar Jul 16 '25 23:07 paward35

Same here... Happening every time we try using a ParallelAgent with sub_agents created at runtime.

svelezdevilla avatar Jul 17 '25 09:07 svelezdevilla

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

vtwoptwo avatar Jul 17 '25 10:07 vtwoptwo

We’re seeing this issue quite frequently during peak hours, while it occurs less often at night or on weekends.

On Thu, Jul 17, 2025 at 4:28 PM Friendly Neighborhood Droid < @.***> wrote:

vtwoptwo left a comment (google/adk-python#1670) https://github.com/google/adk-python/issues/1670#issuecomment-3083603867

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

— Reply to this email directly, view it on GitHub https://github.com/google/adk-python/issues/1670#issuecomment-3083603867, or unsubscribe https://github.com/notifications/unsubscribe-auth/BLBOHXPVNZ77SWAAZKYLEKD3I56WPAVCNFSM6AAAAACAGLOOPWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZTAOBTGYYDGOBWG4 . You are receiving this because you are subscribed to this thread.Message ID: @.***>

--

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.

PrakhyathBits avatar Jul 17 '25 12:07 PrakhyathBits

+1

heinolaubscher avatar Jul 18 '25 10:07 heinolaubscher

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.

Thanks for your all's patience!


@jawoszek could you look into this further?

Jacksunwei avatar Jul 21 '25 23:07 Jacksunwei

@aabmass we can use this issue to track the AsyncGenerator + OTel.

Jacksunwei avatar Jul 24 '25 22:07 Jacksunwei

+1, this doesn't happen to us in development (locally built docker container) but in production it happens consistently when trying to utilize a tool and pass off to a subagent :/

jjbi123 avatar Jul 24 '25 22:07 jjbi123

Got it, I'll copy my comment from the other issue here then


For some context on what is happening see the following:

  • https://github.com/python/cpython/issues/118944
  • https://github.com/open-telemetry/opentelemetry-python/issues/2606
  • https://logfire.pydantic.dev/docs/reference/advanced/generators/ (uses OTel under the hood)

I would recommend this fix https://github.com/python/cpython/issues/118944#issuecomment-2105661088 as a quick and correct workaround if the issue is an async iterator. Changing from start_as_current_span() -> start_span() is not a great fix because it breaks span parent propagation.

aabmass avatar Jul 25 '25 01:07 aabmass

@Jacksunwei I'll work on it, thanks @aabmass for hints!

jawoszek avatar Jul 25 '25 18:07 jawoszek

I seem to be getting it every time I run it, not sure what's causing it

tom-xerberus-io avatar Jul 29 '25 03:07 tom-xerberus-io

The detach errors were fixed in https://github.com/google/adk-python/pull/2383 for most built-in agents (released in https://github.com/google/adk-python/releases/tag/v1.11.0) and in https://github.com/google/adk-python/pull/2601 for parallel agents (to be released next week).

If anyone encounters this while using adk with custom agents or any other custom code, please make sure that all async generators in the custom code are aclosed.

If anyone still encounters the errors with the fixes and no custom code - please let me know.

jawoszek avatar Aug 22 '25 11:08 jawoszek

Thanks @jawoszek for the great work!

Jacksunwei avatar Aug 22 '25 17:08 Jacksunwei

@jawoszek I got the same error on a tutorial example, when using langfuse.

langfuse_test.py

The problem seems to be the break statement here:

    user_msg = types.Content(role="user", parts=[types.Part(text="hi")])
    async for event in runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=user_msg):
        if event.is_final_response():
            print(event.content.parts[0].text)
            break

As soon as I delete the break statement, the error ValueError: <Token var=<ContextVar name='current_context' default={} at 0x00000218493ABBF0> at 0x0000021858D7BA80> was created in a different Context disappears.

The reason, I wrote the break statement was because of the following tutorial, where also a break statement is included in the same context: https://google.github.io/adk-docs/tutorials/agent-team/#step-1-your-first-agent-basic-weather-lookup

I don't know if it is supposed to work despite the break or if this is just sloppy code inside the tutorial?

My versions: google-adk 1.12.0 langfuse 3.3.0 opentelemetry-api 1.36.0 opentelemetry-exporter-gcp-trace 1.9.0 opentelemetry-exporter-otlp-proto-common 1.36.0 opentelemetry-exporter-otlp-proto-http 1.36.0 opentelemetry-proto 1.36.0 opentelemetry-resourcedetector-gcp 1.9.0a0 opentelemetry-sdk 1.36.0 opentelemetry-semantic-conventions 0.57b0

Netzeband avatar Aug 24 '25 15:08 Netzeband

@Netzeband yes, code in the tutorial was not updated with the fix and the break is triggering the issue. The simplest fix is to follow the aclose() example from https://github.com/google/adk-python/blob/ad81aa54de1f38df580915b7f47834ea8e5f1004/contributing/samples/telemetry/main.py#L51-L61 or using contextlib.aclosing.

Thanks for noticing this, I'll update the tutorial.

jawoszek avatar Aug 26 '25 19:08 jawoszek

@jawoszek Thanks for the response and the suggestions, I will try it out.

Netzeband avatar Aug 26 '25 19:08 Netzeband

So I guess the correct way would be something like this (same thing, just no need for try/finally, and notably we can keep break) as per https://docs.python.org/3/library/contextlib.html#contextlib.aclosing

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:
        # ...

alexanderad avatar Sep 27 '25 15:09 alexanderad