Skip to content
Blog

Preventing Context Contamination Across Specialized Sub-Agents in Google ADK

Learn how to isolate scratchpads, isolate working memory, and prevent state pollution across multi-agent fleets in Google Agent Development Kit.

Published on • December 5, 2026

AI Assistant

In complex multi-agent architectures, specialized sub-agents collaborate to achieve overarching goals: a research agent searches documentation, an engineering agent generates code, a QA agent tests it, and a summarizing agent reports back to the end user.

However, when agents share a naive single global session context, context contamination quickly degrades system performance. Intermediate tool calls, raw stack traces, verbose API payloads, and unverified speculative steps bleed into downstream agents. This results in prompt bloat, hallucination cascades, and safety policy violations.


Anatomy of Context Contamination

Context contamination manifests in three primary failure modes:

  1. Working Scratchpad Leakage: Sub-agent trial-and-error reasoning (e.g., failed SQL queries or debugging logs) clutters the coordinator agent’s view.
  2. Instruction Drift & Persona Hijacking: System instructions or behavioral constraints of one specialist (e.g., “Always reply in raw JSON”) bleed into the user-facing conversational agent.
  3. Sensitive Data Exposure: An internal data-fetching agent extracts PII or internal credentials that propagate into customer-facing response buffers.
Contaminated Global State (Naive):
Coordinator ────► [Shared History & Context Buffer] ◄──── Specialist A
                         ▲                ▲
                         │                │
                    Specialist B     Specialist C
(All intermediate tool traces, JSON payloads, and scratchpads merged together)

Isolated Sub-Agent Scopes (ADK Pattern):
                      ┌────────────────────────────────┐
                      │    Coordinator / Supervisor    │
                      │  (High-level goals & summaries)│
                      └───────────────┬────────────────┘
                                      │ Filtered Contract
               ┌──────────────────────┴──────────────────────┐
               ▼                                             ▼
     ┌───────────────────┐                         ┌───────────────────┐
     │  SQL Specialist   │                         │  Code Specialist  │
     │  Isolated Context │                         │  Isolated Context │
     │  [Scratchpad + DB]│                         │  [Sandbox Tests]  │
     └───────────────────┘                         └───────────────────┘

Architectural Solutions in Google ADK

Google ADK provides several design patterns and primitives to guarantee rigorous boundary isolation:

  1. Scoped State Dictionaries: Distinguishing between global session.state and private sub-agent sub_agent_state.
  2. Artifact Delegation: Storing heavy raw payloads in an ArtifactService and passing only light content references.
  3. Structured Handoff Summarization: Requiring sub-agents to emit distilled, typed Pydantic summaries upon completion instead of returning raw execution histories.

Implementation: Building Isolated Sub-Agent Execution

Here is a full pattern showing an orchestrator delegating to an isolated specialist without contaminating the main conversation history:

import asyncio
from typing import Optional, Dict, Any
from pydantic import BaseModel, Field
from google_adk.agents import LlmAgent, BaseAgent
from google_adk.runners import Runner
from google_adk.sessions import InMemorySessionService, Session

class ResearchSummary(BaseModel):
    key_findings: list[str] = Field(description="Distilled 3-5 key findings")
    confidence_score: float = Field(description="Confidence rating between 0 and 1")
    citation_urls: list[str] = Field(description="Direct source URLs")

class IsolatedSpecialistWrapper(BaseAgent):
    """Encapsulates a specialist agent with private context lifecycle."""
    def __init__(self, name: str, specialist: LlmAgent):
        super().__init__(name=name)
        self.specialist = specialist

    async def execute_task(self, prompt: str, parent_session: Session) -> ResearchSummary:
        # Create an ephemeral child session completely isolated from parent turn history
        child_session = Session(id=f"{parent_session.id}_sub_{self.name}")
        
        # Specialist only receives the isolated task instruction
        sub_runner = Runner(agent=self.specialist, session_service=InMemorySessionService())
        
        result_event = await sub_runner.run_async(
            session_id=child_session.id,
            user_message=prompt
        )
        
        # Sub-agent raw history is destroyed when child_session terminates
        return result_event.text

# Define the isolated data scientist specialist
analyst_agent = LlmAgent(
    name="DataAnalystSpecialist",
    model="gemini-3.8-flash",
    system_instruction=(
        "You are an expert data analyst. You execute complex data transformations. "
        "Always summarize your output strictly into factual takeaways. "
        "Do not include raw code or internal scratchpad thoughts in the final answer."
    )
)

# Define the primary user-facing orchestrator
coordinator_agent = LlmAgent(
    name="Coordinator",
    model="gemini-3.8-pro",
    system_instruction=(
        "You are an executive assistant. You coordinate tasks and present clean, "
        "concise conclusions to the user. You never expose internal tool execution traces."
    )
)

Context Hygiene Checklist for Multi-Agent Fleets

To maintain clean context boundaries in production agent swarms:

  • Enforce Output Schemas: Force all sub-agents to return Pydantic models. This guarantees that unstructured thoughts, backtraces, or debugging chatter cannot escape into the parent prompt.
  • Wipe Ephemeral State: Ensure that temporary working keys in state (such as _temp_scratchpad or _current_step) are deleted or filtered before handing control to peer agents.
  • Decouple Artifacts from Tokens: Large tables or multi-megabyte log files should be written to Google Cloud Storage or the ADK Artifact repository, passing only the URI: gs://bucket/reports/2026-run-4.parquet.
  • Set disallow_transfer_to_parent: Restrict lateral or upward message flooding, configuring strict deterministic gates before handoffs.

Conclusion

Context contamination is one of the quickest ways to degrade an enterprise multi-agent deployment. By enforcing scoped sub-agent sessions, structured Pydantic handoff contracts, and artifact-based payload offloading, Google ADK applications remain stable, cost-effective, and safe even across fleets of dozens of coordinating agents.