---
title: "Analyzing Conversation Drift and State Bloat Over 50+ Turns"
date: "2026-12-03T08:32:03+07:00"
description: "Long ADK conversations quietly accumulate stale keys, oversized lists, and duplicated context until latency and accuracy both sag. How to measure drift with real numbers, clean state with explicit deltas, and let context compaction summarize the backlog away."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-conversation-drift-state-bloat.jpg"
alt: "A conversation timeline widening into a bloated cloud of accumulated data"
tags: ['google-adk', 'state', 'context-compaction', 'performance', 'observability']
---

No one decides to let a session rot. Turn 7 the agent is crisp; turn 43 it is re-litigating a constraint abandoned at turn 12, and the p95 latency graph has been climbing the whole time. The cause is not one bug — it is three accumulators running unattended: `session.state` keeps every key it was ever given, `session.events` keeps every token of every tool response, and the model's context window keeps receiving both.

ADK gives you the levers; it does not pull them for you. State entries persist for the whole session unless you overwrite them, events are appended verbatim, and nothing warns you that a `shopping_cart_items` list has grown to four hundred entries across fifty turns. This post treats drift as a measurable phenomenon — instrument it first — then walks through the three mitigations that actually move the numbers: disciplined state hygiene, explicit cleanup via `state_delta`, and `EventsCompactionConfig` for the event backlog.

## Prerequisites

- ADK installed (`pip install google-adk`) and a session that has run at least a handful of turns.
- Familiarity with state prefixes (`user:`, `app:`, `temp:`) and `EventActions.state_delta`.
- Context compaction requires ADK Python v1.16.0 or newer.

## 1. Name the three accumulators

Drift is not one thing, and conflating the three makes the fixes look mystical:

| Accumulator | Grows with | Symptom at 50+ turns | Owner |
| --- | --- | --- | --- |
| `session.state` | Every key ever written | Stale flags, oversized lists, duplicated context | You, via `state_delta` |
| `session.events` | Every message, tool call, tool result | Re-sent history, rising input tokens | ADK appends; compaction summarizes |
| Model context window | Both of the above, re-sent each call | Latency climb, cost climb, attention dilution | `EventsCompactionConfig` |

The first row is pure engineering discipline. The second and third are structural: because state changes travel *inside* events as `state_delta`, a bloated state also bloats the log that gets replayed into context — one problem wearing two hats.

## 2. Measure before you mitigate

You cannot tune what you do not count. Derive drift metrics from the session you already have:

```python
import json
from google.adk.sessions import Session

def drift_report(session: Session) -> dict:
    state = session.state
    # Size of each value as it would serialize — a good proxy for tokens.
    sizes = {k: len(json.dumps(v, default=str)) for k, v in state.items()}
    return {
        "turn_count": sum(1 for e in session.events if e.author == "user"),
        "event_count": len(session.events),
        "state_key_count": len(state),
        "state_bytes": sum(sizes.values()),
        "largest_keys": sorted(sizes.items(), key=lambda kv: -kv[1])[:5],
        "temp_keys": sum(1 for k in state if k.startswith("temp:")),
    }
```

`largest_keys` is where surprises live: a single list-valued key routinely dwarfs everything else combined, and `temp:` keys still present *between* invocations tell you a tool is writing scratch data with a session-scoped name. Track `state_key_count` and `event_count` per turn in production — a linear climb with no plateau is the drift signature.

## 3. State hygiene: the keys that outlive their welcome

State values are per-session dict entries that persist for the entire session unless overwritten. Over a long conversation that produces three failure modes: **stale keys** (`needs_clarification=True` from turn 4 still steering turn 40), **oversized lists** appended to forever, and **duplicated context** — a summary string that gets rewritten each turn but never truncated.

The design rules that prevent it:

- **`temp:` for anything invocation-scoped.** Intermediate tool results, per-request calculations, and validation flags belong in `temp:`, which is discarded when the invocation completes — free cleanup by construction. Reserve unprefixed keys for state that genuinely must outlive the turn.
- **Replace, don't accumulate.** A summary key should be overwritten with the new summary, not appended to. If a list must grow, cap it and drop the oldest entries in the same delta that adds the newest.
- **One key, one purpose.** Duplicated context usually means two keys holding overlapping strings that both get sent to the model.

## 4. Explicit cleanup through `state_delta`

When a key has reached the end of its life, delete it deliberately — write the key with a `None` value in an event's `state_delta`, the same mechanism used for every other state change:

```python
from google.adk.events import Event, EventActions

async def prune_stale_state(session_service, session, stale_keys: list[str]) -> None:
    await session_service.append_event(
        session,
        Event(
            invocation_id="state_prune",
            author="system",
            actions=EventActions(
                state_delta={key: None for key in stale_keys}
            ),
        ),
    )
```

Do this from a periodic hook — an `after_agent_callback` that checks `drift_report()` against thresholds and prunes what has expired. Keeping the cleanup as an *event* rather than an in-place mutation matters: it is tracked, persisted, thread-safe, and replayable, exactly like every other state write.

> **The silent-data-loss footgun:** when building the delta, note that `State` drops from the pending delta any container whose JSON form differs — protobuf messages and `datetime` objects do not match their previous serialized form, so the update can be skipped without an error. If a value must round-trip reliably, store primitives (ISO strings, floats, plain dicts), not library objects.

## 5. Let compaction shrink the event backlog

State hygiene fixes the dictionary; `EventsCompactionConfig` fixes the history. Compaction summarizes older session events — instructions, inputs, and model responses — so the context window stays small while recent turns stay verbatim:

```python
from google.adk.apps.app import App, EventsCompactionConfig

# Token-based: an absolute safety net for unpredictable workloads.
app = App(
    name="long_running_assistant",
    root_agent=root_agent,
    events_compaction_config=EventsCompactionConfig(
        token_threshold=4000,   # compact once the prompt passes this many tokens
        event_retention_size=5, # keep the last 5 events raw for pronoun resolution
    ),
)
```

Two strategies are available, and they are complementary rather than competing:

| Strategy | Trigger | Config keys | Best for |
| --- | --- | --- | --- |
| Token-based | Actual token volume | `token_threshold`, `event_retention_size` | Unpredictable input — pasted files, big tool results |
| Sliding window | Fixed invocation count | `compaction_interval`, `overlap_size` | Regular, predictable chat |

If both are set, token-based wins: exceeding the threshold compacts that turn and skips the sliding-window check. The `overlap_size` parameter keeps prior invocations inside the next summary so consecutive summaries do not drift apart from each other — a different drift than the one this post measures, but the same failure mode: the agent loses the thread.

Two supporting habits matter alongside compaction. **Prune tool outputs** before they enter the log — return the three relevant rows from a search, not the three hundred you fetched, because whatever a tool returns is what history will re-send forever. And **measure after compaction**, not before: a healthy setup shows `event_count` rising while the effective context size plateaus near `token_threshold`.

## Checklist

- [ ] `drift_report()`-style metrics (`state_key_count`, `state_bytes`, `event_count`, turn count) are tracked per session in production.
- [ ] Invocation-scoped data lives in `temp:`, never in unprefixed keys.
- [ ] Summary-style keys are overwritten, not appended to; lists are capped in the same delta that grows them.
- [ ] Stale keys are pruned through an explicit `state_delta`, not in-place mutation of a fetched `Session`.
- [ ] State values are plain JSON-safe primitives — no `datetime`, no protobuf objects, to dodge the dropped-delta footgun.
- [ ] `EventsCompactionConfig` is configured with a `token_threshold` suited to the workload.
- [ ] `event_retention_size` / `overlap_size` keeps enough raw context for pronoun resolution across summaries.
- [ ] Tool outputs are trimmed at the source before they enter the event log.
- [ ] Drift metrics are re-checked after mitigations and shown to plateau rather than climb.

## Conclusion

Conversation drift over fifty turns is the predictable result of three unattended accumulators, not a mystery of long-context models. Measure the state and the log, keep invocation scratch in `temp:`, prune dead keys through tracked deltas, and let `EventsCompactionConfig` summarize the history backlog — then the graph you watch flatten is not just the context size, but the agent's ability to still be right on turn fifty-one.

## References

- https://adk.dev/sessions/state/
- https://adk.dev/context/compaction/
- https://adk.dev/events/
- https://adk.dev/sessions/session/
