State Leakage: Ensuring Sub-Agents Don't Contaminate Global Context
Keep sub-agent writes isolated in Google ADK with state prefixes, temp scope, branch isolation, and include_contents to stop context leakage.
Published on • November 30, 2026
AI Assistant

There is a quiet failure mode that shows up in every mature multi-agent system: one sub-agent writes a scratch value, another sub-agent reads it three turns later, and the coordinator confidently quotes a stale number to a customer. Nothing crashes. Nothing throws. The state dict simply grew a key that nobody owns.
In the Google Agent Development Kit (ADK), this is not a bug — it is the default. session.state is one shared dictionary per conversation, and every agent in the tree writes to that same dictionary. State leakage is what happens when that shared scratchpad fills up with keys whose scope nobody defined.
This article explains exactly how state propagates through an ADK multi-agent tree, catalogs the realistic leakage vectors, and gives you a defense-in-depth pattern: key namespacing, temp: scoping, include_contents='none', and the branch isolation that task and single_turn modes give you for free.
1. One Scratchpad, Many Writers
ADK’s context model has three layers, and confusing them is the root of most leakage:
Session (one conversation thread)
├── session.events ← append-only history of everything that happened
├── session.state ← mutable key-value scratchpad (THE shared surface)
│ 'current_intent' session-scoped
│ 'user:language' user-scoped (shared across sessions)
│ 'app:api_endpoint' app-scoped (shared across users)
│ 'temp:raw_api_payload' invocation-scoped (discarded)
└── Memory ← cross-session searchable knowledge (separate service)
The critical property: the state collection is flat. There is no session.state["billing_agent"] namespace. When a billing_specialist sub-agent’s tool does tool_context.state["transaction_id"] = "TX-10992", that key lands in the same dict the coordinator, the tech specialist, and every future sub-agent will read.
Writes are not applied directly to the object — they are recorded as a state_delta on the EventActions of the event the agent yields, and the SessionService merges that delta into session.state when it appends the event. So state is always a byproduct of the event stream, which is both the danger (any agent can emit a delta) and the cure (every write is auditable).
2. The Four Leakage Vectors
Vector 1 — Unnamespaced keys
The classic case: transaction_id written by billing, overwritten by tech support, read by the coordinator as if it were still the billing one. Two agents, one key, last-writer-wins.
Vector 2 — Instruction templating
ADK substitutes {key} placeholders in an LlmAgent instruction with the live value from session.state. If your instruction says The customer's open ticket is {ticket_id} and ticket_id was written by a sub-agent that has since finished, the next agent inherits a stale or foreign value as trusted input — it is baked into the prompt, invisible in any tool log.
Related: if the key is missing, ADK raises an error unless you write {ticket_id?}. Teams often respond by seeding every key defensively, which makes leakage worse.
Vector 3 — History bleed via include_contents
By default an agent receives the relevant conversation history. A sub-agent that only needs the current turn still sees every prior tool result, transfer, and intermediate reasoning from its peers — including data that is irrelevant or, under regulations like GDPR, not permitted to leave that scope.
Vector 4 — temp: is shared, not private
temp: state is discarded when the invocation ends, which makes it tempting for intermediates. But ADK passes the same invocation context down the tree: a parent and all of its sub-agents share one invocation ID and therefore one temp: scope. temp: protects you from the next turn, not from a sibling agent.
3. Defense Layer 1: Namespacing as Policy
The cheapest fix is a naming convention enforced in code review, not prose. Prefix every state key with the owning agent’s domain:
from google.adk.agents import Agent
from google.adk.tools import ToolContext
def record_billing_facts(transaction_id: str, tool_context: ToolContext) -> dict:
"""Billing specialist only. Writes billing-scoped state."""
tool_context.state["billing:transaction_id"] = transaction_id
tool_context.state["billing:disputed"] = True
# Never: tool_context.state["transaction_id"] = transaction_id
return {"status": "success", "recorded": transaction_id}
def attach_trace(service: str, trace_id: str, tool_context: ToolContext) -> dict:
"""Tech specialist only. Writes tech-scoped state."""
tool_context.state["tech:service"] = service
tool_context.state["tech:trace_id"] = trace_id
return {"status": "success", "trace": trace_id}
Reading follows the same rule. Instruct each agent to consume only its own namespace plus an explicitly promoted set of shared keys:
coordinator = Agent(
name="support_coordinator",
model="gemini-flash-latest",
instruction="""
You see session state directly. Read ONLY:
- `support:*` keys (shared routing state you own)
- `user:*` keys (customer preferences)
Ignore every other namespace — `billing:*` and `tech:*` belong to
specialists and are not your concern. Promote a value to `support:*`
only when the specialist hands it back to you explicitly.
""",
sub_agents=[billing_specialist, tech_specialist],
)
This gives you a two-tier contract: specialists own their namespace; the coordinator owns promotion. The boundary is visible in session.state at any moment, which means you can write assertions against it in tests.
4. Defense Layer 2: Choose the Right Scope
ADK’s prefixes are a scoping system — use them deliberately:
| Prefix | Scope | Use for leakage control |
|---|---|---|
| (none) | current session | Conversation workflow: support:current_step |
user: | all sessions of one user | Preferences: user:language |
app: | all users of the app | Config: app:api_endpoint |
temp: | current invocation only | Intermediates that must not reach the next turn |
The rule that actually prevents bugs: anything a sub-agent computes for its own processing goes into temp:. Raw API payloads, intermediate JSON, chain-of-thought summaries, retry counters — all of it dies when the invocation completes, so a stale value can never be read three turns later.
def fetch_raw_invoice(inv_id: str, tool_context: ToolContext) -> dict:
payload = {"inv": inv_id, "lines": 14, "total": 49.0} # synthetic
# Invocation-scoped: never survives into the next user turn.
tool_context.state["temp:raw_invoice"] = payload
# Only the distilled, namespaced fact is promoted to session scope.
tool_context.state["billing:invoice_total"] = payload["total"]
return {"status": "success", "total": payload["total"]}
If you do need to pass data between agents within one turn, prefer structured handoff over ambient state: give the receiving agent an input_schema and let the transfer carry the payload, or write the result to output_key so the write is tied to one agent’s final response instead of floating in the dict.
5. Defense Layer 3: Cut the History
include_contents controls whether an agent sees the conversation history at all:
from google.adk.agents import LlmAgent
# A summarizer that must only see the current turn's input.
redaction_helper = LlmAgent(
name="pii_scrubber",
model="gemini-flash-latest",
instruction="Strip emails and phone numbers from the supplied text.",
include_contents="none", # no prior contents reach this model call
)
'none' is the right default for any sub-agent whose job is a pure transformation — a summarizer, a formatter, a classifier — because history is pure attack surface for them: extra tokens, extra leakage paths, extra cost.
There is a second, structural isolation available in ADK’s collaboration modes. Sub-agents configured with mode="task" or mode="single_turn" operate in their own isolated session branch: when they run in parallel, each branch only sees its own events while building model context, and the parent collects results once the branches complete. If your architecture runs peers concurrently, that branch isolation is the difference between “isolated workers” and “workers quietly sharing each other’s intermediate state”.
from google.adk import Agent
research_a = Agent(name="research_a", mode="single_turn", include_contents="none",
tools=[search_kb])
research_b = Agent(name="research_b", mode="single_turn", include_contents="none",
tools=[search_kb])
coordinator = Agent(name="analyst", sub_agents=[research_a, research_b])
6. Auditing for Leakage After the Fact
Because every write travels as a state_delta on an event, you can audit leakage by walking a session’s history. This is a cheap test to run in CI against recorded sessions:
from collections import defaultdict
def audit_state_writes(events, allowed_owners):
"""Flags deltas whose key namespace has no declared owner or
a non-promoting writer."""
namespace_author = defaultdict(set)
violations = []
for event in events:
delta = event.actions.state_delta if event.actions else {}
for key in delta:
ns = key.split(":", 1)[0] if ":" in key else "(root)"
namespace_author[ns].add(event.author)
# Root keys are the classic leakage smell.
if ns == "(root)":
violations.append((event.author, key, "unnamespaced key"))
# A namespace touched by more than one author is suspect.
elif len(namespace_author[ns]) > 1:
violations.append((event.author, key, f"shared namespace {ns}"))
return violations
A clean run has exactly one author per namespace (plus the coordinator promoting into support:), and zero root-level keys. Anything else is a candidate for refactoring before it reaches production.
7. Checklist
- Every state key is namespaced:
billing:*,tech:*,support:*— no root keys. - Specialists only write their own namespace; promotion to shared keys is explicit.
- Intermediates live under
temp:and never under a bare key. -
{key}instruction templates reference only keys that agent owns, with?for optionals. - Pure-transformation sub-agents run with
include_contents="none". - Concurrent sub-agents use
mode="task"/mode="single_turn"for branch isolation. - A
state_deltaaudit test runs over recorded sessions in CI. - Session storage is persistent before launch —
InMemorySessionServiceerases all of this on restart.
Sources
- Google ADK Documentation: https://adk.dev/
- Conversational context, state, and sessions: https://adk.dev/sessions/
- Events: https://adk.dev/events/