Skip to content

Commit f3057ef

Browse files
benke520Benke Qumoonbox3
authored
Python: fix: clear service_session_id in _agent_wrapper when propagate_session=True (microsoft#5875)
* fix: clear service_session_id in _agent_wrapper when propagate_session=True When propagate_session=True, the child agent inherits the parent's service_session_id. After the parent's first LLM call, MAF auto-populates this from the Responses API conversation_id. The child sends it as previous_response_id which the server rejects because the parent's tool_call is still pending (400 error). This fix saves and clears service_session_id before calling the child agent and restores it in a finally block, preserving session.state sharing while isolating the server-side conversation pointer. Fixes microsoft#5874 * refactor: use child session copy instead of in-place mutation Address Copilot review comments: - Create a child AgentSession with shared state dict but isolated service_session_id, avoiding race conditions under concurrent asyncio.gather tool invocations. - Update tests to verify child gets a separate session object and that child-set service_session_id does not leak to parent. * fix: update test_chat_agent_as_tool_propagate_session_true for child session isolation The existing test asserted captured_session is parent_session, but since we now create a separate child AgentSession (to avoid racing under concurrent asyncio.gather), the child is a different object. Updated assertions to verify: - child is NOT the parent object (isolation) - child shares the same session_id and state dict (by reference) - child's service_session_id is None (isolated) * fix: add type narrowing asserts for captured_session Add 'assert captured_session is not None' before attribute access to satisfy mypy/pyright type checking on Optional values. * Python: Fix test typing checks --------- Co-authored-by: Benke Qu <[email protected]> Co-authored-by: Evan Mattson <[email protected]> Co-authored-by: Evan Mattson <[email protected]>
1 parent 68136ee commit f3057ef

2 files changed

Lines changed: 118 additions & 2 deletions

File tree

‎python/packages/core/agent_framework/_agents.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -631,10 +631,22 @@ async def _agent_wrapper(ctx: FunctionInvocationContext, **kwargs: Any) -> str:
631631
ctx: the function invocation context used
632632
**kwargs: only used to dynamically load the argument that is defined for this tool.
633633
"""
634+
session = ctx.session if propagate_session else None
635+
636+
# Create a child session that shares the parent's state dict but has
637+
# an isolated service_session_id. This avoids mutating the parent
638+
# session in-place, which would race under concurrent asyncio.gather
639+
# tool invocations sharing the same session.
640+
if session is not None:
641+
child_session = AgentSession(session_id=session.session_id)
642+
child_session.state = session.state # shared by reference
643+
child_session.service_session_id = None
644+
session = child_session
645+
634646
stream = self.run(
635647
str(kwargs.get(arg_name, "")),
636648
stream=True,
637-
session=ctx.session if propagate_session else None,
649+
session=session,
638650
function_invocation_kwargs=dict(ctx.kwargs),
639651
)
640652
if stream_callback is not None:

‎python/packages/core/tests/core/test_agents.py‎

Lines changed: 105 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1737,10 +1737,14 @@ def capturing_run(*args: Any, **kwargs: Any) -> Any:
17371737
)
17381738
)
17391739

1740-
assert captured_session is parent_session
1740+
# Child receives a separate AgentSession (not the parent object) to isolate
1741+
# service_session_id, but shares the same state dict and session_id.
17411742
assert captured_session is not None
1743+
assert captured_session is not parent_session
17421744
assert captured_session.session_id == "parent-session-123"
1745+
assert captured_session.state is parent_session.state
17431746
assert captured_session.state["shared_key"] == "shared_value"
1747+
assert captured_session.service_session_id is None
17441748

17451749

17461750
async def test_chat_agent_as_tool_propagate_session_false_by_default(client: SupportsChatGetResponse) -> None:
@@ -1802,6 +1806,106 @@ def capturing_run(*args: Any, **kwargs: Any) -> Any:
18021806
assert parent_session.state["counter"] == 1
18031807

18041808

1809+
async def test_chat_agent_as_tool_propagate_session_clears_service_session_id(client: SupportsChatGetResponse) -> None:
1810+
"""Test that propagate_session=True gives the child a separate session with cleared service_session_id."""
1811+
agent = Agent(client=client, name="SubAgent", description="Sub agent")
1812+
tool = agent.as_tool(propagate_session=True)
1813+
1814+
parent_session = AgentSession(session_id="shared-session")
1815+
parent_session.service_session_id = "resp_parent_abc123"
1816+
parent_session.state["data"] = "shared"
1817+
1818+
original_run = agent.run
1819+
captured_session = None
1820+
1821+
def capturing_run(*args: Any, **kwargs: Any) -> Any:
1822+
nonlocal captured_session
1823+
captured_session = kwargs.get("session")
1824+
# The child gets a different session object with isolated service_session_id
1825+
assert captured_session is not None
1826+
assert captured_session is not parent_session
1827+
assert captured_session.service_session_id is None
1828+
# But shares the same state dict by reference
1829+
assert captured_session.state is parent_session.state
1830+
assert captured_session.state["data"] == "shared"
1831+
return original_run(*args, **kwargs)
1832+
1833+
agent.run = capturing_run # type: ignore[assignment, method-assign] # ty: ignore[invalid-assignment]
1834+
1835+
await tool.invoke(
1836+
context=FunctionInvocationContext(
1837+
function=tool,
1838+
arguments={"task": "Hello"},
1839+
session=parent_session,
1840+
)
1841+
)
1842+
1843+
# Parent's service_session_id is never mutated
1844+
assert parent_session.service_session_id == "resp_parent_abc123"
1845+
1846+
1847+
async def test_chat_agent_as_tool_propagate_session_restores_service_session_id_on_error(
1848+
client: SupportsChatGetResponse,
1849+
) -> None:
1850+
"""Test that parent's service_session_id is untouched even if the child agent raises."""
1851+
agent = Agent(client=client, name="SubAgent", description="Sub agent")
1852+
tool = agent.as_tool(propagate_session=True)
1853+
1854+
parent_session = AgentSession(session_id="shared-session")
1855+
parent_session.service_session_id = "resp_parent_xyz789"
1856+
1857+
def failing_run(*args: Any, **kwargs: Any) -> Any:
1858+
raise RuntimeError("Child agent failed")
1859+
1860+
agent.run = failing_run # type: ignore[assignment, method-assign] # ty: ignore[invalid-assignment]
1861+
1862+
with raises(RuntimeError, match="Child agent failed"):
1863+
await tool.invoke(
1864+
context=FunctionInvocationContext(
1865+
function=tool,
1866+
arguments={"task": "Hello"},
1867+
session=parent_session,
1868+
)
1869+
)
1870+
1871+
# Parent's service_session_id is never mutated — child has its own session
1872+
assert parent_session.service_session_id == "resp_parent_xyz789"
1873+
1874+
1875+
async def test_chat_agent_as_tool_propagate_session_no_service_session_id(client: SupportsChatGetResponse) -> None:
1876+
"""Test that child setting service_session_id does not leak back to the parent."""
1877+
agent = Agent(client=client, name="SubAgent", description="Sub agent")
1878+
tool = agent.as_tool(propagate_session=True)
1879+
1880+
parent_session = AgentSession(session_id="shared-session")
1881+
parent_session.service_session_id = None
1882+
1883+
original_run = agent.run
1884+
captured_session = None
1885+
1886+
def capturing_run(*args: Any, **kwargs: Any) -> Any:
1887+
nonlocal captured_session
1888+
captured_session = kwargs.get("session")
1889+
assert captured_session is not None
1890+
assert captured_session.service_session_id is None
1891+
# Simulate the child's run populating service_session_id
1892+
captured_session.service_session_id = "resp_child_leaked"
1893+
return original_run(*args, **kwargs)
1894+
1895+
agent.run = capturing_run # type: ignore[assignment, method-assign] # ty: ignore[invalid-assignment]
1896+
1897+
await tool.invoke(
1898+
context=FunctionInvocationContext(
1899+
function=tool,
1900+
arguments={"task": "Hello"},
1901+
session=parent_session,
1902+
)
1903+
)
1904+
1905+
# The child's service_session_id must not leak back to the parent
1906+
assert parent_session.service_session_id is None
1907+
1908+
18051909
async def test_chat_agent_as_mcp_server_basic(client: SupportsChatGetResponse) -> None:
18061910
"""Test basic as_mcp_server functionality."""
18071911
agent = Agent(client=client, name="TestAgent", description="Test agent for MCP")

0 commit comments

Comments
 (0)