Skip to content

Commit eec0616

Browse files
moonbox3Copilot
andcommitted
Use deepcopy for state snapshot to detect nested mutations (microsoft#4500)
Replace dict() shallow copy with copy.deepcopy() when snapshotting workflow state before activity execution. The shallow copy shared references to nested objects (dicts, lists), so in-place mutations by executors were reflected in both the snapshot and live state, producing an empty diff and preventing state updates from propagating to downstream activities. Co-authored-by: Copilot <[email protected]>
1 parent 5ba1c6f commit eec0616

2 files changed

Lines changed: 138 additions & 1 deletion

File tree

‎python/packages/azurefunctions/agent_framework_azurefunctions/_app.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from __future__ import annotations
1010

1111
import asyncio
12+
import copy
1213
import json
1314
import logging
1415
import re
@@ -300,7 +301,7 @@ async def run() -> dict[str, Any]:
300301

301302
# Deserialize shared state values to reconstruct dataclasses/Pydantic models
302303
deserialized_state = {k: deserialize_value(v) for k, v in (shared_state_snapshot or {}).items()}
303-
original_snapshot = dict(deserialized_state)
304+
original_snapshot = copy.deepcopy(deserialized_state)
304305
shared_state.import_state(deserialized_state)
305306

306307
if is_hitl_response:

‎python/packages/azurefunctions/tests/test_app.py‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
# pyright: reportPrivateUsage=false
66

7+
import copy
78
import json
89
from collections.abc import Awaitable, Callable
910
from typing import Any, TypeVar
@@ -1441,5 +1442,140 @@ def test_build_status_url_handles_trailing_slash(self) -> None:
14411442
assert "instance-456" in url
14421443

14431444

1445+
class TestStateSnapshotDiff:
1446+
"""Test suite for state snapshot diffing in activity execution.
1447+
1448+
The activity executor snapshots state before execution and diffs against the
1449+
post-execution state to determine which keys were updated. The snapshot must
1450+
be independent of the live state so that in-place mutations to nested objects
1451+
(dicts, lists) are correctly detected as changes.
1452+
"""
1453+
1454+
@staticmethod
1455+
def _compute_updates(original_snapshot: dict[str, Any], current_state: dict[str, Any]) -> dict[str, Any]:
1456+
"""Compute state updates the same way as _app.py run()."""
1457+
return {k: v for k, v in current_state.items() if k not in original_snapshot or original_snapshot[k] != v}
1458+
1459+
def test_nested_dict_mutation_detected_in_diff(self) -> None:
1460+
"""Test that mutating values inside a nested dict appears in the diff."""
1461+
from agent_framework._workflows._state import State
1462+
1463+
deserialized_state: dict[str, Any] = {
1464+
"Local.config": {"code": "", "enabled": False},
1465+
"simple_key": "simple_value",
1466+
}
1467+
1468+
original_snapshot = copy.deepcopy(deserialized_state)
1469+
1470+
shared_state = State()
1471+
shared_state.import_state(deserialized_state)
1472+
1473+
config = shared_state.get("Local.config")
1474+
config["code"] = "SOMECODEXXX"
1475+
config["enabled"] = True
1476+
1477+
shared_state.commit()
1478+
current_state = shared_state.export_state()
1479+
1480+
updates = self._compute_updates(original_snapshot, current_state)
1481+
1482+
assert "Local.config" in updates
1483+
assert updates["Local.config"]["code"] == "SOMECODEXXX"
1484+
assert updates["Local.config"]["enabled"] is True
1485+
1486+
def test_new_key_in_nested_dict_detected_in_diff(self) -> None:
1487+
"""Test that adding a key to a nested dict appears in the diff."""
1488+
from agent_framework._workflows._state import State
1489+
1490+
deserialized_state: dict[str, Any] = {
1491+
"Local.data": {"existing": "value"},
1492+
}
1493+
1494+
original_snapshot = copy.deepcopy(deserialized_state)
1495+
1496+
shared_state = State()
1497+
shared_state.import_state(deserialized_state)
1498+
1499+
data = shared_state.get("Local.data")
1500+
data["code"] = "NEW_CODE"
1501+
1502+
shared_state.commit()
1503+
current_state = shared_state.export_state()
1504+
1505+
updates = self._compute_updates(original_snapshot, current_state)
1506+
1507+
assert "Local.data" in updates
1508+
assert updates["Local.data"]["code"] == "NEW_CODE"
1509+
1510+
def test_nested_list_mutation_detected_in_diff(self) -> None:
1511+
"""Test that appending to a nested list appears in the diff."""
1512+
from agent_framework._workflows._state import State
1513+
1514+
deserialized_state: dict[str, Any] = {
1515+
"Local.items": [1, 2, 3],
1516+
}
1517+
1518+
original_snapshot = copy.deepcopy(deserialized_state)
1519+
1520+
shared_state = State()
1521+
shared_state.import_state(deserialized_state)
1522+
1523+
items = shared_state.get("Local.items")
1524+
items.append(4)
1525+
1526+
shared_state.commit()
1527+
current_state = shared_state.export_state()
1528+
1529+
updates = self._compute_updates(original_snapshot, current_state)
1530+
1531+
assert "Local.items" in updates
1532+
assert updates["Local.items"] == [1, 2, 3, 4]
1533+
1534+
def test_new_top_level_key_detected_in_diff(self) -> None:
1535+
"""Test that setting a new top-level key appears in the diff."""
1536+
from agent_framework._workflows._state import State
1537+
1538+
deserialized_state: dict[str, Any] = {
1539+
"existing": "value",
1540+
}
1541+
1542+
original_snapshot = copy.deepcopy(deserialized_state)
1543+
1544+
shared_state = State()
1545+
shared_state.import_state(deserialized_state)
1546+
1547+
shared_state.set("Local.code", "SOMECODEXXX")
1548+
1549+
shared_state.commit()
1550+
current_state = shared_state.export_state()
1551+
1552+
updates = self._compute_updates(original_snapshot, current_state)
1553+
1554+
assert "Local.code" in updates
1555+
assert updates["Local.code"] == "SOMECODEXXX"
1556+
1557+
def test_unchanged_nested_state_produces_empty_diff(self) -> None:
1558+
"""Test that unmodified nested state produces no updates."""
1559+
from agent_framework._workflows._state import State
1560+
1561+
deserialized_state: dict[str, Any] = {
1562+
"Local.config": {"code": "existing", "enabled": True},
1563+
"simple_key": "simple_value",
1564+
}
1565+
1566+
original_snapshot = copy.deepcopy(deserialized_state)
1567+
1568+
shared_state = State()
1569+
shared_state.import_state(deserialized_state)
1570+
1571+
# No mutations performed
1572+
shared_state.commit()
1573+
current_state = shared_state.export_state()
1574+
1575+
updates = self._compute_updates(original_snapshot, current_state)
1576+
1577+
assert updates == {}
1578+
1579+
14441580
if __name__ == "__main__":
14451581
pytest.main([__file__, "-v", "--tb=short"])

0 commit comments

Comments
 (0)