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

The last_update_time provided in the session object '2025-07-01 18:59:42' is earlier than the update_time in the storage_session '2025-07-01 18:59:56'. Please check if it is a stale session

Open CodyTonn opened this issue 1 year ago • 35 comments

Describe the bug

{"error": "The last_update_time provided in the session object '2025-07-01 18:59:42' is earlier than the update_time in the storage_session '2025-07-01 18:59:56'. Please check if it is a stale session."}

main.py

session_mysql_url = os.getenv('SESSION_MYSQL_URL')

app = get_fast_api_app(
    agents_dir="./sql_agent",
    session_service_uri=session_mysql_url,
    allow_origins=["*"],
    web=False,
    trace_to_cloud=False,
)

if __name__ == "__main__":
    import uvicorn

    config = uvicorn.Config(
        "main:app",
        log_level="info",
        port=8000,
        reload=True,
        # Disable Uvicorn's default logging config
        log_config=None
    )
    server = uvicorn.Server(config)
    server.run()

Desktop (please complete the following information):

  • OS:
  • Python version(python -V): 3.12
  • ADK version(pip show google-adk): 1.4.1
  • uvicorn: 0.34.3

Model Information:

  • qwen-max model

CodyTonn avatar Jul 01 '25 11:07 CodyTonn

Same problem..Happens when I use MySQL DB for session service uri

veevortexiq avatar Jul 02 '25 15:07 veevortexiq

Thanks for reporting this bug! Could you please provide the following information? which should be helpful for me to understand the problem

  1. Does your mysql db has a different timezone from your environment where you run the agent?
  2. Does the same issue happens when using different databases, e.g. sqlite?

xuanyang15 avatar Jul 02 '25 17:07 xuanyang15

  1. Does your mysql db has a different timezone from your environment where you run the agent?
SELECT @@global.time_zone;
output:+08:00

SELECT @@session.time_zone;
outpu: +08:00

SELECT @@system_time_zone;
outpu: CST

I used Alibaba Cloud's RDS database service, which is based on MySQL.

SELECT VERSION();
outpu: 5.7.44-log

CodyTonn avatar Jul 03 '25 09:07 CodyTonn

Thanks for the additional information! Is it possible for you to share a minimal runnable example to reproduce it?

xuanyang15 avatar Jul 04 '25 03:07 xuanyang15

I tried with the following simple example and I cannot reproduce the error, so I suspect the error you saw was caused by some race conditions, for example, your application might be processing multiple events for the same session concurrently, leading to a race condition where an older session object is used to update the state.

If it is not easy to share a minimal runnable example, could you please let me know how I might modify my following test code to reproduce the error?

folder tree

├── hello_world
│   ├── agent.py
│   └── __init__.py
├── main.py
└── test.py

main.py

from google.adk.cli.fast_api import get_fast_api_app
import uvicorn

# session_service_url = "sqlite:///./sessions.db"
session_service_url = "mysql+pymysql://root:[email protected]:3306/sessions"

app = get_fast_api_app(
    agents_dir=".",
    session_service_uri=session_service_url,
    allow_origins=["*"],
    web=True,
    trace_to_cloud=False,
)

if __name__ == "__main__":
  config = uvicorn.Config(
      "main:app",
      log_level="info",
      port=8080,
      reload=True,
      # Disable Uvicorn's default logging config
      log_config=None,
  )
  server = uvicorn.Server(config)
  server.run()

test.py

from typing import Any
import requests

APP_NAME = "hello_world"
USER_ID = "user"

BASE_URL = "http://localhost:8080"

headers = {}


def get_request(
    url: str, params: dict[str, Any] | None = None
) -> dict[str, Any]:
  if params is None:
    params = {}
  response = requests.get(
      BASE_URL + url, headers=headers, params=params, timeout=60
  )
  response.raise_for_status()
  return response.json()


def post_request(url: str, payload: Any) -> dict[str, Any]:
  response = requests.post(
      BASE_URL + url, headers=headers, json=payload, timeout=60
  )
  response.raise_for_status()
  return response.json()


if __name__ == "__main__":
  print("list-app:", get_request("/list-apps"))

  # request = requests.post(
  #     "http://localhost:8080/apps/test-app/users/test-user/sessions",
  #     json={
  #         "app_name": "test-app",
  #         "user_id": "test-user",
  #     },
  # )
  # print("Created a new session")

  print(
      "list-sessions:",
      get_request(f"/apps/{APP_NAME}/users/{USER_ID}/sessions"),
  )

  print(
      "run:",
      post_request(
          "/run",
          {
              "appName": "hello_world",
              "userId": "user",
              "sessionId": "94c095a0-5379-421d-ae93-3673200d9ee5",
              "newMessage": {
                  "parts": [{"text": "Roll a 10 sided dice"}],
                  "role": "user",
              },
              "streaming": False,
          },
      ),
  )

agent.py

import random

from google.adk import Agent
from google.adk.tools.tool_context import ToolContext
from google.genai import types


def roll_die(sides: int, tool_context: ToolContext) -> int:
  """Roll a die and return the rolled result.

  Args:
    sides: The integer number of sides the die has.

  Returns:
    An integer of the result of rolling the die.
  """
  result = random.randint(1, sides)
  if not 'rolls' in tool_context.state:
    tool_context.state['rolls'] = []

  tool_context.state['rolls'] = tool_context.state['rolls'] + [result]
  return result


async def check_prime(nums: list[int]) -> str:
  """Check if a given list of numbers are prime.

  Args:
    nums: The list of numbers to check.

  Returns:
    A str indicating which number is prime.
  """
  primes = set()
  for number in nums:
    number = int(number)
    if number <= 1:
      continue
    is_prime = True
    for i in range(2, int(number**0.5) + 1):
      if number % i == 0:
        is_prime = False
        break
    if is_prime:
      primes.add(number)
  return (
      'No prime numbers found.'
      if not primes
      else f"{', '.join(str(num) for num in primes)} are prime numbers."
  )


root_agent = Agent(
    model='gemini-2.0-flash',
    name='hello_world_agent',
    description=(
        'hello world agent that can roll a dice of 8 sides and check prime'
        ' numbers.'
    ),
    instruction="""
      You roll dice and answer questions about the outcome of the dice rolls.
      You can roll dice of different sizes.
      You can use multiple tools in parallel by calling functions in parallel(in one request and in one round).
      It is ok to discuss previous dice roles, and comment on the dice rolls.
      When you are asked to roll a die, you must call the roll_die tool with the number of sides. Be sure to pass in an integer. Do not pass in a string.
      You should never roll a die on your own.
      When checking prime numbers, call the check_prime tool with a list of integers. Be sure to pass in a list of integers. You should never pass in a string.
      You should not check prime numbers before calling the tool.
      When you are asked to roll a die and check prime numbers, you should always make the following two function calls:
      1. You should first call the roll_die tool to get a roll. Wait for the function response before calling the check_prime tool.
      2. After you get the function response from roll_die tool, you should call the check_prime tool with the roll_die result.
        2.1 If user asks you to check primes based on previous rolls, make sure you include the previous rolls in the list.
      3. When you respond, you must include the roll_die result from step 1.
      You should always perform the previous 3 steps when asking for a roll and checking prime numbers.
      You should not rely on the previous history on prime results.
    """,
    tools=[
        roll_die,
        check_prime,
    ],
    generate_content_config=types.GenerateContentConfig(
        safety_settings=[
            types.SafetySetting(  # avoid false alarm about rolling dice.
                category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
                threshold=types.HarmBlockThreshold.OFF,
            ),
        ]
    ),
)

xuanyang15 avatar Jul 07 '25 17:07 xuanyang15

I tried with the following simple example and I cannot reproduce the error, so I suspect the error you saw was caused by some race conditions, for example, your application might be processing multiple events for the same session concurrently, leading to a race condition where an older session object is used to update the state.

If it is not easy to share a minimal runnable example, could you please let me know how I might modify my following test code to reproduce the error?

folder tree

├── hello_world
│   ├── agent.py
│   └── __init__.py
├── main.py
└── test.py

main.py

from google.adk.cli.fast_api import get_fast_api_app
import uvicorn

# session_service_url = "sqlite:///./sessions.db"
session_service_url = "mysql+pymysql://root:[email protected]:3306/sessions"

app = get_fast_api_app(
    agents_dir=".",
    session_service_uri=session_service_url,
    allow_origins=["*"],
    web=True,
    trace_to_cloud=False,
)

if __name__ == "__main__":
  config = uvicorn.Config(
      "main:app",
      log_level="info",
      port=8080,
      reload=True,
      # Disable Uvicorn's default logging config
      log_config=None,
  )
  server = uvicorn.Server(config)
  server.run()

test.py

from typing import Any
import requests

APP_NAME = "hello_world"
USER_ID = "user"

BASE_URL = "http://localhost:8080"

headers = {}


def get_request(
    url: str, params: dict[str, Any] | None = None
) -> dict[str, Any]:
  if params is None:
    params = {}
  response = requests.get(
      BASE_URL + url, headers=headers, params=params, timeout=60
  )
  response.raise_for_status()
  return response.json()


def post_request(url: str, payload: Any) -> dict[str, Any]:
  response = requests.post(
      BASE_URL + url, headers=headers, json=payload, timeout=60
  )
  response.raise_for_status()
  return response.json()


if __name__ == "__main__":
  print("list-app:", get_request("/list-apps"))

  # request = requests.post(
  #     "http://localhost:8080/apps/test-app/users/test-user/sessions",
  #     json={
  #         "app_name": "test-app",
  #         "user_id": "test-user",
  #     },
  # )
  # print("Created a new session")

  print(
      "list-sessions:",
      get_request(f"/apps/{APP_NAME}/users/{USER_ID}/sessions"),
  )

  print(
      "run:",
      post_request(
          "/run",
          {
              "appName": "hello_world",
              "userId": "user",
              "sessionId": "94c095a0-5379-421d-ae93-3673200d9ee5",
              "newMessage": {
                  "parts": [{"text": "Roll a 10 sided dice"}],
                  "role": "user",
              },
              "streaming": False,
          },
      ),
  )

agent.py

import random

from google.adk import Agent
from google.adk.tools.tool_context import ToolContext
from google.genai import types


def roll_die(sides: int, tool_context: ToolContext) -> int:
  """Roll a die and return the rolled result.

  Args:
    sides: The integer number of sides the die has.

  Returns:
    An integer of the result of rolling the die.
  """
  result = random.randint(1, sides)
  if not 'rolls' in tool_context.state:
    tool_context.state['rolls'] = []

  tool_context.state['rolls'] = tool_context.state['rolls'] + [result]
  return result


async def check_prime(nums: list[int]) -> str:
  """Check if a given list of numbers are prime.

  Args:
    nums: The list of numbers to check.

  Returns:
    A str indicating which number is prime.
  """
  primes = set()
  for number in nums:
    number = int(number)
    if number <= 1:
      continue
    is_prime = True
    for i in range(2, int(number**0.5) + 1):
      if number % i == 0:
        is_prime = False
        break
    if is_prime:
      primes.add(number)
  return (
      'No prime numbers found.'
      if not primes
      else f"{', '.join(str(num) for num in primes)} are prime numbers."
  )


root_agent = Agent(
    model='gemini-2.0-flash',
    name='hello_world_agent',
    description=(
        'hello world agent that can roll a dice of 8 sides and check prime'
        ' numbers.'
    ),
    instruction="""
      You roll dice and answer questions about the outcome of the dice rolls.
      You can roll dice of different sizes.
      You can use multiple tools in parallel by calling functions in parallel(in one request and in one round).
      It is ok to discuss previous dice roles, and comment on the dice rolls.
      When you are asked to roll a die, you must call the roll_die tool with the number of sides. Be sure to pass in an integer. Do not pass in a string.
      You should never roll a die on your own.
      When checking prime numbers, call the check_prime tool with a list of integers. Be sure to pass in a list of integers. You should never pass in a string.
      You should not check prime numbers before calling the tool.
      When you are asked to roll a die and check prime numbers, you should always make the following two function calls:
      1. You should first call the roll_die tool to get a roll. Wait for the function response before calling the check_prime tool.
      2. After you get the function response from roll_die tool, you should call the check_prime tool with the roll_die result.
        2.1 If user asks you to check primes based on previous rolls, make sure you include the previous rolls in the list.
      3. When you respond, you must include the roll_die result from step 1.
      You should always perform the previous 3 steps when asking for a roll and checking prime numbers.
      You should not rely on the previous history on prime results.
    """,
    tools=[
        roll_die,
        check_prime,
    ],
    generate_content_config=types.GenerateContentConfig(
        safety_settings=[
            types.SafetySetting(  # avoid false alarm about rolling dice.
                category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
                threshold=types.HarmBlockThreshold.OFF,
            ),
        ]
    ),
)

main.py

app = get_fast_api_app(
    agents_dir="./sql_agent",
    session_service_uri=session_mysql_url,
    allow_origins=["*"],
    web=False,
    trace_to_cloud=False,
)

I used this shell script to start project

uvicorn main:app --workers 4 --host 0.0.0.0 

the workers param setting is 4, I guess cased by this

CodyTonn avatar Jul 08 '25 05:07 CodyTonn

@code2tan please share the contents under sql_agent folder for us to reproduce and debug.

seanzhou1023 avatar Jul 08 '25 16:07 seanzhou1023

@seanzhou1023 Thanks for looking into this issue! I just reproduced the error with my above code. Here are the steps:

  1. Started the server by running uvicorn main:app --workers 4 --host 0.0.0.0
  2. Call /run api twice at roughly the same time on the same session id Image
  3. Saw the error ValueError: The last_update_time provided in the session object '2025-07-08 16:55:47' is earlier than the update_time in the storage_session '2025-07-08 16:57:11'. Please check if it is a stale session.`

Actually, even if we use --workers 1, this error can still happen, because the requests are handled asynchronously anyway, as lone as the first request is awaiting some IO, the server will work on the second request.


@code2tan Could you please check if you have similar simultaneous requests on the same session id when you interact with the server? Is it intentional?

xuanyang15 avatar Jul 08 '25 17:07 xuanyang15

@xuanyang15 any update the issue still exists for me, if i call simultaneous /un api

akshatshaw avatar Jul 28 '25 13:07 akshatshaw

@akshatshaw Thanks for letting us know you have the same problem! We were waiting for @code2tan to confirm the root cause. Could you please confirm if the issue is caused by calling the api multiple times on the session id simultaneously? If so, could you please help us understand the use case for this simultaneous calls on the same session id?

xuanyang15 avatar Jul 28 '25 16:07 xuanyang15

@xuanyang15 I am building a whatsapp based chat agent, in which when using the InMemorySessionService() simultaneously multiple messages works completely fine, but when using the DatabaseSessionService(SQLITE_URL) this is issue arises.

This is the issue to be exact and after this the session becomes useless and have to create a new session: Error processing request: The last_update_time provided in the session object '2025-07-27 11:47:33' is earlier than the update_time in the storage_session '2025-07-27 11:47:34'. Please check if it is a stale session.

akshatshaw avatar Jul 28 '25 20:07 akshatshaw

@akshatshaw Thanks for the information! I don't think we support having multiple threads competing on the same session simultaneously (a session is supposed to be used by one thread only, sessions are typically stateful and are not designed to be thread-safe, same as ADK session), which is one of the reasons we added the check (which raises the error you see).

As for why you didn't see the same error when using InMemorySessionService, InMemorySessionService is supposed to be used for prototyping and testing, we didn't add the session.update_timestamp check for it.

xuanyang15 avatar Jul 28 '25 22:07 xuanyang15

Same problem..Happens when I use MySQL DB for session service uri

Directly abandon the ADK framework and opt for LangGraph, which offers better support

CodyTonn avatar Aug 02 '25 15:08 CodyTonn

@akshatshaw Thanks for the information! I don't think we support having multiple threads competing on the same session simultaneously (a session is supposed to be used by one thread only, sessions are typically stateful and are not designed to be thread-safe, same as ADK session), which is one of the reasons we added the check (which raises the error you see).

As for why you didn't see the same error when using InMemorySessionService, InMemorySessionService is supposed to be used for prototyping and testing, we didn't add the session.update_timestamp check for it.

Hi @xuanyang15 : I’m running into a similar issue when users try to send multiple messages in the same session, because my app has a fairly long thinking time. Is there a way to fix this, or will ADK not support it in the near future?

hung12ct avatar Aug 21 '25 02:08 hung12ct

Hi @hung12ct We don't have existing plant to support it, but do you mind creating a feature request for this? I can follow up with the team and see how to support it. We can also talk about alternatives according to you needs in the feature request.

xuanyang15 avatar Aug 21 '25 03:08 xuanyang15

@xuanyang15 : I think it has the same feature as this request: https://github.com/google/adk-python/issues/1049. Can you take a look? I think it’s similar to this feature in ChatGPT:

Image

hung12ct avatar Aug 21 '25 03:08 hung12ct

I have the same issue here, i just called /run once.

mengjiaowang avatar Sep 09 '25 15:09 mengjiaowang

@mengjiaowang Thanks for pointing that out! Do you have a minimal running example for me to reproduce it with only one /run call?

xuanyang15 avatar Sep 09 '25 17:09 xuanyang15

For quick reproducibility: When running Google ADK with a database, if you send two messages before the LLM responds, a race condition occurs.

The last_update_time provided in the session object '2025-07-01 18:59:42' is earlier than the update_time in the storage_session '2025-07-01 18:59:56'. Please check if it is a stale session.

One idea to avoid this issue is to manage messages properly. Suppose I receive two messages at the same time. If I handle messages in a queue, the LLM might respond to the second message first, which would not make sense given the context of the first response. For example, if the user sends two messages in quick succession: 1st message: Hi, how are you? I wanted one of these. 2nd message: Roller car.

In this case, if messages are queued, the LLM might ask which product the user wants, but the second message already specifies it. This would result in a poor user experience, as the user would feel they only asked one question, but the LLM responded twice.

If I group messages before sending them to the LLM, waiting a short period (e.g., 1-5 seconds) to see if more messages from the same user arrive in quick succession, it will increase the perceived delay for the user and also have same issue if LLM take longer than the allotted time to respond.

The solution:

Instead of waiting 5 seconds, the LLM starts processing the first message and records in the database that it is processing, using a process ID for that user. If a new message arrives before the processing is finished or the response is sent, the ADK uses the process ID to cancel and discard the first request. Then, it sends both messages together to the LLM to process the final response. It is important to implement a feedback mechanism in case a second message arrives. This could be something like an await_processing_message, where the developer sets a default message that is sent to the user while the LLM processes the second message. This would prevent an infinite loop without a response.

magarafael avatar Oct 21 '25 18:10 magarafael

adk_version = "1.13.0"

I've been investigating this "stale session" error and believe I've identified the root cause by examining the ADK runner's run_async method.

Root Cause Analysis

The issue occurs within a single request execution in the run_async method. Looking at the runners.py code:

  1. Line 205-207: session = await self.session_service.get_session(...) - Gets the session once at the beginning
  2. Line 280-283: await self.session_service.append_event(session=session, event=early_exit_event) - First append using the original session
  3. Line 290-292: await self.session_service.append_event(session=session, event=event) - Multiple appends throughout execution using the same stale session object

The problem is that the runner fetches the session once at the beginning and then reuses that same session object for multiple append operations throughout the execution. Each append_event call modifies the session in storage, but the local session object in the runner remains stale.

So when the second, third, or subsequent append_event calls happen, they're still using the original session object with the old last_update_time, while the storage has been updated by previous append operations.

Proposed Solution: Session Refresh Before Each Append

I created a custom session service that inherits from the base session service and modifies the append_event method to refresh the session before appending:

class RefreshedSessionService(BaseSessionService):
    def __init__(self, session_service: BaseSessionService):
        self.session_service = session_service

    async def append_event(self, session: Session, event: Event) -> Event:
        """Append event with session refresh to prevent stale session errors."""
        # Refresh the session before appending to get the latest state
        fresh_session = await self.session_service.get_session(
            app_name=session.app_name,
            user_id=session.user_id,
            session_id=session.id
        )
        
        if refreshed_session:
            session.last_update_time = fresh_session.last_update_time
            session.events = fresh_session.events
            session.state = fresh_session.state
        
        # Use the refreshed session for the append operation
        return await self.session_service.append_event(session, event)

Why This Should Work

  1. Addresses Single-Request Issue: Ensures each append operation uses the latest session state
  2. Minimal Performance Impact: Only refreshes when actually appending events
  3. No Runner Changes: Works within the existing ADK architecture
  4. Backward Compatible: No changes needed to existing ADK code

Questions for the Team (@xuanyang15)

  1. Does this analysis align with what you're seeing in the stale session errors?
  2. Would refreshing the session before each append be an acceptable solution?
  3. Are there any concerns about the performance impact of additional get_session calls?

I'm currently testing this solution and would appreciate your thoughts on whether this addresses the core issue.

dennisgera avatar Oct 29 '25 13:10 dennisgera