|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Private helper module for session and artifact rewind in ADK.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import logging |
| 20 | +from typing import Any |
| 21 | +from typing import Awaitable |
| 22 | +from typing import Callable |
| 23 | +from typing import Optional |
| 24 | +from typing import TYPE_CHECKING |
| 25 | + |
| 26 | +from google.genai import types |
| 27 | + |
| 28 | +from ..events.event import Event |
| 29 | +from ..events.event_actions import EventActions |
| 30 | +from ..platform import uuid as platform_uuid |
| 31 | +from ..sessions.base_session_service import BaseSessionService |
| 32 | +from ..sessions.session import Session |
| 33 | + |
| 34 | +if TYPE_CHECKING: |
| 35 | + from ..artifacts.base_artifact_service import BaseArtifactService |
| 36 | + |
| 37 | +logger = logging.getLogger("google_adk." + __name__) |
| 38 | + |
| 39 | + |
| 40 | +async def compute_state_delta_for_rewind( |
| 41 | + session: Session, rewind_event_index: int |
| 42 | +) -> dict[str, Any]: |
| 43 | + """Computes the state delta to reverse changes.""" |
| 44 | + state_at_rewind_point: dict[str, Any] = {} |
| 45 | + for i in range(rewind_event_index): |
| 46 | + if session.events[i].actions.state_delta: |
| 47 | + for k, v in session.events[i].actions.state_delta.items(): |
| 48 | + if k.startswith("app:") or k.startswith("user:"): |
| 49 | + continue |
| 50 | + if v is None: |
| 51 | + state_at_rewind_point.pop(k, None) |
| 52 | + else: |
| 53 | + state_at_rewind_point[k] = v |
| 54 | + |
| 55 | + current_state = session.state |
| 56 | + rewind_state_delta = {} |
| 57 | + |
| 58 | + # 1. Add/update keys in rewind_state_delta to match state_at_rewind_point. |
| 59 | + for key, value_at_rewind in state_at_rewind_point.items(): |
| 60 | + if key not in current_state or current_state[key] != value_at_rewind: |
| 61 | + rewind_state_delta[key] = value_at_rewind |
| 62 | + |
| 63 | + # 2. Set keys to None in rewind_state_delta if they are in current_state |
| 64 | + # but not in state_at_rewind_point. These keys were added after the |
| 65 | + # rewind point and need to be removed. |
| 66 | + for key in current_state: |
| 67 | + if key.startswith("app:") or key.startswith("user:"): |
| 68 | + continue |
| 69 | + if key not in state_at_rewind_point: |
| 70 | + rewind_state_delta[key] = None |
| 71 | + |
| 72 | + return rewind_state_delta |
| 73 | + |
| 74 | + |
| 75 | +async def compute_artifact_delta_for_rewind( |
| 76 | + session: Session, |
| 77 | + rewind_event_index: int, |
| 78 | + *, |
| 79 | + artifact_service: Optional[BaseArtifactService] = None, |
| 80 | + app_name: Optional[str] = None, |
| 81 | +) -> dict[str, int]: |
| 82 | + """Computes the artifact delta to reverse changes.""" |
| 83 | + if not artifact_service: |
| 84 | + return {} |
| 85 | + |
| 86 | + versions_at_rewind_point: dict[str, int] = {} |
| 87 | + for i in range(rewind_event_index): |
| 88 | + event = session.events[i] |
| 89 | + if event.actions.artifact_delta: |
| 90 | + versions_at_rewind_point.update(event.actions.artifact_delta) |
| 91 | + |
| 92 | + current_versions: dict[str, int] = {} |
| 93 | + for event in session.events: |
| 94 | + if event.actions.artifact_delta: |
| 95 | + current_versions.update(event.actions.artifact_delta) |
| 96 | + |
| 97 | + rewind_artifact_delta = {} |
| 98 | + for filename, vn in current_versions.items(): |
| 99 | + if filename.startswith("user:"): |
| 100 | + # User artifacts are not restored on rewind. |
| 101 | + continue |
| 102 | + vt = versions_at_rewind_point.get(filename) |
| 103 | + if vt == vn: |
| 104 | + continue |
| 105 | + |
| 106 | + rewind_artifact_delta[filename] = vn + 1 |
| 107 | + artifact: types.Part |
| 108 | + if vt is None: |
| 109 | + # Artifact did not exist at rewind point. Mark it as inaccessible. |
| 110 | + artifact = types.Part( |
| 111 | + inline_data=types.Blob(mime_type="application/octet-stream", data=b"") |
| 112 | + ) |
| 113 | + else: |
| 114 | + # Artifact version changed after rewind point. Restore to version at |
| 115 | + # rewind point by loading the actual data via the artifact service. |
| 116 | + loaded_artifact = await artifact_service.load_artifact( |
| 117 | + app_name=app_name, |
| 118 | + user_id=session.user_id, |
| 119 | + session_id=session.id, |
| 120 | + filename=filename, |
| 121 | + version=vt, |
| 122 | + ) |
| 123 | + if loaded_artifact is None: |
| 124 | + logger.warning( |
| 125 | + "Artifact %s version %d not found during rewind for" |
| 126 | + " session %s. Replacing with empty data.", |
| 127 | + filename, |
| 128 | + vt, |
| 129 | + session.id, |
| 130 | + ) |
| 131 | + artifact = types.Part( |
| 132 | + inline_data=types.Blob( |
| 133 | + mime_type="application/octet-stream", data=b"" |
| 134 | + ) |
| 135 | + ) |
| 136 | + else: |
| 137 | + artifact = loaded_artifact |
| 138 | + await artifact_service.save_artifact( |
| 139 | + app_name=app_name, |
| 140 | + user_id=session.user_id, |
| 141 | + session_id=session.id, |
| 142 | + filename=filename, |
| 143 | + artifact=artifact, |
| 144 | + ) |
| 145 | + |
| 146 | + return rewind_artifact_delta |
| 147 | + |
| 148 | + |
| 149 | +async def rewind_session( |
| 150 | + *, |
| 151 | + session_service: BaseSessionService, |
| 152 | + session: Session, |
| 153 | + rewind_before_invocation_id: str, |
| 154 | + artifact_service: Optional[BaseArtifactService] = None, |
| 155 | + app_name: Optional[str] = None, |
| 156 | + compute_state_delta: Optional[ |
| 157 | + Callable[[Session, int], Awaitable[dict[str, Any]]] |
| 158 | + ] = None, |
| 159 | + compute_artifact_delta: Optional[ |
| 160 | + Callable[[Session, int], Awaitable[dict[str, int]]] |
| 161 | + ] = None, |
| 162 | +) -> None: |
| 163 | + """Rewinds the session to before the specified invocation.""" |
| 164 | + rewind_event_index = -1 |
| 165 | + for i, event in enumerate(session.events): |
| 166 | + if event.invocation_id == rewind_before_invocation_id: |
| 167 | + rewind_event_index = i |
| 168 | + break |
| 169 | + |
| 170 | + if rewind_event_index == -1: |
| 171 | + raise ValueError(f"Invocation ID not found: {rewind_before_invocation_id}") |
| 172 | + |
| 173 | + # Compute state delta to reverse changes |
| 174 | + if compute_state_delta is not None: |
| 175 | + state_delta = await compute_state_delta(session, rewind_event_index) |
| 176 | + else: |
| 177 | + state_delta = await compute_state_delta_for_rewind( |
| 178 | + session, rewind_event_index |
| 179 | + ) |
| 180 | + |
| 181 | + # Compute artifact delta to reverse changes |
| 182 | + if compute_artifact_delta is not None: |
| 183 | + artifact_delta = await compute_artifact_delta(session, rewind_event_index) |
| 184 | + else: |
| 185 | + artifact_delta = await compute_artifact_delta_for_rewind( |
| 186 | + session, |
| 187 | + rewind_event_index, |
| 188 | + artifact_service=artifact_service, |
| 189 | + app_name=app_name, |
| 190 | + ) |
| 191 | + |
| 192 | + # Create rewind event |
| 193 | + rewind_event = Event( |
| 194 | + invocation_id=f"e-{platform_uuid.new_uuid()}", |
| 195 | + author="user", |
| 196 | + actions=EventActions( |
| 197 | + rewind_before_invocation_id=rewind_before_invocation_id, |
| 198 | + state_delta=state_delta, |
| 199 | + artifact_delta=artifact_delta, |
| 200 | + ), |
| 201 | + ) |
| 202 | + |
| 203 | + logger.info("Rewinding session to invocation: %s", rewind_event) |
| 204 | + await session_service.append_event(session=session, event=rewind_event) |
0 commit comments