Skip to content

Commit 0152f3c

Browse files
committed
fix(python): iterate adjacency walk with ID closure to prevent tool-block split
When the ID-closure pass moves the cut back to keep a matched pair, the new candidate may land inside an adjacent call/result block — e.g. a TOOL message carrying plain text with no FunctionResultContent for the earlier call. Re-walk adjacency from the candidate and repeat ID closure until a fixed point, so a text-only TOOL result is never orphaned from its call. Covers Copilot review r4415468227 (text-only TOOL orphan) and a chained fixed-point case. Existing pair-invariant controls unchanged.
1 parent c814f99 commit 0152f3c

2 files changed

Lines changed: 107 additions & 2 deletions

File tree

‎python/semantic_kernel/contents/history_reducer/chat_history_reducer_utils.py‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def get_call_result_pairs(history: list[ChatMessageContent]) -> list[tuple[int,
4848
def locate_summarization_boundary(history: list[ChatMessageContent]) -> int:
4949
"""Identify the index of the first message that is not a summary message.
5050
51-
This is indicated by the presence of the SUMMARY_METADATA_KEY in the message metadata.
51+
This is indicated by the presence of SUMMARY_METADATA_KEY in the message metadata.
5252
5353
Returns:
5454
The insertion point index for normal history messages (i.e., after all summary messages).
@@ -146,7 +146,26 @@ def locate_safe_reduction_index(
146146
for index in range(total_count - 1, -1, -1):
147147
suffix_min_call_index[index] = min(suffix_min_call_index[index], suffix_min_call_index[index + 1])
148148

149+
# Iterate adjacency walk and ID closure to a fixed point: moving the cut back to satisfy
150+
# a matched pair may land inside an adjacent call/result block (e.g. a TOOL message with
151+
# plain text but no FunctionResultContent for the earlier call), so re-walk adjacency from
152+
# the new candidate and repeat until neither rule moves the index further back.
149153
while True:
154+
# Re-run adjacency walk from current candidate to avoid cutting inside a tool block.
155+
walk = candidate_index
156+
while walk >= offset_count:
157+
msg = history[walk]
158+
if msg.role in (AuthorRole.DEVELOPER, AuthorRole.SYSTEM):
159+
break
160+
if not contains_function_call_or_result(msg):
161+
break
162+
prev_idx = walk - 1
163+
if (prev_idx < offset_count) or not contains_function_call_or_result(history[prev_idx]):
164+
break
165+
walk -= 1
166+
if walk < candidate_index:
167+
candidate_index = walk
168+
150169
required_call_index = suffix_min_call_index[candidate_index]
151170
if required_call_index >= candidate_index:
152171
break
@@ -172,7 +191,7 @@ def extract_range(
172191
Args:
173192
history: The source history.
174193
start: The index of the first message to extract (inclusive).
175-
end: The index of the last message to extract (exclusive). If None, extracts through end.
194+
end: The last message to extract (exclusive). If None, extracts through end.
176195
filter_func: A function that takes a ChatMessageContent and returns True if the message should
177196
be skipped, False otherwise.
178197
preserve_pairs: If True, ensures that function call and result pairs are either both kept or both skipped.
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
from semantic_kernel.contents.chat_message_content import ChatMessageContent
4+
from semantic_kernel.contents.function_call_content import FunctionCallContent
5+
from semantic_kernel.contents.function_result_content import FunctionResultContent
6+
from semantic_kernel.contents.history_reducer.chat_history_reducer_utils import locate_safe_reduction_index
7+
from semantic_kernel.contents.history_reducer.chat_history_truncation_reducer import ChatHistoryTruncationReducer
8+
from semantic_kernel.contents.utils.author_role import AuthorRole
9+
10+
11+
def _call(cid: str) -> ChatMessageContent:
12+
m = ChatMessageContent(role=AuthorRole.ASSISTANT, content="")
13+
m.items.append(FunctionCallContent(id=cid, function_name=f"f{cid}", plugin_name="p", arguments={}))
14+
return m
15+
16+
17+
def _has_call(history: list[ChatMessageContent], cid: str) -> bool:
18+
return any(isinstance(item, FunctionCallContent) and item.id == cid for msg in history for item in msg.items)
19+
20+
21+
def _has_result(history: list[ChatMessageContent], cid: str) -> bool:
22+
return any(isinstance(item, FunctionResultContent) and item.id == cid for msg in history for item in msg.items)
23+
24+
25+
async def test_public_reducer_keeps_text_tool_without_orphaning_earlier_call():
26+
"""Copilot r4415468227 case through the public reducer API.
27+
28+
[user, call A, call B, TOOL(text result A), assistant, TOOL(result B)]
29+
target_count=2. On base the cut lands at idx=2, dropping call A but keeping
30+
the TOOL message carrying text for A. After the fix the cut moves to idx=1
31+
so both call A and its text-result TOOL are retained.
32+
"""
33+
history = [
34+
ChatMessageContent(role=AuthorRole.USER, content="u0"),
35+
_call("A"),
36+
_call("B"),
37+
ChatMessageContent(role=AuthorRole.TOOL, content="result A as plain text"),
38+
ChatMessageContent(role=AuthorRole.ASSISTANT, content="text"),
39+
ChatMessageContent(
40+
role=AuthorRole.TOOL,
41+
items=[FunctionResultContent(id="B", function_name="fB", plugin_name="p", result="r-B")],
42+
),
43+
]
44+
reducer = ChatHistoryTruncationReducer(target_count=2, threshold_count=0)
45+
reducer.messages = history
46+
result = await reducer.reduce()
47+
48+
assert result is not None
49+
kept = result.messages
50+
assert _has_call(kept, "B"), "call B should be retained"
51+
assert _has_result(kept, "B"), "result B should be retained"
52+
assert _has_call(kept, "A"), "call A must be retained alongside its text TOOL result"
53+
assert any(msg.role == AuthorRole.TOOL and msg.content == "result A as plain text" for msg in kept), (
54+
"the text-only TOOL result for A must be retained alongside call A"
55+
)
56+
57+
58+
def test_chained_closure_requires_multiple_adjacency_id_rounds():
59+
"""n=10 history with two ID pairs and a text-only TOOL block.
60+
61+
Initial cut at 8. ID closure for (B,resultB) moves to 5; ID closure for
62+
(A,resultA) moves to 2; adjacency re-walk from 2 moves to 1 (call X).
63+
On base (no adjacency re-walk) the cut stops at 2, orphaning the text-only
64+
TOOL for X at msg3.
65+
"""
66+
history = [
67+
ChatMessageContent(role=AuthorRole.USER, content="u0"), # 0
68+
_call("X"), # 1
69+
_call("A"), # 2
70+
ChatMessageContent(role=AuthorRole.TOOL, content="text X"), # 3 (no FunctionResult)
71+
ChatMessageContent(role=AuthorRole.ASSISTANT, content="text"), # 4
72+
_call("B"), # 5
73+
ChatMessageContent(
74+
role=AuthorRole.TOOL,
75+
items=[FunctionResultContent(id="A", function_name="fA", plugin_name="p", result="r-A")],
76+
), # 6
77+
ChatMessageContent(role=AuthorRole.TOOL, content="text B"), # 7 (no FunctionResult)
78+
ChatMessageContent(role=AuthorRole.ASSISTANT, content="text"), # 8
79+
ChatMessageContent(
80+
role=AuthorRole.TOOL,
81+
items=[FunctionResultContent(id="B", function_name="fB", plugin_name="p", result="r-B")],
82+
), # 9
83+
]
84+
idx = locate_safe_reduction_index(history, target_count=2, threshold_count=0)
85+
assert idx is not None
86+
assert idx == 1, f"expected cut at call X (idx=1), got {idx}"

0 commit comments

Comments
 (0)