|
| 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 | +"""Helpers for resolving which events are live after rewinds.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +from .event import Event |
| 20 | + |
| 21 | + |
| 22 | +def _apply_rewinds(events: list[Event]) -> list[Event]: |
| 23 | + """Returns ``events`` with rewound invocations removed. |
| 24 | +
|
| 25 | + Iterates backward. When an event carries |
| 26 | + ``actions.rewind_before_invocation_id == X``, drops that event together with |
| 27 | + every event between it and the earliest event of invocation ``X`` (inclusive), |
| 28 | + then resumes the backward walk from there. |
| 29 | +
|
| 30 | + This is the single source of truth for "which events are live" after rewinds. |
| 31 | + Both LLM prompt building (``google.adk.flows.llm_flows.contents``) and context |
| 32 | + compaction (``google.adk.apps.compaction``) must agree on it, otherwise |
| 33 | + rewound content can leak back into prompts through a compaction summary. |
| 34 | +
|
| 35 | + Args: |
| 36 | + events: The full event history, in chronological order. |
| 37 | +
|
| 38 | + Returns: |
| 39 | + The chronological subset of ``events`` that survives all rewinds. |
| 40 | + """ |
| 41 | + kept: list[Event] = [] |
| 42 | + i = len(events) - 1 |
| 43 | + while i >= 0: |
| 44 | + event = events[i] |
| 45 | + if event.actions and event.actions.rewind_before_invocation_id: |
| 46 | + rewind_invocation_id = event.actions.rewind_before_invocation_id |
| 47 | + for j in range(0, i, 1): |
| 48 | + if events[j].invocation_id == rewind_invocation_id: |
| 49 | + i = j |
| 50 | + break |
| 51 | + else: |
| 52 | + kept.append(event) |
| 53 | + i -= 1 |
| 54 | + kept.reverse() |
| 55 | + return kept |
0 commit comments