Google ADK: Needle-in-a-Haystack Benchmarks for Agents with 1M+ Token Contexts
Build a depth-swept needle-in-a-haystack suite for ADK agents: corpus generation, eval datasets, pytest harness, and the ADK-specific ways retrieval silently fails.
Published on • December 4, 2026
AI Assistant

A model card says “1M-token context window.” It does not say your agent can use it. The gap between “the tokens fit” and “the answer survives” is exactly what needle-in-a-haystack testing measures — and for an ADK agent the gap is wider than for a bare model, because between the haystack and the answer sit history management, tool routing, summarization, and instruction placement.
That matters now more than ever: current Gemini models advertise unified 1M-token context windows and long-decode generation up to 1M tokens, which makes it technically unremarkable to hand an agent a 1M-token prompt. What stays hard is knowing whether the specific fact planted at position 700,000 still reaches the final response after your compaction policy folds the transcript, after a sub-agent decides to re-retrieve, or after an instruction edit shifts the prefix.
This article builds a depth-swept NIAH suite on ADK’s own evaluation primitives: a corpus generator, an eval dataset ADK can run from the CLI or pytest, a direct Runner harness for exact-match scoring, and a reading of the results that distinguishes context capacity from agent retrieval behavior.
1. What you are actually benchmarking
Three distinct questions, and a good suite answers all three separately:
| Question | Topology | Failure it exposes |
|---|---|---|
| Can the model attend to a fact in a huge prompt? | Haystack sent as conversation content | Pure long-context degradation by depth |
| Can the agent find a fact behind a retrieval tool? | Haystack behind a tool/database | Wrong tool, bad query, premature final answer |
| Does ADK’s context machinery preserve the fact? | Same haystack across config variants | Compaction, include_contents, history pruning |
Run them as separate experiment arms. If arm 1 passes and arm 3 fails, your problem is configuration, not capacity.
2. Prerequisites
pip install google-adk- A model with a large window (e.g.
gemini-4-neon/gemini-4-hydrogen, both documented with unified 1M-token contexts) - Rough cost awareness: ~4 characters per token means a 1M-token haystack is on the order of 4 MB of text per trial. Sweep a few depths, not hundreds.
3. Step 1 — generate corpus, needle, and depth
"""Corpus generator: deterministic filler plus one planted needle."""
import random
import string
def filler(n_sentences: int, seed: int = 7) -> str:
random.seed(seed) # reproducible corpus across runs
topics = ["billing", "routing", "SLA", "onboarding", "audit", "rollback"]
return "\n".join(
f"Log {i}: the {random.choice(topics)} policy for cluster "
f"{random.choice(string.ascii_uppercase)}-{i % 97} was reviewed and filed."
for i in range(n_sentences)
)
def make_needle() -> tuple[str, str]:
token = f"{random.choice(string.ascii_uppercase)}-{random.randint(1000, 9999)}"
return token, f"Deployment authorization code for the audit: {token}."
def build_haystack(n_sentences: int, needle: str, depth: float) -> str:
"""Insert the needle at `depth` (0.0 = top of the context, 1.0 = bottom)."""
body = filler(n_sentences)
cut = int(len(body) * depth)
return body[:cut] + "\n" + needle + "\n" + body[cut:]
Sweep depth over [0.0, 0.25, 0.5, 0.75, 0.99] — the classic NIAH curve shows degradation in the middle and, on some models, near the very end. Each depth gets its own session so nothing leaks between trials.
4. Step 2 — put the haystack where the agent will read it
For the in-context arm, the haystack becomes the first user turn and the probe the second:
import asyncio
from google.adk import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
agent = Agent(
name="haystack_agent",
model="gemini-4-neon",
instruction="Answer from the conversation. If the requested value is present, "
"quote it exactly; otherwise say NOT FOUND.",
include_contents="default", # the haystack rides in session history
)
session_service = InMemorySessionService()
runner = Runner(agent=agent, app_name="niah", session_service=session_service)
async def ask(session_id: str, text: str) -> str:
content = types.Content(role="user", parts=[types.Part(text=text)])
final = ""
async for event in runner.run_async(
user_id="u1", session_id=session_id, new_message=content
):
if event.is_final_response() and event.content:
final = event.content.parts[0].text or ""
return final
async def run_trial(session_id: str, haystack: str, needle: str) -> bool:
await session_service.create_session(app_name="niah", user_id="u1", session_id=session_id)
await ask(session_id, haystack) # plant the corpus
answer = await ask(session_id, "What is the deployment authorization code?")
return needle in answer # exact-match scoring
Note what the harness does not do: no LLM judge. For a needle with a literal token, exact string match is the honest metric and costs nothing.
5. Step 3 — run it through ADK’s own evaluation
Once the trials work, encode them as an ADK test file so they are reproducible and runnable from the CLI. ADK checks the .test.json suffix, and each case carries user_content, expected final_response, and intermediate_data.tool_uses:
{
"eval_set_id": "niah_depth_50",
"eval_cases": [
{
"eval_id": "depth_050_trial_1",
"conversation": [
{
"invocation_id": "inv-0001",
"user_content": { "role": "user", "parts": [{ "text": "<generated haystack>" }] },
"final_response": { "role": "model", "parts": [{ "text": "ack" }] },
"intermediate_data": { "tool_uses": [], "intermediate_responses": [] }
},
{
"invocation_id": "inv-0002",
"user_content": { "role": "user", "parts": [{ "text": "What is the deployment authorization code?" }] },
"final_response": { "role": "model", "parts": [{ "text": "QX-4417" }] },
"intermediate_data": { "tool_uses": [], "intermediate_responses": [] }
}
],
"session_input": { "app_name": "niah", "user_id": "u1", "state": {} }
}
]
}
Then from pytest:
import pytest
from google.adk.evaluation.agent_evaluator import AgentEvaluator
@pytest.mark.asyncio
async def test_needle_at_50_percent_depth():
await AgentEvaluator.evaluate(
agent_module="niah_agent", # dir with __init__.py exposing root_agent
eval_dataset_file_path_or_dir="tests/niah.test.json",
)
…or from the shell:
adk eval niah_agent tests/niah.test.json --print_detailed_results
Two configuration facts worth relying on: if you supply no criteria, ADK defaults to tool_trajectory_avg_score: 1.0 and response_match_score: 0.8, and a test_config.json lets you set them explicitly. For long-context work you will also get the efficiency criteria for free on every run — token_usage_v1, tool_call_count_v1, inference_call_count_v1, and invocation_duration_v1 are reported automatically and never fail a case, which is exactly what you want when comparing two context configurations at equal quality.
6. Step 4 — interpret the curve
A healthy in-context arm looks like near-100% recall at every depth. The interesting results are the deviations:
| Observation | Likely cause | ADK-specific check |
|---|---|---|
| Passes at depth 0.0, fails at 0.5 | Genuine mid-context degradation | Model/serving issue; re-run before changing agent code |
| Fails at all depths in arm 3 but passes arm 1 | Context machinery ate the needle | EventsCompactionConfig summarized it away; raise event_retention_size or move the fact to session.state |
| Fails only when the needle is in history | History is not being sent | include_contents='none' on the agent under test |
| Inconsistent across runs | Non-deterministic tool routing | Score intermediate_data.tool_uses against an expected trajectory |
Answer correct but token_usage_v1 exploding | Haystack resent every turn | Compaction interval, or cache-prefix breakage |
For the tool-backed arm, exact match stops being enough — an agent may answer correctly after the wrong tool call. ADK’s trajectory criteria cover that: tool_trajectory_avg_score for exact path match, hallucinations_v1 for groundedness of the claim against tool output, and the rubric-based rubric_based_tool_use_quality_v1 when you care about ordering (“lookup_policy must be called before ruling”) rather than an exact path.
7. Guard against the measurement pitfalls
- Do not use a summed input-token field as your context size. On long-decode continuations,
usage.total_input_tokensaccumulates across hops; the docs direct you tousage.initial_input_tokensplustotal_output_tokensandtotal_thought_tokensinstead. A benchmark that mislabels its depth axis is worse than no benchmark. - Hold the prefix constant between arms. Same instruction, same tool order, same
thinking_level— otherwise you are measuring cache invalidation, not attention. - Keep user simulation out of the first version. Criteria that expect fixed responses (
tool_trajectory_avg_score,response_match_score,final_response_match_v2) are incompatible with ADK’s user simulation, where prompts are generated dynamically. Fix the probe first; add simulated users only for the multi-turn variant. - For CI regression, use conformance testing.
adk conformance testcompares live LLM requests, responses, and tool calls against recorded baselines (spec.yamlplusgenerated-recordings.yaml), and it fails the build on unexpected deviation — a good backstop for “did our last context refactor change what the agent actually sees?” - Estimate before you pay. Use
count_tokens(or a cheap length/4 estimate) to size each haystack, and budget the suite: 5 depths × N seeds × full-context inputs adds up faster than the accuracy numbers suggest.
Checklist
- Separate the three arms: in-context attention, tool-backed retrieval, and ADK context-machinery preservation.
- Generate a deterministic corpus with a fixed seed and a needle token that supports exact-match scoring.
- Sweep at least five depths including the very top and very bottom of the context.
- Give each trial its own
Sessionso history never bleeds between depths. - Encode trials as
.test.jsonand run them withAgentEvaluator.evaluateoradk eval. - Compare variants on
token_usage_v1andinference_call_count_v1— reported automatically, never failing. - Re-run the sweep after any change to
EventsCompactionConfig,include_contents, or instruction/tool placement. - Record the harness’s token-accounting basis so the depth axis stays honest across model versions.
- Add
adk conformancebaselines once the suite is green, to catch silent prefix changes in CI.
Conclusion
Needle-in-a-haystack stops being a parlor trick the moment you attach it to an agent: it becomes a regression test for every context decision you have made — where history lives, what compaction preserves, which agent sees the transcript, and how much of the haystack you resend each turn. ADK already gives you the machinery to run it (AgentEvaluator, adk eval, trajectory and efficiency criteria), so the only new work is a corpus generator and the discipline to sweep depth.
Run it before you advertise a 1M-token capability and after every context change. The curve tells you in one chart whether your agent’s long-context claim is real, and the failure pattern tells you which configuration knob to reach for.