Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"})

Copy link
Copy Markdown
Collaborator

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 the summary_preamble key is fine (there's precedent for additive keys: sliding_window_conversation_manager.py:134,147). The part that isn't additive is redefining what summary_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 main restores agent.messages as ['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 a schema_version on 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-review label applies (team/API_BAR_RAISING.md)? The PR currently carries bug/python/area-context/size/m. Your call — I'm flagging the workflow, not asserting the verdict.

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.
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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.

Agent.load_snapshot (agent/agent.py:1607-1611) copy.deepcopys data["messages"] and separately calls restore_from_session. After that, self._summary_preamble / self._summary_message are content-identical but not the same objects as the ones in agent.messages — so every is not previous check (here, and at :224-230, :232-234, :236-237) silently stops excluding them, and removed_message_count += len(persisted_to_summarize) at :233 over-counts by however many artifacts leaked in. That offset is the slice index into persisted session rows (session/repository_session_manager.py:219-223), so the over-count skips real rows forever.

Repro — FileSessionManager, 5 turns, summarize, take_snapshot(preset="session") → load_snapshot, summarize again, restore:

PR    : removed_message_count 5 -> 8   (delta 3, but only ONE real persisted row was consumed)
        LIVE     : [preamble, summary, 'user:question 3', 'assistant:...', 'user:question 4', ...]
        RESTORED : [preamble, summary,                                     'user:question 4', ...]
        >>> 'user:question 3' is gone, and it was never summarized <<<
base  : removed_message_count 5 -> 7   restored == live, no loss

Pre-PR is immune because its arithmetic (+= len(to_summarize) then -= 1) is identity-independent — so this is a regression introduced here. Reachable through the public Agent.take_snapshot/load_snapshot API, and already called that way in-repo per request at multiagent/a2a/executor.py:216 and per retry at vended_plugins/goal/plugin.py:365. (multiagent/swarm.py:115, multiagent/graph.py:256, agent/_agent_as_tool.py:268 all use the same messages = copy.deepcopy(...) shape.)

Every message here already carries a durable tracking_id — minted at :117 for the preamble and :242 for the summary — and types/content.py:236-240 documents it as "Durable, stable UUID… Survives session save/restore and snapshots… Preserved when a message is copied or restored." That's exactly the identity you want:

Suggested change
persisted_to_summarize = [
message
for message in to_summarize
if all(message is not previous for previous in previous_summary_messages)
]
persisted_to_summarize = [
message for message in to_summarize if not self._is_generated_summary_message(message)
]

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 False

I ran this: the repro flips to 5 -> 6 with restored == live and no loss, all 84 tests still pass, ruff clean. Worth a regression test for the exact path too (save → summarize → snapshot round-trip → summarize → assert no persisted message is lost) — nothing in the suite exercises it today, which is how this got through.

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.
Expand Down Expand Up @@ -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

Expand All @@ -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"})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 The coercion runs after the extension point, so a custom summarization_agent's role is silently overwritten with no opt-out.

summarization_agent is a documented public constructor parameter, and this line discards whatever role its result carried — as does :338 for the default model path. Before this PR the overwrite was to user, so this isn't new behavior, but it is newly load-bearing: a caller whose summarization agent deliberately shapes its output (or who depends on the pre-PR user contract) has no way to keep it.

Suggest either documenting it as an intentional non-overridable contract in the summarization_agent docstring (:57-58), or gating the coercion so a subclass overriding _generate_summary can opt out. Cheap either way; mostly I want the choice to be explicit rather than implicit.


finally:
summarization_agent.system_prompt = original_system_prompt
Expand Down Expand Up @@ -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"})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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.

models/bedrock.py:460-475 (_find_last_user_text_message_index) plus the wrap at :509-511 target the last user message with text when guardrail_latest_message=True. Before this PR a summary of possibly-attacker-influenced scraped content was role="user" and got scanned. After it, the last user text message is the constant preamble, so that's all the guardrail sees:

PRE-PR  (summary=user)      -> text sent to guardrail: ['SUMMARY: <untrusted scraped text>']
POST-PR (summary=assistant) -> text sent to guardrail: ['Previous conversation summary:']

Reachable whenever no later user turn carries text — i.e. mid-tool-loop, where trailing user turns are toolResult-only (which is the exact case the :504-506 comment says that index lookup exists for).

🟡 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand All @@ -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):
Expand Down Expand Up @@ -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."

Expand Down Expand Up @@ -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"

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Coverage is missing exactly the lines the 🔴 above lives behind.

pytest --cov=strands.agent.conversation_manager.summarizing_conversation_manager --cov-report=term-missing on this branch:

summarizing_conversation_manager.py   119   5   26   5   93%   98-99, 214, 219, 237, 297->301
  • 98-99 — restore_from_session's no-prior-summary branch
  • 214, 219 — both new ContextWindowOverflowException raise paths of the progress loop this PR adds
  • 237 — summary_input.insert(0, self._summary_message), i.e. the branch that keeps a prior summary from being dropped
  • (297->301 is pre-existing, not yours)

Mutation testing found one survivor: deleting the "summary_preamble" key from get_state() leaves all 84 tests green — because restore_from_session regenerates a textually identical preamble at :102, nothing distinguishes "restored the persisted one" from "silently regenerated one". Also, the += 1 → += 2 mutation in the loop is killed by only this test; nothing else drives the loop past its first iteration.

On this test specifically: it does pin down a real bug (against 1b29bee8 alone the second reduce_context is a byte-identical no-op (7,3)→(7,3); on the full PR (7,3)→(6,4)), so it's genuine, not padding. But it asserts magic tuples with no derivation. Consider also asserting the invariant that actually matters — removed_message_count strictly increases and len(agent.messages) strictly decreases between calls — which survives accounting refactors. And the missing test that matters most is a session save → restore → re-summarize round trip; that's the hole 🔴 #1 shipped through.

(Credit where it's due: tests/strands/session/test_repository_session_manager.py:153 flipping the fixture role to "user" is not a tautology — I mutation-verified it's the only test covering the backward-compat coercion.)

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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def test_initialize_restores_existing_agent_with_summarizing_conversation_manage
"""Test that initializing an existing agent restores its state."""
conversation_manager = SummarizingConversationManager()
conversation_manager.removed_message_count = 1
conversation_manager._summary_message = {"role": "assistant", "content": [{"text": "summary"}]}
conversation_manager._summary_message = {"role": "user", "content": [{"text": "summary"}]}

# Create agent in repository first
session_agent = SessionAgent(
Expand Down Expand Up @@ -179,10 +179,14 @@ def test_initialize_restores_existing_agent_with_summarizing_conversation_manage

# Verify agent state restored
assert agent.state.get("key") == "value"
# The session message plus the summary message
assert len(agent.messages) == 2
assert agent.messages[1]["role"] == "user"
assert agent.messages[1]["content"][0]["text"] == "Hello"
# The attributed summary is prepended to the remaining persisted session message.
assert len(agent.messages) == 3
assert agent.messages[0]["role"] == "user"
assert agent.messages[0]["content"] == [{"text": "Previous conversation summary:"}]
assert agent.messages[1]["role"] == "assistant"
assert agent.messages[1]["content"][0]["text"] == "summary"
assert agent.messages[2]["role"] == "user"
assert agent.messages[2]["content"][0]["text"] == "Hello"
assert agent.conversation_manager.removed_message_count == 1


Expand Down
Loading
Loading