Skip to content

Commit 4aee32c

Browse files
RachelWangggclaude
andauthored
Python: Surface switch-case condition errors instead of routing to the default branch (microsoft#8490)
* Python: surface switch-case condition errors instead of routing to default SwitchCaseEdgeGroup wrapped every case predicate in a bare `except Exception` that only logged a warning, so a predicate that raised was treated exactly like one that returned False: the message fell through to the default branch and the workflow completed successfully. A broken routing predicate became silently wrong routing rather than a visible failure. This contradicted `Edge.should_route`, which documents that predicate errors are deliberately allowed to surface "to avoid masking logic bugs", and made the existing `FanOutEdgeRunner` error path (span status EXCEPTION, re-raise) unreachable for switch-case groups, so the failures were missing from telemetry too. The block was marked `# pragma: no cover`. Also align `FanOutEdgeRunner` with `SingleEdgeRunner`, which checks `_can_handle` before evaluating a condition: drop messages no target can handle before running the selection function. Without this, removing the catch would turn an undeliverable message into a raised AttributeError instead of a type-mismatch drop. Fixes microsoft#8489 Co-Authored-By: Claude Opus 5 <[email protected]> * Python: drop target-mismatched messages before the fan-out selection function The runner fans every message out to all of the source's edge runners and gathers them with `gather_cancelling_siblings_on_error`. `FanOutEdgeRunner` checked `message.target_id` only after running the selection function, so a message addressed to an executor reached through a different edge still had this group's selection function evaluated against it - and a raise there cancelled the sibling runner that was actually delivering the message. Check `message.target_id` against `_target_map` first and return DROPPED_TARGET_MISMATCH, ahead of the `_can_handle` check, matching `SingleEdgeRunner`, which checks the target and then `_can_handle` before evaluating `Edge.should_route`. Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]>
1 parent 38fbb7f commit 4aee32c

3 files changed

Lines changed: 136 additions & 5 deletions

File tree

‎python/packages/core/agent_framework/_workflows/_edge.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -863,11 +863,12 @@ def selection_func(message: Any, targets: list[str]) -> list[str]:
863863
for case in cases:
864864
if isinstance(case, SwitchCaseEdgeGroupDefault):
865865
return [case.target_id]
866-
try:
867-
if case.condition(message):
868-
return [case.target_id]
869-
except Exception as exc: # pragma: no cover - defensive logging
870-
logger.warning("Error evaluating condition for case %s: %s", case.target_id, exc)
866+
# Errors raised by a case predicate deliberately surface to the caller, matching
867+
# `Edge.should_route`. Swallowing them would route the message to the default
868+
# branch, turning a broken predicate into silent misrouting rather than a
869+
# visible failure. `FanOutEdgeRunner` records the error on the edge-group span.
870+
if case.condition(message):
871+
return [case.target_id]
871872
raise RuntimeError("No matching case found in SwitchCaseEdgeGroup")
872873

873874
target_ids = [case.target_id for case in cases]

‎python/packages/core/agent_framework/_workflows/_edge_runner.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,29 @@ async def send_message(
255255
source_span_ids=message.source_span_ids,
256256
) as span:
257257
try:
258+
# Drop messages this group cannot deliver before running the selection function, so
259+
# a selection function is only ever asked about a message this group could route.
260+
# `SingleEdgeRunner` applies the same ordering, checking the target and
261+
# `_can_handle` before `Edge.should_route`.
262+
#
263+
# The target check matters beyond saving work: the runner fans every message out to
264+
# all of the source's edge runners and cancels sibling deliveries when one raises,
265+
# so evaluating a selection function for a message addressed to an executor outside
266+
# this group could cancel that message's real delivery.
267+
if message.target_id and message.target_id not in self._target_map:
268+
span.set_attributes({
269+
OtelAttr.EDGE_GROUP_DELIVERED: False,
270+
OtelAttr.EDGE_GROUP_DELIVERY_STATUS: EdgeGroupDeliveryStatus.DROPPED_TARGET_MISMATCH.value,
271+
})
272+
return False
273+
274+
if not any(self._can_handle(target_id, message) for target_id in self._target_ids):
275+
span.set_attributes({
276+
OtelAttr.EDGE_GROUP_DELIVERED: False,
277+
OtelAttr.EDGE_GROUP_DELIVERY_STATUS: EdgeGroupDeliveryStatus.DROPPED_TYPE_MISMATCH.value,
278+
})
279+
return False
280+
258281
selection_results = (
259282
self._selection_func(message.data, self._target_ids) if self._selection_func else self._target_ids
260283
)

‎python/packages/core/tests/workflow/test_edge.py‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1389,6 +1389,113 @@ async def test_switch_case_edge_group_send_message() -> None:
13891389
assert mock_send.call_count == 1
13901390

13911391

1392+
def test_switch_case_edge_group_condition_error_propagates() -> None:
1393+
"""A failing case condition surfaces instead of falling through to the default."""
1394+
source = MockExecutor(id="source_executor")
1395+
target1 = MockExecutor(id="target_executor_1")
1396+
target2 = MockExecutor(id="target_executor_2")
1397+
1398+
def broken_condition(message: MockMessage) -> bool:
1399+
raise ValueError("condition is broken")
1400+
1401+
edge_group = SwitchCaseEdgeGroup(
1402+
source_id=source.id,
1403+
cases=[
1404+
SwitchCaseEdgeGroupCase(condition=broken_condition, target_id=target1.id),
1405+
SwitchCaseEdgeGroupDefault(target_id=target2.id),
1406+
],
1407+
)
1408+
1409+
assert edge_group._selection_func is not None # type: ignore[reportPrivateUsage]
1410+
with pytest.raises(ValueError, match="condition is broken"):
1411+
edge_group._selection_func(MockMessage(data=1), [target1.id, target2.id]) # type: ignore[reportPrivateUsage]
1412+
1413+
1414+
async def test_switch_case_edge_group_send_message_condition_error_propagates() -> None:
1415+
"""A failing case condition surfaces from send_message and delivers nothing."""
1416+
source = MockExecutor(id="source_executor")
1417+
target1 = MockExecutor(id="target_executor_1")
1418+
target2 = MockExecutor(id="target_executor_2")
1419+
1420+
def broken_condition(message: MockMessage) -> bool:
1421+
raise ValueError("condition is broken")
1422+
1423+
edge_group = SwitchCaseEdgeGroup(
1424+
source_id=source.id,
1425+
cases=[
1426+
SwitchCaseEdgeGroupCase(condition=broken_condition, target_id=target1.id),
1427+
SwitchCaseEdgeGroupDefault(target_id=target2.id),
1428+
],
1429+
)
1430+
executors: dict[str, Executor] = {source.id: source, target1.id: target1, target2.id: target2}
1431+
edge_runner = create_edge_runner(edge_group, executors)
1432+
1433+
message = WorkflowMessage(data=MockMessage(data=1), source_id=source.id)
1434+
1435+
with patch("agent_framework._workflows._edge_runner.EdgeRunner._execute_on_target") as mock_send:
1436+
with pytest.raises(ValueError, match="condition is broken"):
1437+
await edge_runner.send_message(message, State(), InProcRunnerContext())
1438+
1439+
assert mock_send.call_count == 0
1440+
1441+
1442+
async def test_fan_out_edge_group_send_message_with_target_outside_group() -> None:
1443+
"""A message addressed to an executor outside the group never reaches the selection function."""
1444+
source = MockExecutor(id="source_executor")
1445+
target1 = MockExecutor(id="target_executor_1")
1446+
target2 = MockExecutor(id="target_executor_2")
1447+
1448+
def broken_condition(message: MockMessage) -> bool:
1449+
raise ValueError("condition is broken")
1450+
1451+
edge_group = SwitchCaseEdgeGroup(
1452+
source_id=source.id,
1453+
cases=[
1454+
SwitchCaseEdgeGroupCase(condition=broken_condition, target_id=target1.id),
1455+
SwitchCaseEdgeGroupDefault(target_id=target2.id),
1456+
],
1457+
)
1458+
executors: dict[str, Executor] = {source.id: source, target1.id: target1, target2.id: target2}
1459+
edge_runner = create_edge_runner(edge_group, executors)
1460+
1461+
# RunnerImpl fans every message out to all of the source's edge runners, so a message
1462+
# addressed to an executor reached through a different edge still arrives here. It must be
1463+
# dropped as a target mismatch, not evaluated -- raising would cancel its real delivery.
1464+
message = WorkflowMessage(data=MockMessage(data=1), source_id=source.id, target_id="unrelated_executor")
1465+
1466+
success = await edge_runner.send_message(message, State(), InProcRunnerContext())
1467+
1468+
assert success is False
1469+
1470+
1471+
async def test_fan_out_edge_group_send_message_with_unhandleable_data() -> None:
1472+
"""A message no target can handle is dropped before the selection function runs."""
1473+
source = MockExecutor(id="source_executor")
1474+
target1 = MockExecutor(id="target_executor_1")
1475+
target2 = MockExecutor(id="target_executor_2")
1476+
1477+
calls: list[Any] = []
1478+
1479+
def selection_func(message: Any, targets: list[str]) -> list[str]:
1480+
calls.append(message)
1481+
return targets
1482+
1483+
edge_group = FanOutEdgeGroup(
1484+
source_id=source.id,
1485+
target_ids=[target1.id, target2.id],
1486+
selection_func=selection_func,
1487+
)
1488+
executors: dict[str, Executor] = {source.id: source, target1.id: target1, target2.id: target2}
1489+
edge_runner = create_edge_runner(edge_group, executors)
1490+
1491+
message = WorkflowMessage(data="invalid_data", source_id=source.id)
1492+
1493+
success = await edge_runner.send_message(message, State(), InProcRunnerContext())
1494+
1495+
assert success is False
1496+
assert calls == []
1497+
1498+
13921499
async def test_switch_case_edge_group_send_message_with_invalid_target() -> None:
13931500
"""Test sending a message through a switch case edge group with an invalid target."""
13941501
source = MockExecutor(id="source_executor")

0 commit comments

Comments
 (0)