Python: [Bug]: AG-UI queued approvals stream both tool results but final snapshot drops the first
Description
With a real Agent + ToolApprovalMiddleware, two queued approvals for the same local tool execute both calls and emit both TOOL_CALL_RESULT events, but the final thread snapshot retains only the second result. A subsequent user turn then reaches the scripted chat client with both historical calls and only the second result.
Reproduced at 218700d4e94ad14652746b02a5877655ff8780d2, using the public FastAPI endpoint and InMemoryAGUIThreadSnapshotStore:
| After approving the second card | Observed |
|---|---|
| Local effects | first, second, once each |
| SSE terminal results | call_first, call_second |
| Saved snapshot / subsequent hydration | Both calls, only call_second result |
| Next chat-client input | Both calls, only call_second result |
Expected: both completed results survive the snapshot round trip. This also happens without a reload. Repeating the final approval adds no effect or model call; execution is held until the batch is approved, as documented.
Code Sample
Minimal local reproduction (no reload needed)From this repository revision, install the local core/ag-ui packages into a temporary environment with fastapi, httpx, and starlette. Save the following as minimal_snapshot_repro.py and run python minimal_snapshot_repro.py. It prints the four observations above and fails the result-retention assertion. The scripted client's layers follow the repository's StreamingChatClientStub; no approval registry is edited.
"""Local AG-UI queued-result snapshot reproduction; no model/API calls."""
import asyncio
import json
from typing import Any
from agent_framework import (
Agent,
BaseChatClient,
ChatResponse,
ChatResponseUpdate,
Content,
FunctionTool,
ToolApprovalMiddleware,
)
from agent_framework._middleware import ChatMiddlewareLayer
from agent_framework._tools import FunctionInvocationLayer
from agent_framework._types import ResponseStream
from agent_framework.observability import ChatTelemetryLayer
from agent_framework_ag_ui import (
AgentFrameworkAgent,
InMemoryAGUIThreadSnapshotStore,
add_agent_framework_fastapi_endpoint,
)
from fastapi import FastAPI
from fastapi.testclient import TestClient
class ScriptedClient(FunctionInvocationLayer, ChatMiddlewareLayer, ChatTelemetryLayer, BaseChatClient):
def __init__(self) -> None:
super().__init__(middleware=[])
self.calls = 0
self.input_results: list[list[str]] = []
def _inner_get_response(
self, *, messages: Any, stream: bool = False, options: Any, **kwargs: Any
) -> ResponseStream:
assert stream
self.input_results.append([c.call_id for m in messages for c in m.contents if c.type == "function_result"])
return ResponseStream(self.updates(), finalizer=ChatResponse.from_updates)
async def updates(self):
self.calls += 1
contents = [Content.from_text(text="Done.")]
if self.calls == 1:
contents = [
Content.from_function_call(
call_id=f"call_{label}", name="record", arguments=json.dumps({"label": label})
)
for label in ("first", "second")
]
yield ChatResponseUpdate(role="assistant", message_id=f"model-{self.calls}", contents=contents)
effects: list[str] = []
def record(label: str) -> str:
effects.append(label)
return f"recorded:{label}"
model = ScriptedClient()
agent = Agent(
name="snapshot-repro",
client=model,
tools=[
FunctionTool(name="record", description="Record a local value", func=record, approval_mode="always_require")
],
middleware=[ToolApprovalMiddleware()],
)
app, store = FastAPI(), InMemoryAGUIThreadSnapshotStore()
add_agent_framework_fastapi_endpoint(
app,
AgentFrameworkAgent(agent=agent, require_confirmation=False),
path="/agent",
snapshot_store=store,
snapshot_scope_resolver=lambda _: "local-test",
)
def post(
client: TestClient, stage: str, *, text: str | None = None, approval: str | None = None
) -> list[dict[str, Any]]:
payload: dict[str, Any] = {
"threadId": "thread",
"runId": stage,
"messages": [{"role": "user", "content": text}] if text else [],
}
if approval:
payload["resume"] = [{"interruptId": approval, "status": "resolved", "payload": {"approved": True}}]
response = client.post("/agent", json=payload)
assert response.status_code == 200
events = [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: ")]
assert not [e for e in events if e["type"] == "RUN_ERROR"]
return events
def approval_id(events: list[dict[str, Any]]) -> str:
finished = [e for e in events if e["type"] == "RUN_FINISHED"][-1]
return finished["outcome"]["interrupts"][0]["id"]
with TestClient(app) as client:
first = post(client, "initial", text="Record both values")
second = post(client, "first-approval", approval=approval_id(first))
assert effects == [] # Queued decisions do not release a partial batch.
completed = post(client, "second-approval", approval=approval_id(second))
wire_results = [e["toolCallId"] for e in completed if e["type"] == "TOOL_CALL_RESULT"]
saved = asyncio.run(store.get(scope="local-test", thread_id="thread"))
assert saved is not None
stored_results = [m["tool_call_id"] for m in saved.messages if m.get("role") == "tool"]
post(client, "next-user-turn", text="What happened?")
assert effects == ["first", "second"]
assert wire_results == ["call_first", "call_second"]
assert model.input_results[1] == wire_results # Current turn receives both results.
print(
json.dumps(
{"effects": effects, "SSE": wire_results, "snapshot": stored_results, "next_turn": model.input_results[-1]}
)
)
assert stored_results == model.input_results[-1] == wire_results, "snapshot round trip lost a completed tool result"Error Messages / Stack Traces
No RUN_ERROR occurs on normal approval or reload. The reproduction ends with:
AssertionError: snapshot round trip lost a completed tool resultPackage Versions
agent-framework-core 1.19.0, agent-framework-ag-ui 1.4.0, editable at the SHA above. Python 3.12.11, macOS arm64. Local ASGI transport, scripted chat client, and in-memory snapshots; no live model or external storage.
Additional Context
Found while independently checking #8758; that alias-conflict error did not reproduce in this fixture. Historical #6828/#6910 cover related snapshot loss through synthetic confirm_changes; this uses native queued approvals. The original reports helped locate the boundary.
Local tracing narrows the loss to _agent_run.py native-result/snapshot reconciliation: the earlier collected approval is absent from current messages when its result is processed. No SDK source was changed.
Disclosure: Mission, investigated with Codex. Independently rerun; six-case local checks yield three passing execution/retry controls and three failing snapshot invariants. Three existing endpoint controls also pass.
Source: microsoft/agent-framework