Repository navigation
fix: preserve summary role attribution #3614
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -79,6 +79,7 @@ def __init__( | |||||||||||||||||
| self.summarization_system_prompt = summarization_system_prompt | ||||||||||||||||||
| self.pin_first = max(0, pin_first) if pin_first is not None else None | ||||||||||||||||||
| self._pin_first_applied = False | ||||||||||||||||||
| self._summary_preamble: Message | None = None | ||||||||||||||||||
| self._summary_message: Message | None = None | ||||||||||||||||||
|
|
||||||||||||||||||
| @override | ||||||||||||||||||
|
|
@@ -93,11 +94,28 @@ def restore_from_session(self, state: dict[str, Any]) -> list[Message] | None: | |||||||||||||||||
| """ | ||||||||||||||||||
| super().restore_from_session(state) | ||||||||||||||||||
| self._summary_message = state.get("summary_message") | ||||||||||||||||||
| return [self._summary_message] if self._summary_message else None | ||||||||||||||||||
| if not self._summary_message: | ||||||||||||||||||
| self._summary_preamble = None | ||||||||||||||||||
| return None | ||||||||||||||||||
|
|
||||||||||||||||||
| self._summary_message = cast(Message, {**self._summary_message, "role": "assistant"}) | ||||||||||||||||||
| self._summary_preamble = state.get("summary_preamble") or self._create_summary_preamble() | ||||||||||||||||||
| return [self._summary_preamble, self._summary_message] | ||||||||||||||||||
|
|
||||||||||||||||||
| def get_state(self) -> dict[str, Any]: | ||||||||||||||||||
| """Returns a dictionary representation of the state for the Summarizing Conversation Manager.""" | ||||||||||||||||||
| return {"summary_message": self._summary_message, **super().get_state()} | ||||||||||||||||||
| return { | ||||||||||||||||||
| "summary_preamble": self._summary_preamble, | ||||||||||||||||||
| "summary_message": self._summary_message, | ||||||||||||||||||
| **super().get_state(), | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| @staticmethod | ||||||||||||||||||
| def _create_summary_preamble() -> Message: | ||||||||||||||||||
| """Create the user message that introduces an assistant-authored summary.""" | ||||||||||||||||||
| preamble: Message = {"role": "user", "content": [{"text": "Previous conversation summary:"}]} | ||||||||||||||||||
| _ensure_tracking_id(preamble) | ||||||||||||||||||
| return preamble | ||||||||||||||||||
|
|
||||||||||||||||||
| def apply_management(self, agent: "Agent", **kwargs: Any) -> None: | ||||||||||||||||||
| """Apply management strategy to conversation history. | ||||||||||||||||||
|
|
@@ -176,27 +194,55 @@ def _summarize_oldest(self, agent: "Agent") -> None: | |||||||||||||||||
| apply_pin_first(agent.messages, self.pin_first) | ||||||||||||||||||
| self._pin_first_applied = True | ||||||||||||||||||
|
|
||||||||||||||||||
| # Partition [0, messages_to_summarize_count) into pinned (preserve) and non-pinned (summarize) | ||||||||||||||||||
| protected_to_preserve, to_summarize = partition_pinned(agent.messages, 0, messages_to_summarize_count) | ||||||||||||||||||
|
|
||||||||||||||||||
| if not to_summarize: | ||||||||||||||||||
| raise ContextWindowOverflowException("Cannot summarize: all messages in summarize range are pinned") | ||||||||||||||||||
|
|
||||||||||||||||||
| remaining_messages = agent.messages[messages_to_summarize_count:] | ||||||||||||||||||
|
|
||||||||||||||||||
| # Keep track of the number of messages that have been summarized thus far. | ||||||||||||||||||
| self.removed_message_count += len(to_summarize) | ||||||||||||||||||
| # If there is a summary message, don't count it in the removed_message_count. | ||||||||||||||||||
| if self._summary_message: | ||||||||||||||||||
| self.removed_message_count -= 1 | ||||||||||||||||||
|
|
||||||||||||||||||
| # Generate summary | ||||||||||||||||||
| self._summary_message = self._generate_summary(to_summarize, agent) | ||||||||||||||||||
| previous_summary_messages = tuple( | ||||||||||||||||||
| message for message in (self._summary_preamble, self._summary_message) if message is not None | ||||||||||||||||||
| ) | ||||||||||||||||||
| max_messages_to_summarize = len(agent.messages) - self.preserve_recent_messages | ||||||||||||||||||
| while True: | ||||||||||||||||||
| # Partition the range into pinned messages and messages eligible for summarization. | ||||||||||||||||||
| protected_to_preserve, to_summarize = partition_pinned(agent.messages, 0, messages_to_summarize_count) | ||||||||||||||||||
| persisted_to_summarize = [ | ||||||||||||||||||
| message | ||||||||||||||||||
| for message in to_summarize | ||||||||||||||||||
| if all(message is not previous for previous in previous_summary_messages) | ||||||||||||||||||
| ] | ||||||||||||||||||
|
Comment on lines
+204
to
+208
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 Identity-based filtering breaks across a snapshot round-trip → real messages are silently and permanently lost on the next session restore.
Repro — Pre-PR is immune because its arithmetic ( Every message here already carries a durable
Suggested change
with a helper (and the same substitution at the three other filter sites): def _is_generated_summary_message(self, message: Message, *, preamble_only: bool = False) -> bool:
"""Whether ``message`` is a preamble/summary this manager generated.
Compares on the durable ``tracking_id`` as well as object identity, so the check still
holds after a snapshot round-trip or any other copy of ``agent.messages``.
"""
candidates = (self._summary_preamble,) if preamble_only else (self._summary_preamble, self._summary_message)
for previous in candidates:
if previous is None:
continue
if message is previous:
return True
tracking_id = previous.get("tracking_id")
if tracking_id and message.get("tracking_id") == tracking_id:
return True
return FalseI ran this: the repro flips to |
||||||||||||||||||
| if persisted_to_summarize: | ||||||||||||||||||
| break | ||||||||||||||||||
|
|
||||||||||||||||||
| messages_to_summarize_count += 1 | ||||||||||||||||||
| if messages_to_summarize_count > max_messages_to_summarize: | ||||||||||||||||||
| raise ContextWindowOverflowException("Cannot summarize: insufficient messages for summarization") | ||||||||||||||||||
| messages_to_summarize_count = self._adjust_split_point_for_tool_pairs( | ||||||||||||||||||
| agent.messages, messages_to_summarize_count | ||||||||||||||||||
| ) | ||||||||||||||||||
| if messages_to_summarize_count > max_messages_to_summarize: | ||||||||||||||||||
| raise ContextWindowOverflowException("Cannot summarize: insufficient messages for summarization") | ||||||||||||||||||
|
|
||||||||||||||||||
| protected_to_preserve = [ | ||||||||||||||||||
| message | ||||||||||||||||||
| for message in protected_to_preserve | ||||||||||||||||||
| if all(message is not previous for previous in previous_summary_messages) | ||||||||||||||||||
| ] | ||||||||||||||||||
| remaining_messages = [ | ||||||||||||||||||
| message | ||||||||||||||||||
| for message in agent.messages[messages_to_summarize_count:] | ||||||||||||||||||
| if all(message is not previous for previous in previous_summary_messages) | ||||||||||||||||||
| ] | ||||||||||||||||||
|
|
||||||||||||||||||
| # Only persisted conversation messages contribute to the repository restore offset. | ||||||||||||||||||
| self.removed_message_count += len(persisted_to_summarize) | ||||||||||||||||||
|
|
||||||||||||||||||
| summary_input = [message for message in to_summarize if message is not self._summary_preamble] | ||||||||||||||||||
| if self._summary_message and all(message is not self._summary_message for message in summary_input): | ||||||||||||||||||
| summary_input.insert(0, self._summary_message) | ||||||||||||||||||
|
|
||||||||||||||||||
| self._summary_preamble = self._create_summary_preamble() | ||||||||||||||||||
| self._summary_message = self._generate_summary(summary_input, agent) | ||||||||||||||||||
| # Assign tracking id to the summary message since it bypasses the append method. | ||||||||||||||||||
| _ensure_tracking_id(self._summary_message) | ||||||||||||||||||
|
|
||||||||||||||||||
| # Replace summarized range with protected messages + summary + remaining | ||||||||||||||||||
| agent.messages[:] = protected_to_preserve + [self._summary_message] + remaining_messages | ||||||||||||||||||
| # Replace summarized range with protected messages + attributed summary + remaining | ||||||||||||||||||
| agent.messages[:] = protected_to_preserve + [self._summary_preamble, self._summary_message] + remaining_messages | ||||||||||||||||||
|
|
||||||||||||||||||
| def _generate_summary(self, messages: list[Message], agent: "Agent") -> Message: | ||||||||||||||||||
| """Generate a summary of the provided messages. | ||||||||||||||||||
|
|
@@ -247,7 +293,7 @@ def _generate_summary_with_agent(self, messages: list[Message]) -> Message: | |||||||||||||||||
|
|
||||||||||||||||||
| try: | ||||||||||||||||||
| # Disable structured output for summarization. Summaries are plain text and | ||||||||||||||||||
| # structured output adds toolUse blocks that are invalid in user messages. | ||||||||||||||||||
| # structured output can add toolUse blocks without matching toolResult blocks. | ||||||||||||||||||
| if hasattr(summarization_agent, "_default_structured_output_model"): | ||||||||||||||||||
| summarization_agent._default_structured_output_model = None | ||||||||||||||||||
|
|
||||||||||||||||||
|
|
@@ -260,7 +306,7 @@ def _generate_summary_with_agent(self, messages: list[Message]) -> Message: | |||||||||||||||||
| summarization_agent.messages = messages | ||||||||||||||||||
|
|
||||||||||||||||||
| result = summarization_agent("Please summarize this conversation.") | ||||||||||||||||||
| return cast(Message, {**result.message, "role": "user"}) | ||||||||||||||||||
| return cast(Message, {**result.message, "role": "assistant"}) | ||||||||||||||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 The coercion runs after the extension point, so a custom
Suggest either documenting it as an intentional non-overridable contract in the |
||||||||||||||||||
|
|
||||||||||||||||||
| finally: | ||||||||||||||||||
| summarization_agent.system_prompt = original_system_prompt | ||||||||||||||||||
|
|
@@ -288,7 +334,8 @@ def _generate_summary_with_model(self, messages: list[Message], agent: "Agent") | |||||||||||||||||
| Returns: | ||||||||||||||||||
| A message containing the conversation summary. | ||||||||||||||||||
| """ | ||||||||||||||||||
| return run_async(lambda: generate_summary(messages, agent.model, self.summarization_system_prompt)) | ||||||||||||||||||
| summary = run_async(lambda: generate_summary(messages, agent.model, self.summarization_system_prompt)) | ||||||||||||||||||
| return cast(Message, {**summary, "role": "assistant"}) | ||||||||||||||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 The relabel removes the summary from Bedrock guardrail scanning — the one role-keyed security mechanism in the SDK.
Reachable whenever no later user turn carries text — i.e. mid-tool-loop, where trailing user turns are 🟡 rather than 🔴: it stops the summary being scanned, it doesn't disable guardrails for other messages, and I didn't test an end-to-end bypass against a live guardrail. But this PR is motivated by a security concern, so it's worth deciding deliberately rather than inheriting it as a side effect — either keep scannable content in the preamble, or extend the guardrail-target search to include the manager's attributed summary. |
||||||||||||||||||
|
|
||||||||||||||||||
| def _adjust_split_point_for_tool_pairs(self, messages: list[Message], split_point: int) -> int: | ||||||||||||||||||
| """Adjust the split point to avoid breaking ToolUse/ToolResult pairs. | ||||||||||||||||||
|
|
||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -130,13 +130,14 @@ def test_reduce_context_with_summarization(summarizing_manager, mock_agent): | |
|
|
||
| summarizing_manager.reduce_context(mock_agent) | ||
|
|
||
| # Should have: 1 summary message + 2 preserved recent messages + remaining from summarization | ||
| assert len(mock_agent.messages) == 4 | ||
|
|
||
| # First message should be the summary | ||
| assert mock_agent.messages[0]["role"] == "user" | ||
| first_content = mock_agent.messages[0]["content"][0] | ||
| assert "text" in first_content and "This is a summary of the conversation." in first_content["text"] | ||
| # The user preamble keeps the assistant-authored summary valid as conversation history. | ||
| assert len(mock_agent.messages) == 5 | ||
| preamble_message, summary_message = mock_agent.messages[:2] | ||
| assert preamble_message["role"] == "user" | ||
| assert preamble_message["content"] == [{"text": "Previous conversation summary:"}] | ||
| assert summary_message["role"] == "assistant" | ||
| summary_content = summary_message["content"][0] | ||
| assert "text" in summary_content and "This is a summary of the conversation." in summary_content["text"] | ||
|
|
||
| # Recent messages should be preserved | ||
| assert "Message 3" in str(mock_agent.messages[-2]["content"]) | ||
|
|
@@ -156,9 +157,12 @@ def test_reduce_context_summary_message_has_durable_id(summarizing_manager, mock | |
|
|
||
| summarizing_manager.reduce_context(mock_agent) | ||
|
|
||
| summary_message = mock_agent.messages[0] | ||
| preamble_message, summary_message = mock_agent.messages[:2] | ||
| assert isinstance(preamble_message.get("tracking_id"), str) | ||
| assert preamble_message["tracking_id"] | ||
| assert isinstance(summary_message.get("tracking_id"), str) | ||
| assert summary_message["tracking_id"] | ||
| assert preamble_message["tracking_id"] != summary_message["tracking_id"] | ||
|
|
||
|
|
||
| def test_reduce_context_too_few_messages_raises_exception(summarizing_manager, mock_agent): | ||
|
|
@@ -236,6 +240,7 @@ def test_generate_summary(summarizing_manager, mock_agent): | |
|
|
||
| summary = summarizing_manager._generate_summary(test_messages, mock_agent) | ||
|
|
||
| assert summary["role"] == "assistant" | ||
| summary_content = summary["content"][0] | ||
| assert "text" in summary_content and summary_content["text"] == "This is a summary of the conversation." | ||
|
|
||
|
|
@@ -368,6 +373,7 @@ def test_uses_summarization_agent_when_provided(): | |
| summary = manager._generate_summary(messages, parent_agent) | ||
|
|
||
| # Should use the dedicated summarization agent, not the parent agent | ||
| assert summary["role"] == "assistant" | ||
| summary_content = summary["content"][0] | ||
| assert "text" in summary_content and summary_content["text"] == "Custom summary from dedicated agent" | ||
|
|
||
|
|
@@ -572,17 +578,17 @@ def test_reduce_context_tool_pair_adjustment_works_with_forward_search(): | |
| # messages_to_summarize_count = (3 - 1) * 0.5 = 1 | ||
| # But split point adjustment will move forward from the toolUse, potentially increasing count | ||
| manager.reduce_context(mock_agent) | ||
| # Should have summary + remaining messages | ||
| assert len(mock_agent.messages) == 2 | ||
| assert len(mock_agent.messages) == 3 | ||
|
|
||
| # First message should be the summary | ||
| assert mock_agent.messages[0]["role"] == "user" | ||
| summary_content = mock_agent.messages[0]["content"][0] | ||
| assert mock_agent.messages[0]["content"] == [{"text": "Previous conversation summary:"}] | ||
| assert mock_agent.messages[1]["role"] == "assistant" | ||
| summary_content = mock_agent.messages[1]["content"][0] | ||
| assert "text" in summary_content and "This is a summary of the conversation." in summary_content["text"] | ||
|
|
||
| # Last message should be the preserved recent message | ||
| assert mock_agent.messages[1]["role"] == "user" | ||
| assert mock_agent.messages[1]["content"][0]["text"] == "Latest message" | ||
| assert mock_agent.messages[2]["role"] == "user" | ||
| assert mock_agent.messages[2]["content"][0]["text"] == "Latest message" | ||
|
|
||
|
|
||
| def test_adjust_split_point_exceeds_message_length(summarizing_manager): | ||
|
|
@@ -729,26 +735,54 @@ def test_summarizing_conversation_manager_properly_records_removed_message_count | |
| assert manager.removed_message_count == 0 | ||
|
|
||
| manager.reduce_context(agent) | ||
| # Assert the oldest message is the sumamry message | ||
| assert manager._summary_message["content"][0]["text"] == "Summary" | ||
| # There are 8 messages in the agent messages array, since half will be summarized, | ||
| # 4 will remain plus 1 summary message = 5 | ||
| assert (len(agent.messages)) == 5 | ||
| # Half of the messages were summarized and removed: 8/2 = 4 | ||
| assert manager._summary_message["role"] == "assistant" | ||
| assert len(agent.messages) == 6 | ||
| assert agent.messages[0]["content"] == [{"text": "Previous conversation summary:"}] | ||
| assert agent.messages[1] is manager._summary_message | ||
| assert manager.removed_message_count == 4 | ||
|
|
||
| manager.reduce_context(agent) | ||
| assert manager._summary_message["content"][0]["text"] == "Summary" | ||
| # After the first summary, 5 messages remain. Summarizing again will lead to: | ||
| # 5 - (int(5/2)) (messages to be sumamrized) + 1 (new summary message) = 5 - 2 + 1 = 4 | ||
| assert (len(agent.messages)) == 4 | ||
| # Half of the messages were summarized and removed: int(5/2) = 2 | ||
| # However, one of the messages that was summarized was the previous summary message, | ||
| # so we dont count this toward the total: | ||
| # 4 (Previously removed messages) + 2 (removed messages) - 1 (Previous summary message) = 5 | ||
| assert manager._summary_message["role"] == "assistant" | ||
| assert len(agent.messages) == 5 | ||
| assert agent.messages[0]["content"] == [{"text": "Previous conversation summary:"}] | ||
| assert agent.messages[1] is manager._summary_message | ||
| # The generated preamble and prior summary do not advance the persisted-message offset. | ||
| assert manager.removed_message_count == 5 | ||
|
|
||
|
|
||
| def test_reduce_context_with_pinned_prefix_makes_progress(): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Coverage is missing exactly the lines the 🔴 above lives behind.
Mutation testing found one survivor: deleting the On this test specifically: it does pin down a real bug (against (Credit where it's due: |
||
| mock_model = MockedModelProvider( | ||
| [ | ||
| {"role": "assistant", "content": [{"text": "Summary"}]}, | ||
| {"role": "assistant", "content": [{"text": "Summary"}]}, | ||
| ] | ||
| ) | ||
| messages: Messages = [ | ||
| {"role": "user", "content": [{"text": "Message 1"}]}, | ||
| {"role": "assistant", "content": [{"text": "Response 1"}]}, | ||
| {"role": "user", "content": [{"text": "Message 2"}]}, | ||
| {"role": "assistant", "content": [{"text": "Response 2"}]}, | ||
| {"role": "user", "content": [{"text": "Message 3"}]}, | ||
| {"role": "assistant", "content": [{"text": "Response 3"}]}, | ||
| {"role": "user", "content": [{"text": "Message 4"}]}, | ||
| {"role": "assistant", "content": [{"text": "Response 4"}]}, | ||
| ] | ||
| agent = Agent(model=mock_model, messages=messages) | ||
| manager = SummarizingConversationManager(summary_ratio=0.5, preserve_recent_messages=1, pin_first=1) | ||
|
|
||
| manager.reduce_context(agent) | ||
| tru_first_state = (len(agent.messages), manager.removed_message_count) | ||
| exp_first_state = (7, 3) | ||
| assert tru_first_state == exp_first_state | ||
|
|
||
| manager.reduce_context(agent) | ||
| tru_second_state = (len(agent.messages), manager.removed_message_count) | ||
| exp_second_state = (6, 4) | ||
| assert tru_second_state == exp_second_state | ||
|
|
||
|
|
||
| @patch("strands.agent.conversation_manager.summarizing_conversation_manager.ToolRegistry") | ||
| def test_summarizing_conversation_manager_generate_summary_with_noop_tool_agent_path( | ||
| mock_registry_cls, | ||
|
|
@@ -797,12 +831,7 @@ def test_summarizing_conversation_manager_generate_summary_with_tools_agent_path | |
|
|
||
|
|
||
| def test_generate_summary_disables_structured_output_on_summarization_agent(): | ||
| """Test that structured output is disabled during summarization to avoid toolUse in user messages. | ||
|
|
||
| When a summarization agent has structured_output_model configured, the response contains toolUse blocks. | ||
| Since the summary is converted to a user message, toolUse blocks would violate the model API constraint | ||
| that user messages cannot contain tool uses. The fix disables structured output during summarization. | ||
| """ | ||
| """Test that assistant summaries cannot contain unmatched toolUse blocks.""" | ||
| summary_agent = create_mock_agent() | ||
| structured_output_model = Mock() | ||
| summary_agent._default_structured_output_model = structured_output_model | ||
|
|
@@ -861,9 +890,10 @@ def test_proactive_compression_summarizes_when_exceeded(): | |
| event = BeforeModelCallEvent(agent=agent, invocation_state={}, projected_input_tokens=800) | ||
| registry.invoke_callbacks(event) | ||
|
|
||
| # 20 * 0.5 = 10 summarized → 1 summary + 10 remaining = 11 | ||
| assert len(agent.messages) == 11 | ||
| # 20 * 0.5 = 10 summarized → preamble + summary + 10 remaining = 12 | ||
| assert len(agent.messages) == 12 | ||
| assert agent.messages[0]["role"] == "user" | ||
| assert agent.messages[1]["role"] == "assistant" | ||
|
|
||
|
|
||
| def test_proactive_compression_no_summarize_when_below(): | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Persisted-state contract changed with no version marker — and "No public API changes" is arguable because of it.
get_state()/restore_from_session()are a serialization contract with sessions written by other SDK versions. Adding thesummary_preamblekey is fine (there's precedent for additive keys:sliding_window_conversation_manager.py:134,147). The part that isn't additive is redefining whatsummary_message's role means, with nothing in the serialized dict saying which contract wrote it — while the SDK versions its other serialized contracts (types/_snapshot.py:33,45,60-63,experimental/checkpoint/checkpoint.py:40,57,73-80).Concretely, state written by this branch and read by
mainrestoresagent.messagesas['assistant', 'user']— assistant-first, which I live-verified is rejected by all three model families I could reach (claude-3-haiku,nova-micro,mistral-7b:ValidationException: A conversation must start with a user message). That's exactly what PR #698 (d9f8d8a7) existed to fix. It only bites a rollback or a mixed-version fleet sharing a session store, but sessions outlive SDK versions, so it's worth aschema_versionon this manager's state slice (or at minimum a migration note in the PR body).Also: given this contract shift, would you check whether the repo's
api/needs-reviewlabel applies (team/API_BAR_RAISING.md)? The PR currently carriesbug/python/area-context/size/m. Your call — I'm flagging the workflow, not asserting the verdict.