Schema Validation on State: Preventing Silent Failures with StateSchemaError
Declare a Pydantic state_schema on your ADK agent and every bad state write fails loudly with StateSchemaError — plus the two failure modes, the colon-key bypass, and the nested-write hole you still have to close yourself.
Published on • December 3, 2026
AI Assistant

A typo in a state key never announces itself. context.state["severity_level"] = 4 when the real key is severity sails through the event loop, commits cleanly, and surfaces three turns later as an agent that has forgotten how urgent the ticket is. Wrong types are worse: "severity": "high" passes a dict around happily until a comparison blows up in a callback far from the line that wrote it.
ADK closes that gap with a schema on state: a Pydantic model passed as state_schema that makes every state mutation either valid or an immediate StateSchemaError. This tutorial covers declaring the schema, reading both error modes precisely, and knowing exactly which mutations are — and are not — checked.
Prerequisites
- ADK installed (
pip install google-adk) and Pydantic (bundled with ADK). - A working agent that writes to
ctx.stateor emitsstate_deltavalues. - Basic Pydantic
BaseModelandFieldfamiliarity.
1. Declare the schema on the agent
state_schema is a field on every agent (it lives on the base node class, so LlmAgent, callbacks, and tools all inherit it). It takes a Pydantic BaseModel whose fields are the state keys you permit:
from google.adk.agents import LlmAgent
from pydantic import BaseModel, Field
class SupportState(BaseModel):
ticket_id: str
severity: int = Field(ge=1, le=5)
tags: list[str] = []
support_agent = LlmAgent(
name="support_agent",
model="gemini-flash-latest",
instruction="Triage the ticket; maintain ticket_id, severity and tags in state.",
state_schema=SupportState,
)
When set, ctx.state mutations are validated at runtime against this schema. Child nodes inherit the schema from their parent through the InvocationContext unless they declare their own — so one declaration at the root covers the whole agent tree. Field constraints (ge, le, pattern, …) are enforced exactly as Pydantic enforces them elsewhere.
2. The two failure modes of StateSchemaError
StateSchemaError subclasses TypeError, and it is exported straight from the package:
from google.adk.sessions import StateSchemaError
Every rejection is one of two shapes:
| Failure mode | Trigger | What the message tells you |
|---|---|---|
| Undeclared key | Writing a key the schema does not declare | The key name plus the sorted list of declared fields |
| Invalid value | Key is declared, value fails its annotation or constraints | The field’s annotation, the schema class name, and the wrapped Pydantic ValidationError |
try:
context.state["severity_level"] = 4 # typo — not in SupportState
except StateSchemaError as e:
print(e)
# Key 'severity_level' is not declared in state schema 'SupportState'.
# Declared fields: ['severity', 'tags', 'ticket_id']
try:
context.state["severity"] = "high" # declared, wrong type
except StateSchemaError as e:
print(e)
# Value for 'severity' does not satisfy field 'severity' (int)
# in 'SupportState': 1 validation error for SupportState...
Because it is a TypeError, existing except TypeError handlers catch it too — but catch it specifically in agent code so a bad write fails the turn instead of being swallowed as a generic error.
3. What is validated — and what is not
Validation happens at mutation time, when state[key] = value or state.update({...}) runs — not at commit. That timing makes the boundaries worth memorizing:
| Mutation | Checked against schema? | Outcome |
|---|---|---|
state["severity"] = "high" | Yes — assignment | StateSchemaError (wraps ValidationError) |
state.update({...}) | Yes — every entry in the dict | StateSchemaError on the first bad pair |
state["severity_level"] = 4 (undeclared) | Yes | StateSchemaError listing declared fields |
state["user:theme"] = "dark" | No — key contains : | Passes; scopes are not schema fields |
state["tags"].append(1) where tags: list[str] | No — nested write, no assignment | Reaches the pending-commit delta unvalidated |
Container holding a protobuf message or datetime | n/a | Excluded from the delta entirely |
Two rules fall out of that table:
- Keys containing
:bypass validation. That coversapp:,user:,temp:, and ADK’s own<owner>:<key>internal names — the schema describes unprefixed, session-scoped keys only. Never assume a schema constrainsuser:state. - Only assignment is checked.
state["tags"] = tags + ["rush"]is validated; the visually similarstate["tags"].append("rush")is not, because the list was handed out by a read and mutated in place. If validation matters for a container, reassign it:
tags = list(context.state["tags"])
tags.append("rush")
context.state["tags"] = tags # assignment → validated against list[str]
4. The pending-commit delta behind the checks
State is not a plain dict: it keeps the current value plus a pending-commit delta that the Runner commits when it processes the yielded event. Assignment writes to both; in-place container writes are discovered later by comparing the container against a snapshot taken at read time, and only then recorded into the delta.
That machinery has one more consequence: a container whose JSON form is not equal to itself — a protobuf message, a datetime — is left out of the delta, along with any writes into it recorded earlier. Those keys silently fail to persist regardless of schema. The practical rule mirrors the general ADK advice: keep state values JSON-shaped (strings, numbers, booleans, lists, dicts), and store identifiers for anything richer.
5. Designing a schema that pays for itself
A schema that declares three keys while tools write thirty just moves the typo. Declare the keys your callbacks, tools, and {key} instruction templating actually read; use Field constraints for the invariants you would otherwise assert by hand; and keep prefixes (user:, app:, temp:) out of the model — they are scope, not schema. The result is a state contract that fails at the write site, with the full list of legal keys in the error message, instead of three turns downstream.
Checklist
- The root agent declares
state_schema=; children rely on inheritance or declare their own. - Every unprefixed key written by tools, callbacks, or
output_keyexists as a schema field. - Constraints that matter (
ge,le,pattern) live inField(...), not in prose instructions. - Prefixed keys (
user:,app:,temp:) are understood to bypass validation entirely. - Container mutations use reassignment, not in-place
append/pop, where validation matters. - State values are JSON-shaped — no prototypes,
datetimeobjects, or protobuf messages. - Agent code catches
StateSchemaErrorspecifically and fails the turn loudly. - A test exercises one bad key and one bad value to prove the schema is wired up.
Conclusion
Untyped state turns every typo into a slow-motion bug. A state_schema converts that class of failure into a StateSchemaError at the exact line that wrote the value, with the declared field list or the Pydantic ValidationError` in the message. Know the two boundaries — colon keys bypass, nested writes slip past assignment checks — and close them with convention and reassignment, and your agent’s scratchpad becomes a contract instead of a hope.
References
- https://adk.dev/sessions/state/
- https://raw.githubusercontent.com/google/adk-python/main/src/google/adk/sessions/state.py
- https://raw.githubusercontent.com/google/adk-python/main/src/google/adk/workflow/_base_node.py
- https://raw.githubusercontent.com/google/adk-python/main/src/google/adk/agents/context.py