Skip to content

BufferedSessionService replays an equal event into the live session after a newer update #8497

Description

@OUAO-FRANK

Required Information

Describe the Bug: Wrapping an InMemorySessionService in BufferedSessionService changes what a caller sees when it retries an equal event. The backing store correctly ignores the retry, but the buffered service appends the event to the caller's live Session and reapplies its old state delta. A caller that keeps using that Session can take the next step from stale state even after a successful flush.

Steps to Reproduce:

  1. Use an ADK checkout at 60cef52f992ca507f4ce3dbbae6e591627c1c0e0 with its runtime dependencies installed, for example via uv sync --no-dev.
  2. Save the script below as repro.py at the repository root and run uv run --no-sync python -B repro.py.
  3. The script appends an event setting status=pending, then a newer event setting status=complete, then an equal copy of the first event. It compares the original session object with a fresh read after flushing.

Expected Behavior: With this delegate, an equal redelivery should leave both views at [first, second] and status=complete, matching the direct in-memory service. A distinct third event should still be applied normally.

Observed Behavior: Buffering leaves the original session at [first, second, first] and status=pending. The fresh read returns [first, second] and status=complete. This occurs with one flush or a flush after each append.

Environment Details: ADK 2.15.1 from the main commit above, Windows 11, CPython 3.12.13. BufferedSessionService is experimental.

Model Information: LiteLLM: No. Model: N/A. The script uses both actual session services and needs no credentials, external database, or model calls.

Optional Information

Frequency / Controls: Both buffered retry cases reproduced in all three runs. All four controls per run passed: direct retries, and genuine new events in each mode.

Additional Context: BufferedSessionService.append_event applies the event to the live object before the delegate processes it. The in-memory delegate later deduplicates the event. The buffered completion path copies the storage version, leaving the live history and state already modified. The result is a live-session mismatch. #8143 and PR #8144 concern deduplication failing in the underlying store when an event contains temporary state. The present case uses ordinary state and the underlying store deduplicates it. #7454 concerns a second session object that had never received the event. The present case reuses one session object that already holds it. The reproduction models an application retrying a service call. The standard Runner does not redeliver events during normal execution.

AI disclosure: OpenAI Codex assisted with source tracing, the offline reproducer, and drafting this report.

Minimal Reproduction Code:

import asyncio
from pathlib import Path
import sys

sys.path.insert(0, str(Path.cwd() / "src"))

from google.adk.events.event import Event
from google.adk.events.event_actions import EventActions
from google.adk.sessions import BufferedSessionService, InMemorySessionService
from google.genai import types


def event(event_id, value):
    return Event(
        id=event_id,
        author="agent",
        invocation_id="turn",
        actions=EventActions(state_delta={"status": value}),
        content=types.Content(role="model", parts=[types.Part(text=value)]),
    )


def observed(session):
    return [e.id for e in session.events], session.state["status"]


async def run(mode, equal_retry):
    key = dict(app_name="example", user_id="tester", session_id="test")
    store = InMemorySessionService()
    service = store if mode == "direct" else BufferedSessionService(store)
    try:
        session = await service.create_session(**key)
        early = event("first", "pending")
        later = event("second", "complete")
        for next_event in (
            early,
            later,
            early.model_copy(deep=True) if equal_retry else event("third", "pending"),
        ):
            await service.append_event(session, next_event)
            if mode == "buffered_separate_flush":
                await service.flush_session(**key)
        await service.flush_session(**key)
        return observed(session), observed(await service.get_session(**key))
    finally:
        if isinstance(service, BufferedSessionService):
            await service.aclose()


async def main():
    wanted = (["first", "second"], "complete")
    distinct = (["first", "second", "third"], "pending")
    failures = 0
    for mode in ("direct", "buffered_one_flush", "buffered_separate_flush"):
        for retry in (True, False):
            live, stored = await run(mode, retry)
            print(f"{mode} retry={retry} live={live!r} stored={stored!r}")
            expected = wanted if retry else distinct
            failures += live != expected or stored != expected
    assert failures == 0, f"{failures} of 6 cases had unexpected state/history"


if __name__ == "__main__":
    asyncio.run(main())

Activity

  1. added
    services
    on Dec 4, 2026
  2. vidhvath28 commented on Dec 4, 2026

    @vidhvath28

    Ran the repro on current main (84e103b) and got the same result, the live session ends up as [first, second, first] with status=pending.

    BufferedSessionService._apply_to_live_session doesn't have the equal-event check that InMemorySessionService.append_event has, so the retry gets appended and its delta reapplied before the store ever sees it. The store then drops it, and _sync_live_session only copies the version back, so nothing fixes up the live session afterwards.

    What I'm thinking: before applying, skip it if session.events already has an event with the same id that's equal to the temp-trimmed snapshot. That's the same rule InMemory uses, so two different events that just share an id both still go through. I'd still queue the write and let the store decide, so a failed earlier write gets reported the same way as now. Comparing against the snapshot instead of the raw event also sidesteps the temp: mismatch from #8143.

    Tried it locally: all 6 cases in the repro pass and the existing buffered session tests still pass. Added two tests, one for an equal redelivery being a no-op and one for a same-id event with different content still being applied.

    Happy to open a PR if this sounds right. One question: would you rather not queue the write at all for a duplicate? Saves a round trip, but then it only matches the store if the store would have deduped it too.

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

Metadata

Metadata

Assignees

Labels

services

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions