Skip to content

Session state not restored when using SQLite persistence in BIDI demo #3573

Closed

Description

@quantexperts

Hi folks,

I'm new to ADK and am trying to replicate the BIDI demos using SQLite for persistence.
Specifically, I'm working with the sample at:
https://github.com/google/adk-samples/tree/main/python/agents/bidi-demo

To test persistence, I configured SQLite and temporarily hard-coded the user_id and session_id inside the WebSocket endpoint:

from google.adk.sessions import DatabaseSessionService

db_url = "sqlite:///./adk_sessions.db"
session_service = DatabaseSessionService(db_url=db_url)

@app.websocket("/ws/{user_id}/{session_id}")
async def websocket_endpoint(websocket: WebSocket, user_id: str, session_id: str) -> None:
    """WebSocket endpoint for bidirectional streaming with ADK."""
    user_id = "user_123"
    session_id = "session_123"
    logger.debug(f"WebSocket connection request: user_id={user_id}, session_id={session_id}")
    await websocket.accept()
    logger.debug("WebSocket connection accepted")
    # rest of the code...

My expectation is that if I reconnect to the WebSocket (with the same hardcoded user and session IDs), the session should be restored and previous conversation context should be loaded automatically.

However, this does not seem to be happening—each reconnection starts a completely fresh conversation, even though I see rows written to the events table in the SQLite DB.

So I'm unsure whether the session is being saved correctly, or whether it is being loaded but not applied.
Could you clarify:

  1. Does the BIDI demo automatically restore conversation state when a session ID is reused?
  2. Is any additional configuration required for DatabaseSessionService when using SQLite?
  3. Which tables/columns should I inspect to verify that session and conversation state are actually being persisted?

Any guidance would be greatly appreciated!

Activity

  1. added
    services[Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc
    on Nov 16, 2025
  2. added theissue type on Nov 16, 2025
  3. quantexperts commented on Nov 17, 2025

    @quantexperts
    Author

    I started with a completely clean SQLite DB, launched the server, and opened a WebSocket connection using a fixed user_id and session_id.

    Then I tested persistence with this sequence:

    1. I said: “My favourite color is Blue.”

    2. The agent correctly responded:
      → “Blue is a great choice!…”

    3. I then restarted the server (without deleting the database).

    4. On reconnect, the server logs show:

      Loaded existing session with 32 events.
      

      So the events are being stored and loaded successfully.

    5. I then asked: “What is my favourite color?”

    6. But the agent replied:
      → “I don’t know your favorite color. Can you tell me what it is?”

    So even though the stored events were loaded from SQLite, the agent is not able to recall anything from earlier in the conversation.

    I suspect I may be misunderstanding how conversational memory is supposed to work in ADK. My assumption was:

    • If DatabaseSessionService restores the previous session’s events,
    • And LlmAgent.include_contents defaults to "default",
    • Then the restored history should be included in the prompt automatically,
    • And therefore the agent should remember earlier user messages.

    Is there an additional step required for the agent to use restored session state as prompt context?

    I tried the same approach with a normal setup (without BIDI) and it works fine. So I am confused why in case of BIDI, it is not working in the same way.

    Any guidance on what I’m missing would be greatly appreciated — especially since the session is loading correctly but the agent still behaves as if it’s a fresh conversation.

  4. DeanChensj commented on Nov 19, 2025

    @DeanChensj
    Collaborator

    Hi @quantexperts , does your sqlite session persist when you test with non-bidi agents?

  5. surajksharma07 commented on Nov 19, 2025

    @surajksharma07
    Collaborator

    @quantexperts events are loading but the conversation history isn't being reconstructed in BIDI mode.
    In your WebSocket endpoint, after calling get_session() and get_events(), you need to explicitly build the conversation history by iterating through the events and extracting the Content objects (filtering for "user" and "model" roles), then combine this history with new messages before passing to the agent.
    This reconstruction happens automatically in non-BIDI mode but needs to be done explicitly in BIDI WebSocket handlers.
    Thanks!

  6. quantexperts commented on Nov 19, 2025

    @quantexperts
    Author

    @surajksharma07 Thanks for your suggestions.
    I am having trouble understanding how the data is saved in the database in case of BIDI.

    When I inspect the event object, I see the output like this and I cant figure out how to extract the user and agent text. This works in non BIDI mode.

        # Get or create session (handles both new sessions and reconnections)
        session = await session_service.get_session(
            app_name=APP_NAME,
            user_id=user_id,
            session_id=session_id
        )
        if session:
            print(f"Loaded existing session with {len(session.events)} events.")
        if not session:
            await session_service.create_session(
                app_name=APP_NAME,
                user_id=user_id,
                session_id=session_id
            )
        events = getattr(session, 'events', [])
        for event in events:
            print(f"--- Replaying event {event}")
    
        live_request_queue = LiveRequestQueue()
    

    In the logs, the output_transcription fields are empty.

    INFO:     127.0.0.1:63043 - "WebSocket /ws/demo-user/demo-session-o5uag" [accepted]
    Loaded existing session with 14 events.
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='e3e45bcf-ba32-464b-adcc-9566f523a3f2' timestamp=1763591464.758228
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=GenerateContentResponseUsageMetadata(
      prompt_token_count=1753,
      prompt_tokens_details=[
        ModalityTokenCount(
          modality=<MediaModality.TEXT: 'TEXT'>,
          token_count=1753
        ),
      ],
      total_token_count=1778
    ) live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='5e4fc84b-4f93-4666-aa77-8ee132eaa841' timestamp=1763591465.887902
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=True finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='fb02bf84-b5f6-4e37-8a94-d718d93800c9' timestamp=1763591465.896351
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='ec706962-213b-4860-96c6-43c64d56f9ac' timestamp=1763591472.887949
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='1b6fd894-be57-401c-a426-7a9c75f68ed3' timestamp=1763591473.074558
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='9d8e66af-a634-4076-a132-690a58910aab' timestamp=1763591473.203803
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='0e1b8b44-8715-41fd-8d7c-d59465109fa3' timestamp=1763591473.317096
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='bea180d0-24ad-4ce0-8de4-de5e6cf393f1' timestamp=1763591473.541057
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='b79745fc-59f0-4b19-b81b-56cafcbea4d7' timestamp=1763591473.598504
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='401f39d7-5be5-426a-abec-32a69d8b0ad2' timestamp=1763591473.71045
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='f2e52ec4-c177-4a95-8cc2-6079a9d12a03' timestamp=1763591473.902177
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='637b12ac-a92b-4e29-a348-ce2bbcffe87a' timestamp=1763591473.963509
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='38d4349c-b8aa-4e2b-a42a-6f00f9bc85a4' timestamp=1763591474.158333
    --- Replaying event model_version=None content=None grounding_metadata=None partial=None turn_complete=None finish_reason=None error_code=None error_message=None interrupted=None custom_metadata=None usage_metadata=None live_session_resumption_update=None input_transcription=None output_transcription=None avg_logprobs=None logprobs_result=None cache_metadata=None citation_metadata=None invocation_id='e-5b305a5d-9dc1-44ff-960d-2fa5bf0f1633' author='google_search_agent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}, requested_tool_confirmations={}, compaction=None, end_of_agent=None, agent_state=None, rewind_before_invocation_id=None) long_running_tool_ids=set() branch=None id='33e441e3-c11a-4c10-ae9d-32781acdb7ee' timestamp=1763591474.249816
    INFO:     connection open
    

    The screenshot from the database event table:

    Image
  7. surajksharma07 commented on Nov 20, 2025

    @surajksharma07
    Collaborator

    I see the issue - you're using getattr(session, 'events', []) which doesn't properly load events.
    Change it to events = await session.get_events() instead.
    Then filter for content: conversation_history = [event.content for event in events if event.content and event.content.role in ("user", "model")].
    If content is still None after this fix, that indicates a BIDI-specific persistence bug where content isn't being saved to events - in that case, please share your full WebSocket handler code so we can investigate further.

  8. quantexperts commented on Nov 20, 2025

    @quantexperts
    Author

    It says session.get_events() is an invalid method. I couldn't figure out what is the right method

  9. 8 remaining items

  10. added
    need attention[Status] This issue is important but the maintainers haven't started working on it
    and removed
    request clarification[Status] The maintainer need clarification or more information from the author
    on Nov 21, 2025
  11. added
    needs review[Status] The PR/issue is awaiting review from the maintainer
    and removed
    need attention[Status] This issue is important but the maintainers haven't started working on it
    on Dec 6, 2025
  12. surajksharma07 commented on Feb 6, 2026

    @surajksharma07
    Collaborator

    @quantexperts This is a confirmed BIDI-specific persistence bug — user messages aren't being saved into session events in Live/BIDI mode, so there's nothing to replay on reconnection.

    ADK v1.24.0 added history replay infrastructure (contents.py transcription-to-content conversion, send_history() in run_live()), but the root issue remains: user input events are stored with content=None and no transcription data.

    PR #4194 is linked to address this but hasn't been merged yet.

    This issue remains open and we're tracking it.

  13. removed their assignment
    on Feb 26, 2026
  14. added
    request clarification[Status] The maintainer need clarification or more information from the author
    on May 6, 2026
  15. surajksharma07 commented on May 6, 2026

    @surajksharma07
    Collaborator

    @quantexperts Traced through the thread — the content=None behaviour in BIDI/Live mode was addressed in v1.23.0 (commit a04828d: "Persist user input content to session in live mode"), with session replay on reconnect completed in v1.24.0 and further refined in v1.32.0.

    Worth upgrading to v1.23.0+ (ideally v1.32.0) and switching from DatabaseSessionService to SqliteSessionService for SQLite — the dedicated class was introduced in v1.19.0 specifically for this backend:

    session_service = SqliteSessionService(db_path="./adk_sessions.db")

    Could you test on the latest version and confirm whether session history is being restored correctly on reconnect?
    If it's working, happy to close this out!

  16. surajksharma07 commented on May 19, 2026

    @surajksharma07
    Collaborator

    Going ahead and closing this out since we haven't heard back in a couple of weeks — assuming the v1.23.0 upgrade + SqliteSessionService sorted the session persistence issue for you!

    Just to confirm for anyone landing here: the content=None bug for BIDI/live mode user messages was fixed in v1.23.0 (commit a04828d), and SqliteSessionService is available from that version onward as the right persistence layer for live sessions.

    Feel free to reopen if the upgrade didn't fully cover your case or you're seeing something different on v1.23.0+ — happy to dig in further!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

needs review[Status] The PR/issue is awaiting review from the maintainerrequest clarification[Status] The maintainer need clarification or more information from the authorservices[Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions