feat: Add rewind_async to support rewinding the session to before a previous invocation

PiperOrigin-RevId: 820552460
This commit is contained in:
Shangjie Chen
2025-10-16 23:24:40 -07:00
committed by Copybara-Service
parent 307896aece
commit 9dce06f9b0
11 changed files with 830 additions and 4 deletions
@@ -0,0 +1,109 @@
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for artifact_util."""
from google.adk.artifacts import artifact_util
from google.genai import types
import pytest
def test_parse_session_scoped_artifact_uri():
"""Tests parsing a valid session-scoped artifact URI."""
uri = "artifact://apps/app1/users/user1/sessions/session1/artifacts/file1/versions/123"
parsed = artifact_util.parse_artifact_uri(uri)
assert parsed is not None
assert parsed.app_name == "app1"
assert parsed.user_id == "user1"
assert parsed.session_id == "session1"
assert parsed.filename == "file1"
assert parsed.version == 123
def test_parse_user_scoped_artifact_uri():
"""Tests parsing a valid user-scoped artifact URI."""
uri = "artifact://apps/app2/users/user2/artifacts/file2/versions/456"
parsed = artifact_util.parse_artifact_uri(uri)
assert parsed is not None
assert parsed.app_name == "app2"
assert parsed.user_id == "user2"
assert parsed.session_id is None
assert parsed.filename == "file2"
assert parsed.version == 456
@pytest.mark.parametrize(
"invalid_uri",
[
"http://example.com",
"artifact://invalid",
"artifact://app1/user1/sessions/session1/artifacts/file1",
"artifact://apps/app1/users/user1/sessions/session1/artifacts/file1",
"artifact://apps/app1/users/user1/artifacts/file1",
],
)
def test_parse_invalid_artifact_uri(invalid_uri):
"""Tests parsing invalid artifact URIs."""
assert artifact_util.parse_artifact_uri(invalid_uri) is None
def test_get_session_scoped_artifact_uri():
"""Tests constructing a session-scoped artifact URI."""
uri = artifact_util.get_artifact_uri(
app_name="app1",
user_id="user1",
session_id="session1",
filename="file1",
version=123,
)
assert (
uri
== "artifact://apps/app1/users/user1/sessions/session1/artifacts/file1/versions/123"
)
def test_get_user_scoped_artifact_uri():
"""Tests constructing a user-scoped artifact URI."""
uri = artifact_util.get_artifact_uri(
app_name="app2", user_id="user2", filename="file2", version=456
)
assert uri == "artifact://apps/app2/users/user2/artifacts/file2/versions/456"
def test_is_artifact_ref_true():
"""Tests is_artifact_ref with a valid artifact reference."""
artifact = types.Part(
file_data=types.FileData(
file_uri="artifact://apps/a/u/s/f/v/1", mime_type="text/plain"
)
)
assert artifact_util.is_artifact_ref(artifact) is True
@pytest.mark.parametrize(
"part",
[
types.Part(text="hello"),
types.Part(inline_data=types.Blob(data=b"123", mime_type="text/plain")),
types.Part(
file_data=types.FileData(
file_uri="http://example.com", mime_type="text/plain"
)
),
types.Part(),
],
)
def test_is_artifact_ref_false(part):
"""Tests is_artifact_ref with non-reference parts."""
assert artifact_util.is_artifact_ref(part) is False
@@ -324,6 +324,63 @@ async def test_confirmation_events_are_filtered():
]
@pytest.mark.asyncio
async def test_rewind_events_are_filtered_out():
"""Test that events are filtered based on rewind action."""
agent = Agent(model="gemini-2.5-flash", name="test_agent")
llm_request = LlmRequest(model="gemini-2.5-flash")
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
events = [
Event(
invocation_id="inv1",
author="user",
content=types.UserContent("First message"),
),
Event(
invocation_id="inv1",
author="test_agent",
content=types.ModelContent("First response"),
),
Event(
invocation_id="inv2",
author="user",
content=types.UserContent("Second message"),
),
Event(
invocation_id="inv2",
author="test_agent",
content=types.ModelContent("Second response"),
),
Event(
invocation_id="rewind_inv",
author="test_agent",
actions=EventActions(rewind_before_invocation_id="inv2"),
),
Event(
invocation_id="inv3",
author="user",
content=types.UserContent("Third message"),
),
]
invocation_context.session.events = events
# Process the request
async for _ in contents.request_processor.run_async(
invocation_context, llm_request
):
pass
# Verify rewind correctly filters conversation history
assert llm_request.contents == [
types.UserContent("First message"),
types.ModelContent("First response"),
types.UserContent("Third message"),
]
@pytest.mark.asyncio
async def test_events_with_empty_content_are_skipped():
"""Test that events with empty content (state-only changes) are skipped."""
@@ -0,0 +1,248 @@
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for runner.rewind_async."""
from google.adk.agents.base_agent import BaseAgent
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
from google.adk.events.event import Event
from google.adk.events.event import EventActions
from google.adk.runners import Runner
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.genai import types
import pytest
class TestRunnerRewind:
"""Tests for runner.rewind_async."""
runner: Runner
def setup_method(self):
"""Set up test fixtures."""
root_agent = BaseAgent(name="test_agent")
session_service = InMemorySessionService()
artifact_service = InMemoryArtifactService()
self.runner = Runner(
app_name="test_app",
agent=root_agent,
session_service=session_service,
artifact_service=artifact_service,
)
@pytest.mark.asyncio
async def test_rewind_async_with_state_and_artifacts(self):
"""Tests rewind_async rewinds state and artifacts."""
runner = self.runner
user_id = "test_user"
session_id = "test_session"
# 1. Setup session and initial artifacts
session = await runner.session_service.create_session(
app_name=runner.app_name, user_id=user_id, session_id=session_id
)
# invocation1
await runner.artifact_service.save_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f1",
artifact=types.Part.from_text(text="f1v0"),
)
event1 = Event(
invocation_id="invocation1",
author="agent",
content=types.Content(parts=[types.Part.from_text(text="event1")]),
actions=EventActions(
state_delta={"k1": "v1"}, artifact_delta={"f1": 0}
),
)
await runner.session_service.append_event(session=session, event=event1)
# invocation2
await runner.artifact_service.save_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f1",
artifact=types.Part.from_text(text="f1v1"),
)
await runner.artifact_service.save_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f2",
artifact=types.Part.from_text(text="f2v0"),
)
event2 = Event(
invocation_id="invocation2",
author="agent",
content=types.Content(parts=[types.Part.from_text(text="event2")]),
actions=EventActions(
state_delta={"k1": "v2", "k2": "v2"},
artifact_delta={"f1": 1, "f2": 0},
),
)
await runner.session_service.append_event(session=session, event=event2)
# invocation3
event3 = Event(
invocation_id="invocation3",
author="agent",
content=types.Content(parts=[types.Part.from_text(text="event3")]),
actions=EventActions(state_delta={"k2": "v3"}),
)
await runner.session_service.append_event(session=session, event=event3)
session = await runner.session_service.get_session(
app_name=runner.app_name, user_id=user_id, session_id=session_id
)
assert session.state == {"k1": "v2", "k2": "v3"}
assert await runner.artifact_service.load_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f1",
) == types.Part.from_text(text="f1v1")
assert await runner.artifact_service.load_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f2",
) == types.Part.from_text(text="f2v0")
# 2. Rewind before invocation2
await runner.rewind_async(
user_id=user_id,
session_id=session_id,
rewind_before_invocation_id="invocation2",
)
# 3. Verify state and artifacts are rewinded
session = await runner.session_service.get_session(
app_name=runner.app_name, user_id=user_id, session_id=session_id
)
# After rewind before invocation2, only event1 state delta should apply.
assert session.state["k1"] == "v1"
assert not session.state["k2"]
# f1 should be rewinded to v0
assert await runner.artifact_service.load_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f1",
) == types.Part.from_text(text="f1v0")
# f2 should not exist
assert (
await runner.artifact_service.load_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f2",
)
is None
)
@pytest.mark.asyncio
async def test_rewind_async_not_first_invocation(self):
"""Tests rewind_async rewinds state and artifacts to invocation2."""
runner = self.runner
user_id = "test_user"
session_id = "test_session"
# 1. Setup session and initial artifacts
session = await runner.session_service.create_session(
app_name=runner.app_name, user_id=user_id, session_id=session_id
)
# invocation1
await runner.artifact_service.save_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f1",
artifact=types.Part.from_text(text="f1v0"),
)
event1 = Event(
invocation_id="invocation1",
author="agent",
content=types.Content(parts=[types.Part.from_text(text="event1")]),
actions=EventActions(
state_delta={"k1": "v1"}, artifact_delta={"f1": 0}
),
)
await runner.session_service.append_event(session=session, event=event1)
# invocation2
await runner.artifact_service.save_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f1",
artifact=types.Part.from_text(text="f1v1"),
)
await runner.artifact_service.save_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f2",
artifact=types.Part.from_text(text="f2v0"),
)
event2 = Event(
invocation_id="invocation2",
author="agent",
content=types.Content(parts=[types.Part.from_text(text="event2")]),
actions=EventActions(
state_delta={"k1": "v2", "k2": "v2"},
artifact_delta={"f1": 1, "f2": 0},
),
)
await runner.session_service.append_event(session=session, event=event2)
# invocation3
event3 = Event(
invocation_id="invocation3",
author="agent",
content=types.Content(parts=[types.Part.from_text(text="event3")]),
actions=EventActions(state_delta={"k2": "v3"}),
)
await runner.session_service.append_event(session=session, event=event3)
# 2. Rewind before invocation3
await runner.rewind_async(
user_id=user_id,
session_id=session_id,
rewind_before_invocation_id="invocation3",
)
# 3. Verify state and artifacts are rewinded
session = await runner.session_service.get_session(
app_name=runner.app_name, user_id=user_id, session_id=session_id
)
# After rewind before invocation3, event1 and event2 state deltas should apply.
assert session.state == {"k1": "v2", "k2": "v2"}
# f1 should be v1
assert await runner.artifact_service.load_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f1",
) == types.Part.from_text(text="f1v1")
# f2 should be v0
assert await runner.artifact_service.load_artifact(
app_name=runner.app_name,
user_id=user_id,
session_id=session_id,
filename="f2",
) == types.Part.from_text(text="f2v0")