Skip to content

Commit b9a004f

Browse files
committed
fix: let agents see finished output of ParallelAgents in other branches
Only ParallelAgent writes branches, always as parallel_agent.sub_agent pairs. Walk both branches to the first mismatch: an odd index means sibling lanes of the same ParallelAgent (hidden); an even index or no mismatch means visible. Event.branch stays a plain string. Fixes google#3470
1 parent d509d7c commit b9a004f

3 files changed

Lines changed: 239 additions & 21 deletions

File tree

‎src/google/adk/flows/llm_flows/contents.py‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -750,17 +750,32 @@ def _is_event_belongs_to_branch(
750750
) -> bool:
751751
"""Check if an event belongs to the current branch.
752752
753-
This is for event context segregation between agents. E.g. agent A shouldn't
754-
see output of agent B.
753+
Sub-agents of a ParallelAgent are isolated lanes: an agent never sees output
754+
from a sibling lane or from anything nested inside one. Everything else is
755+
visible.
756+
757+
Only ParallelAgent writes branches, always as `parallel_agent.sub_agent`
758+
pairs, so even segments name a ParallelAgent and odd segments name one of
759+
its sub-agents. Walk both branches to the first mismatch:
760+
761+
odd same ParallelAgent, different sub-agents: sibling lanes. Hidden.
762+
even different ParallelAgents. Every earlier segment matched, so no
763+
ParallelAgent above forked them into different lanes. Visible.
764+
none one branch is a prefix of the other: same lane. Visible.
765+
766+
stage1.a vs stage1.b mismatch at 1, odd hidden
767+
stage2.c vs stage1.a mismatch at 0, even visible
768+
par.r1 vs par.r1.abc.a no mismatch, prefix visible
769+
gp.x.p1.a vs gp.y.p2.d mismatch at 1, odd hidden
755770
"""
756771
if not invocation_branch or not event.branch:
757772
return True
758-
# We use dot to delimit branch nodes. To avoid simple prefix match
759-
# (e.g. agent_0 unexpectedly matching agent_00), require either perfect branch
760-
# match, or match prefix with an additional explicit '.'
761-
return invocation_branch == event.branch or invocation_branch.startswith(
762-
f'{event.branch}.'
763-
)
773+
current = invocation_branch.split('.')
774+
other = event.branch.split('.')
775+
for i, (a, b) in enumerate(zip(current, other)):
776+
if a != b:
777+
return i % 2 == 0
778+
return True
764779

765780

766781
def _is_function_call_event(event: Event, function_name: str) -> bool:
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Which earlier agent outputs reach an agent's LLM request (issue #3470)."""
16+
17+
import random
18+
19+
from google.adk.agents.base_agent import BaseAgent
20+
from google.adk.agents.llm_agent import LlmAgent
21+
from google.adk.agents.parallel_agent import ParallelAgent
22+
from google.adk.agents.sequential_agent import SequentialAgent
23+
import pytest
24+
25+
from .. import testing_utils
26+
27+
28+
def _agent(name: str) -> LlmAgent:
29+
return LlmAgent(
30+
name=name, model=testing_utils.MockModel.create(responses=[f'{name} out'])
31+
)
32+
33+
34+
def _seen_outputs(agent: LlmAgent) -> set[str]:
35+
"""Names of agents whose output is in the agent's last LLM request."""
36+
seen = set()
37+
for content in agent.model.requests[-1].contents:
38+
for part in content.parts or []:
39+
if part.text and part.text.rstrip().endswith(' out'):
40+
seen.add(part.text.split(' out')[0].split()[-1])
41+
return seen
42+
43+
44+
@pytest.mark.asyncio
45+
async def test_reducer_nested_in_parallel_sees_its_workers():
46+
"""The architecture from issue #3470."""
47+
a, b, c, d, e, f = (_agent(n) for n in 'abcdef')
48+
r1, r2, r3 = _agent('r1'), _agent('r2'), _agent('r3')
49+
root = SequentialAgent(
50+
name='final_seq',
51+
sub_agents=[
52+
ParallelAgent(
53+
name='final_par',
54+
sub_agents=[
55+
SequentialAgent(
56+
name='group1',
57+
sub_agents=[
58+
ParallelAgent(name='abc', sub_agents=[a, b, c]),
59+
r1,
60+
],
61+
),
62+
SequentialAgent(
63+
name='group2',
64+
sub_agents=[
65+
ParallelAgent(name='def', sub_agents=[d, e, f]),
66+
r2,
67+
],
68+
),
69+
],
70+
),
71+
r3,
72+
],
73+
)
74+
75+
await testing_utils.InMemoryRunner(root).run_async('go')
76+
77+
assert _seen_outputs(r1) == {'a', 'b', 'c'}
78+
assert _seen_outputs(r2) == {'d', 'e', 'f'}
79+
assert _seen_outputs(r3) == {'a', 'b', 'c', 'd', 'e', 'f', 'r1', 'r2'}
80+
81+
82+
@pytest.mark.asyncio
83+
async def test_sequence_of_parallel_stages_sees_earlier_stages():
84+
"""The follow-up case from issue #3470."""
85+
a, b, c, d = (_agent(n) for n in 'abcd')
86+
root = SequentialAgent(
87+
name='seq',
88+
sub_agents=[
89+
ParallelAgent(name='stage1', sub_agents=[a, b]),
90+
ParallelAgent(name='stage2', sub_agents=[c, d]),
91+
],
92+
)
93+
94+
await testing_utils.InMemoryRunner(root).run_async('go')
95+
96+
assert _seen_outputs(a) == set()
97+
assert _seen_outputs(c) == {'a', 'b'}
98+
assert _seen_outputs(d) == {'a', 'b'}
99+
100+
101+
# A path is the list of (container_kind, child_index) from the root to a leaf.
102+
_Path = tuple[tuple[type[BaseAgent], int], ...]
103+
104+
105+
def _random_tree(
106+
rng: random.Random,
107+
depth: int,
108+
leaves: dict[str, tuple[LlmAgent, _Path]],
109+
path: _Path = (),
110+
) -> BaseAgent:
111+
"""Builds a random Sequential/Parallel tree with LlmAgent leaves."""
112+
if depth == 0 or (path and rng.random() < 0.25):
113+
leaf = _agent(f'a{len(leaves)}')
114+
leaves[leaf.name] = (leaf, path)
115+
return leaf
116+
kind = rng.choice([SequentialAgent, ParallelAgent])
117+
children = [
118+
_random_tree(rng, depth - 1, leaves, path + ((kind, i),))
119+
for i in range(rng.randint(2, 3))
120+
]
121+
name = '_'.join([kind.__name__] + [str(i) for _, i in path])
122+
return kind(name=name, sub_agents=children)
123+
124+
125+
def _expected_seen(viewer: _Path, others: dict[str, _Path]) -> set[str]:
126+
"""Outputs the viewer should see, derived from the tree alone.
127+
128+
Walk both paths from the root to the first container where they take
129+
different children. If it is a ParallelAgent the two are in sibling lanes and
130+
the output is hidden. If it is a SequentialAgent the output is visible
131+
exactly when the other agent's child came first.
132+
"""
133+
seen = set()
134+
for name, other in others.items():
135+
for (kind, i), (_, j) in zip(viewer, other):
136+
if i != j:
137+
if kind is SequentialAgent and j < i:
138+
seen.add(name)
139+
break
140+
return seen
141+
142+
143+
@pytest.mark.asyncio
144+
@pytest.mark.parametrize('seed', range(20))
145+
async def test_visibility_matches_tree_structure(seed):
146+
"""Hidden across ParallelAgent lanes, visible otherwise, for any tree."""
147+
leaves: dict[str, tuple[LlmAgent, _Path]] = {}
148+
root = _random_tree(random.Random(seed), 3, leaves)
149+
150+
await testing_utils.InMemoryRunner(root).run_async('go')
151+
152+
paths = {name: path for name, (_, path) in leaves.items()}
153+
for name, (leaf, path) in leaves.items():
154+
assert _seen_outputs(leaf) == _expected_seen(path, paths), name

‎tests/unittests/flows/llm_flows/test_contents_branch.py‎

Lines changed: 62 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
from google.adk.agents.llm_agent import Agent
2222
from google.adk.events.event import Event
23+
from google.adk.flows.llm_flows.contents import _is_event_belongs_to_branch
2324
from google.adk.flows.llm_flows.contents import request_processor
2425
from google.adk.models.llm_request import LlmRequest
2526
from google.genai import types
@@ -28,6 +29,35 @@
2829
from ... import testing_utils
2930

3031

32+
@pytest.mark.parametrize(
33+
"invocation_branch, event_branch, expected",
34+
[
35+
# No branch on either side: nothing to segregate.
36+
(None, "p.a", True),
37+
("p.a", None, True),
38+
# Same branch.
39+
("p.a", "p.a", True),
40+
# Event from an enclosing level (event branch is a prefix).
41+
("p.a.q.x", "p.a", True),
42+
# Event from a finished nested group below (invocation branch is a
43+
# prefix). The reducer case from issue #3470.
44+
("p.a", "p.a.q.x", True),
45+
# Sub-agents of the same ParallelAgent are isolated lanes. So is
46+
# everything nested under them, including different ParallelAgents.
47+
("p.a", "p.b", False),
48+
("gp.x.p1.a", "gp.y.p2.d", False),
49+
# Different ParallelAgents run one after another. The sequence of
50+
# stages case from issue #3470.
51+
("p2.c", "p1.a", True),
52+
# A name prefix is not ancestry.
53+
("p.agent_00", "p.agent_0", False),
54+
],
55+
)
56+
def test_is_event_belongs_to_branch(invocation_branch, event_branch, expected):
57+
event = Event(invocation_id="inv", author="x", branch=event_branch)
58+
assert _is_event_belongs_to_branch(invocation_branch, event) is expected
59+
60+
3161
@pytest.mark.asyncio
3262
async def test_branch_filtering_child_sees_parent():
3363
"""Test that child agents can see parent agents' events."""
@@ -199,16 +229,18 @@ async def test_branch_filtering_grandchild_sees_grandparent():
199229
invocation_context = await testing_utils.create_invocation_context(
200230
agent=agent
201231
)
202-
# Set deeply nested branch: grandparent.parent.grandchild
203-
invocation_context.branch = "grandparent_agent.parent_agent.grandchild_agent"
232+
# grandparent_agent forks parent_agent, which forks grandchild and sibling.
233+
invocation_context.branch = (
234+
"grandparent_agent.parent_agent.parent_agent.grandchild_agent"
235+
)
204236

205237
# Add events from all levels of hierarchy
206238
events = [
207239
Event(
208240
invocation_id="inv1",
209241
author="grandparent_agent",
210242
content=types.ModelContent("Grandparent response"),
211-
branch="grandparent_agent",
243+
branch=None,
212244
),
213245
Event(
214246
invocation_id="inv2",
@@ -220,13 +252,13 @@ async def test_branch_filtering_grandchild_sees_grandparent():
220252
invocation_id="inv3",
221253
author="grandchild_agent",
222254
content=types.ModelContent("Grandchild response"),
223-
branch="grandparent_agent.parent_agent.grandchild_agent",
255+
branch="grandparent_agent.parent_agent.parent_agent.grandchild_agent",
224256
),
225257
Event(
226258
invocation_id="inv4",
227259
author="sibling_agent",
228260
content=types.ModelContent("Sibling response"),
229-
branch="grandparent_agent.parent_agent.sibling_agent",
261+
branch="grandparent_agent.parent_agent.parent_agent.sibling_agent",
230262
),
231263
]
232264
invocation_context.session.events = events
@@ -251,15 +283,15 @@ async def test_branch_filtering_grandchild_sees_grandparent():
251283

252284

253285
@pytest.mark.asyncio
254-
async def test_branch_filtering_parent_cannot_see_child():
255-
"""Test that parent agents cannot see child agents' events."""
286+
async def test_branch_filtering_parent_sees_finished_children():
287+
"""A reducer after parallel agents sees their finished work (#3470)."""
256288
agent = Agent(model="gemini-2.5-flash", name="parent_agent")
257289
llm_request = LlmRequest(model="gemini-2.5-flash")
258290
invocation_context = await testing_utils.create_invocation_context(
259291
agent=agent
260292
)
261-
# Set current branch as parent
262-
invocation_context.branch = "parent_agent"
293+
# parent_agent runs under outer, after workers and sub_workers finished.
294+
invocation_context.branch = "outer.parent_agent"
263295

264296
# Add events from parent and its children
265297
events = [
@@ -272,19 +304,22 @@ async def test_branch_filtering_parent_cannot_see_child():
272304
invocation_id="inv2",
273305
author="parent_agent",
274306
content=types.ModelContent("Parent response"),
275-
branch="parent_agent",
307+
branch="outer.parent_agent",
276308
),
277309
Event(
278310
invocation_id="inv3",
279311
author="child_agent",
280312
content=types.ModelContent("Child response"),
281-
branch="parent_agent.child_agent",
313+
branch="outer.parent_agent.workers.child_agent",
282314
),
283315
Event(
284316
invocation_id="inv4",
285317
author="grandchild_agent",
286318
content=types.ModelContent("Grandchild response"),
287-
branch="parent_agent.child_agent.grandchild_agent",
319+
branch=(
320+
"outer.parent_agent.workers.child_agent.sub_workers"
321+
".grandchild_agent"
322+
),
288323
),
289324
]
290325
invocation_context.session.events = events
@@ -293,8 +328,22 @@ async def test_branch_filtering_parent_cannot_see_child():
293328
async for _ in request_processor.run_async(invocation_context, llm_request):
294329
pass
295330

296-
# Verify parent cannot see child or grandchild events
331+
# Verify parent sees child and grandchild events
297332
assert llm_request.contents == [
298333
types.UserContent("User message"),
299334
types.ModelContent("Parent response"),
335+
types.Content(
336+
role="user",
337+
parts=[
338+
types.Part(text="For context:"),
339+
types.Part(text="[child_agent] said: Child response"),
340+
],
341+
),
342+
types.Content(
343+
role="user",
344+
parts=[
345+
types.Part(text="For context:"),
346+
types.Part(text="[grandchild_agent] said: Grandchild response"),
347+
],
348+
),
300349
]

0 commit comments

Comments
 (0)