Skip to content

Commit 2cb2c76

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 4e09023 commit 2cb2c76

3 files changed

Lines changed: 105 additions & 37 deletions

File tree

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

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -750,31 +750,31 @@ 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.
755-
756-
ParallelAgent writes branches as `parallel_agent.sub_agent` segment pairs,
757-
one pair per ParallelAgent above the agent, e.g. `par1.seq1.par2.a`. Sibling
758-
sub-agents of the same ParallelAgent run concurrently, so their events are
759-
hidden from each other. Events from an earlier ParallelAgent, or from within
760-
the current agent's own branch, are already complete and are visible.
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
761770
"""
762771
if not invocation_branch or not event.branch:
763772
return True
764-
invocation_segments = invocation_branch.split('.')
765-
event_segments = event.branch.split('.')
766-
for idx, (invocation_segment, event_segment) in enumerate(
767-
zip(invocation_segments, event_segments)
768-
):
769-
if invocation_segment != event_segment:
770-
if idx % 2 == 0:
771-
# Different ParallelAgents. They run sequentially, so the event's
772-
# ParallelAgent already finished and its events should be visible.
773-
return True
774-
# Different sub-agents of the same ParallelAgent. They run in parallel,
775-
# so they should not see each other.
776-
return False
777-
# One branch is a prefix of the other.
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
778778
return True
779779

780780

‎tests/unittests/agents/test_parallel_branch_visibility.py‎

Lines changed: 53 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414

1515
"""Which earlier agent outputs reach an agent's LLM request (issue #3470)."""
1616

17+
import random
18+
19+
from google.adk.agents.base_agent import BaseAgent
1720
from google.adk.agents.llm_agent import LlmAgent
1821
from google.adk.agents.parallel_agent import ParallelAgent
1922
from google.adk.agents.sequential_agent import SequentialAgent
@@ -95,22 +98,57 @@ async def test_sequence_of_parallel_stages_sees_earlier_stages():
9598
assert _seen_outputs(d) == {'a', 'b'}
9699

97100

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+
98143
@pytest.mark.asyncio
99-
async def test_parallel_siblings_do_not_see_each_other_at_any_depth():
100-
a, b, c = (_agent(n) for n in 'abc')
101-
root = ParallelAgent(
102-
name='outer',
103-
sub_agents=[
104-
SequentialAgent(
105-
name='left',
106-
sub_agents=[ParallelAgent(name='inner', sub_agents=[a, b])],
107-
),
108-
c,
109-
],
110-
)
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)
111149

112150
await testing_utils.InMemoryRunner(root).run_async('go')
113151

114-
assert _seen_outputs(a) == set()
115-
assert _seen_outputs(b) == set()
116-
assert _seen_outputs(c) == set()
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: 30 additions & 0 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."""

0 commit comments

Comments
 (0)