Replaying Historical Sessions for Auditing and Offline Debugging
A session is an ordered event log — replay it to rebuild state at any point, generate audit transcripts, and bisect bad invocations, with Runner.rewind_async as the interactive counterpart.
Published on • December 3, 2026
AI Assistant

When a stakeholder asks “why did the agent refund $400 on Tuesday?”, you do not reach for a log aggregator — the answer is already inside the session. A Session is an ordered event log: every user message, agent reply, tool call, and state change is an Event in session.events, each stamped with an invocation_id, an author, and a timestamp. Nothing needs to be reconstructed after the fact, because nothing was thrown away.
This post turns that property into two working tools: an audit replay that walks history and rebuilds exactly what the agent knew at any moment, and an offline debug workflow that bisects a conversation down to the single invocation that went wrong. We finish with Runner.rewind_async, ADK’s built-in “undo one request” primitive — and its very real limitations.
Prerequisites
- ADK installed (
pip install google-adk) and aRunnerthat has run at least once against a persistentSessionService. - Familiarity with
session.events,event.actions.state_delta, andinvocation_id. - No assumption that history is stored anywhere but the session itself.
1. The session is already the audit trail
An Event (google.adk.events.Event) carries everything an auditor or debugger needs:
| Field | What it tells you |
|---|---|
event.id | Unique ID of this specific event |
event.invocation_id | Which user-request-to-final-response cycle it belongs to — the unit of “one turn” |
event.author | 'user' or the agent name that produced it |
event.content.parts | The payload: text, function calls, function responses |
event.actions.state_delta | Exactly which state keys this step changed, and to what |
event.actions.artifact_delta | Which artifacts were saved, and their new version |
event.timestamp | When it happened |
event.partial | Whether the text was a streaming chunk (not a complete message) |
The Runner hands every event to the SessionService, which merges state_delta into session.state and appends the event to history. That means the log is the source of truth and state is a materialized view of it — which is precisely why we can replay.
2. Rebuild state at any point by replaying deltas
Replaying is not a special API: it is iterating events and re-applying each state_delta, exactly as a SessionService does when it reconstructs session.state from storage. The one subtlety is the temp: prefix — invocation-scoped keys must be dropped when a new invocation starts:
from google.adk.events import Event
def rebuild_state(events: list[Event], upto_invocation_id: str | None = None) -> dict:
"""Reconstruct session state as it existed at a point in history."""
state: dict = {}
current_invocation: str | None = None
for event in events:
if upto_invocation_id and event.invocation_id == upto_invocation_id:
break # stop *before* the invocation we want to inspect
if event.invocation_id != current_invocation:
# `temp:` state is discarded when an invocation completes.
current_invocation = event.invocation_id
state = {k: v for k, v in state.items() if not k.startswith("temp:")}
if event.actions and event.actions.state_delta:
state.update(event.actions.state_delta)
return state
# Usage: what did the agent know right before the refund turn?
session = await session_service.get_session(
app_name=APP_NAME, user_id=user_id, session_id=session_id
)
state_before_refund = rebuild_state(session.events, upto_invocation_id="inv-refund-1")
Because scoped keys (user:, app:) arrive in the same deltas, this function rebuilds the visible state of the session — the same dictionary the agent read when it made its decision.
3. Generate an audit transcript
An audit wants rows, not objects. Classify each event the same way the framework does, then flatten:
def transcript(session) -> list[dict]:
rows = []
for event in session.events:
kind, detail = "other", ""
if event.get_function_calls():
kind = "tool_call"
detail = ", ".join(f"{c.name}({c.args})" for c in event.get_function_calls())
elif event.get_function_responses():
kind = "tool_result"
detail = ", ".join(r.name for r in event.get_function_responses())
elif event.content and event.content.parts and event.content.parts[0].text:
kind = "stream_chunk" if event.partial else "message"
detail = event.content.parts[0].text
elif event.actions and event.actions.state_delta:
kind = "state_update"
detail = str(event.actions.state_delta)
rows.append({
"timestamp": event.timestamp,
"invocation_id": event.invocation_id,
"author": event.author,
"kind": kind,
"detail": detail,
"state_delta": event.actions.state_delta if event.actions else None,
"artifact_delta": event.actions.artifact_delta if event.actions else None,
})
return rows
The same pass answers three different questions with one traversal:
| You are… | Read from each event |
|---|---|
| Auditing a decision | author, text, tool_call args, state_delta up to that point |
| Tracing a side effect | tool_result payloads and artifact_delta versions |
| Evaluating quality | is_final_response() events only — the user-visible turns |
4. Offline debugging: bisect by invocation
The invocation_id groups events into turns, so the fastest triage is “which turn first went wrong”:
from collections import defaultdict
from google.adk.events import Event
def invocations(session) -> dict[str, list[Event]]:
by_id: dict[str, list[Event]] = defaultdict(list)
for event in session.events:
by_id[event.invocation_id].append(event)
return by_id
def first_turn_without_final(session) -> str | None:
"""An invocation that produced tool calls but never a final response
is a strong candidate for a crash, timeout, or escalation loop."""
for inv_id, events in invocations(session).items():
if not any(e.is_final_response() for e in events):
return inv_id
return None
Once you have the suspect invocation, replay rebuild_state(events, upto_invocation_id=inv_id) to see the exact state the model received, and inspect that slice’s tool_call/tool_result pairs for the bad input. Common symptoms map cleanly onto the log:
| Symptom | Where to look first |
|---|---|
| Agent forgot a preference stated earlier | Deltas before the turn — was the key ever written? |
| Tool received a wrong argument | The tool_call event’s args in that invocation |
| Wrong value persisted after a fix | A later state_delta overwriting your key |
| Turn never produced output | Invocation with no is_final_response() event |
5. Rewind: replay’s interactive counterpart
When debugging turns into “just undo that request”, ADK ships Runner.rewind_async (Python v1.17.0+):
# Rewind to *before* the request identified by this invocation id.
await runner.rewind_async(
user_id=user_id,
session_id=session_id,
rewind_before_invocation_id=suspect_invocation_id,
)
It restores session-level state and artifacts to before that invocation. Crucially for auditors: rewound requests stay in the event log for debugging and analysis — the system simply ignores them when preparing the next model request, so the model effectively forgets interactions from the rewind point onward. The limitations are where teams get burned:
| Rewind does… | Rewind does not… |
|---|---|
| Restore session-scoped state and artifacts | Restore app:-level or user:-level state/artifacts |
| Keep rewound events in the log for audit | Revert external side effects (emails, API calls, DB writes) |
| Let the next request start from the restored point | Perform state + artifact + event updates atomically |
Because updates are not one atomic transaction, never rewind a session that is actively receiving traffic — run the rewind while the session is quiesced, or accept the inconsistency risk.
Checklist
- Session storage is persistent (
DatabaseSessionServiceorVertexAiSessionService) — replay ofInMemorySessionServicedies with the process. - Replay helpers drop
temp:keys at every invocation boundary. - Audit transcripts record
invocation_id,author, and both deltas, not just message text. - Final-response detection uses
event.is_final_response()rather than assuming the last event is the answer. - Suspect turns are located by
invocation_idbefore reading individual events. -
rewind_asyncis only called on quiesced sessions, never mid-conversation. - Stakeholders are told what rewind does not undo (external side effects,
user:/app:state). - Rewound events are retained — they are evidence, not garbage.
Conclusion
Replaying a session is not a feature you bolt on: it falls out of the fact that a session is an ordered event log whose state_deltas can be re-applied at will. Walk the log to rebuild state for an audit, group by invocation_id to bisect a failing turn, and reach for rewind_async when the fix is “undo that request” — remembering that history survives the rewind even when the model’s context does not. Build the replay tools once, and every future “why did it do that?” question becomes a query instead of an incident.