[BUG] Python context manager: summaries merge into message 0 and can't be reduced, so long sessions end in permanent overflow
Human Overview
I checked whether #4685 also hits Python. It looks like it does. Every summary gets merged into message 0. Nothing's allowed to shrink message 0. On the harness default, a long session ends up raising ContextWindowOverflowException on every call without recovering.. I'd fix both SDKs the same way.
Checks
- [x] I have updated to the lastest minor and patch version of Strands
- [x] I have checked the documentation and this is not expected behavior
- [x] I have searched ./issues and there are no duplicates of my issue
SDK Language
Python
Strands Version
1.57.1 (also on main at 456b15f)
Language Runtime Version
Python 3.12.5
Operating System
macOS
Installation Method
git clone
Steps to Reproduce
#4685 describes a ratchet in the TypeScript context manager: summaries get merged into message 0, and message 0 is never reduced. I checked the Python port and it has the same three steps, so Agent(context_manager="auto") behaves the same way. "auto" is also the harness default (harness-py/src/strands_harness/defaults.py:9).
SummarizeStrategy._apply_per_messageadds each summary as a newusermessage atmax(1, lowest_index), then calls_repair_alternation(strands-py/src/strands/_context_manager/strategies/offload/summarize.py:111-118)._repair_alternationmerges consecutive same-role messages (offload/base.py:214). When the summarized span starts at index 1, the summary lands right after user message 0 and gets merged into it.- From then on, nothing can reduce message 0.
_get_eligible_messagesskips it (base.py:448,base.py:454), and the overflow fallbackEmergencyTruncateStrategyonly removes messages atindex > 0(truncate.py:165).
So message 0 only grows.
The script under Additional Context shows it with no network or API key. It runs ten invocations of 50 tool calls each on one agent, against a scripted model that reports usage and raises ContextWindowOverflowException once a request goes over its 2,000-token window.
Expected Behavior
Older summaries stay reducible, so there's always room left for new work, and a long session never reaches a point where every call overflows.
Actual Behavior
Every summary ends up in message 0. In the run below that's 65 of 65, while the rest of the conversation shrinks to 3 messages. Once message 0 and the tool specs fill the window, every call raises ContextWindowOverflowException, and the session can't recover. The only thing left to reduce is message 0, and no strategy is allowed to touch it.
invocation 1: ok messages=8 message 0 holds 8 of 8 summaries, ~138 tokens
invocation 4: ok messages=4 message 0 holds 58 of 58 summaries, ~987 tokens
invocation 8: ContextWindowOverflowException messages=3 message 0 holds 65 of 65 summaries, ~1105 tokens
invocation 10: ContextWindowOverflowException messages=3 message 0 holds 65 of 65 summaries, ~1109 tokens
Possible Solution
I'd keep both SDKs on whichever fix #4685 settles on, and I can send the Python change once that's decided. The options listed there work here too. For example, summaries could stay out of message 0, or existing [Summarized: ...] blocks could be summarized again once they take up a set share of the budget. One catch carries over from the source analysis on #4685: _repair_alternation marks the merged message pinned when either side was pinned (base.py:229), so pinning only the original first message won't fix this on its own.
Additional Context
Reproduction script and full output (main, 456b15f)
import asyncio
import json
from strands import Agent, tool
from strands.models import Model
from strands.types.exceptions import ContextWindowOverflowException
WINDOW = 2000
@tool
def read(path: str) -> str:
"""Read a file."""
return f"contents of {path}: " + "x" * 400
class ScriptedModel(Model):
"""Calls `read` 50 times per invocation and answers summary requests with text.
Reports usage, and raises ContextWindowOverflowException when a request exceeds
its window, like a provider would.
"""
def __init__(self):
self.config = {"context_window_limit": WINDOW}
self.turn = 0
self.summaries = 0
def get_config(self):
return self.config
def update_config(self, **kwargs):
self.config.update(kwargs)
async def structured_output(self, *args, **kwargs):
raise NotImplementedError
yield
async def stream(self, messages, tool_specs=None, system_prompt=None, **kwargs):
tokens = await self.count_tokens(messages, tool_specs, system_prompt)
if tokens > WINDOW:
raise ContextWindowOverflowException("input is too long")
yield {"messageStart": {"role": "assistant"}}
if not tool_specs: # summarization request
self.summaries += 1
yield {"contentBlockDelta": {"delta": {"text": "read returned file contents"}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "end_turn"}}
elif self.turn < 50:
self.turn += 1
yield {"contentBlockStart": {"start": {"toolUse": {"toolUseId": f"t{self.turn}", "name": "read"}}}}
yield {"contentBlockDelta": {"delta": {"toolUse": {"input": json.dumps({"path": f"/f{self.turn}"})}}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "tool_use"}}
else:
yield {"contentBlockDelta": {"delta": {"text": "done"}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "end_turn"}}
usage = {"inputTokens": tokens, "outputTokens": 5, "totalTokens": tokens + 5}
yield {"metadata": {"usage": usage, "metrics": {"latencyMs": 1}}}
model = ScriptedModel()
agent = Agent(model=model, tools=[read], context_manager="auto", callback_handler=None)
for invocation in range(1, 11):
model.turn = 0
try:
agent(f"task {invocation}")
outcome = "ok"
except ContextWindowOverflowException:
outcome = "ContextWindowOverflowException"
first = agent.messages[0]
in_first = sum("[Summarized:" in (block.get("text") or "") for block in first["content"])
tokens = asyncio.run(model.count_tokens([first]))
print(
f"invocation {invocation:2}: {outcome:30} messages={len(agent.messages)} "
f"message 0 holds {in_first} of {model.summaries} summaries, ~{tokens} tokens"
)
invocation 1: ok messages=8 message 0 holds 8 of 8 summaries, ~138 tokens
invocation 2: ok messages=8 message 0 holds 19 of 19 summaries, ~325 tokens
invocation 3: ok messages=6 message 0 holds 46 of 46 summaries, ~784 tokens
invocation 4: ok messages=4 message 0 holds 58 of 58 summaries, ~987 tokens
invocation 5: ok messages=4 message 0 holds 60 of 60 summaries, ~1020 tokens
invocation 6: ok messages=4 message 0 holds 62 of 62 summaries, ~1053 tokens
invocation 7: ok messages=4 message 0 holds 64 of 64 summaries, ~1086 tokens
invocation 8: ContextWindowOverflowException messages=3 message 0 holds 65 of 65 summaries, ~1105 tokens
invocation 9: ContextWindowOverflowException messages=3 message 0 holds 65 of 65 summaries, ~1107 tokens
invocation 10: ContextWindowOverflowException messages=3 message 0 holds 65 of 65 summaries, ~1109 tokens
The tool specs (read, plus the retrieve_context tool the context manager adds) take about 795 of those 2,000 tokens. That's why the overflow starts while message 0 is only around 1,100 tokens.
I shrank the window to 2,000 tokens so the overflow shows up in ten invocations instead of days of use. I haven't run this against a live provider, so the token counts come from Model.count_tokens, the SDK's own estimate.
Related Issues
#4685 (same ratchet in TypeScript), #3338 (Python overflow recovery without a convergence check), #4027 (pin_first with sessions)
Reporter here. Before picking a direction I went through all four fix directions from #4685 against the Python code.
Two of them don't fix it in Python:
- Keep the newest tool call and its result out of summarization. Python already does this by default. The "auto" setting never summarizes the newest 4 messages (preserve_recent=4), and the script in this issue still ends with every call overflowing.
- Stop the agent when it keeps fetching the same large tool output back from storage. That ends the loop #4685 ran into, but it never touches message 0. Message 0 is the first message in the conversation, the user's original prompt, and it keeps growing either way.
The third fix, keeping each summary as its own message, needs a deeper change. After every edit, the context manager merges any two neighboring messages that have the same role, so user and assistant messages keep alternating (_repair_alternation). A summary is added as a user message, and message 0 is also a user message. So a summary placed right after message 0 always gets merged into it. So that one needs a role or alternation change.
I'd go with fourth option, re-summarizing the old summaries. It's what SummarizingConversationManager already does with its own summary, and it stays inside SummarizeStrategy without touching alternation or pinning. I tried it locally. When the new summary lands right after message 0, fold the [Summarized: ...] blocks message 0 already holds into the same pass. With that, message 0 held a single summary through all 10 invocations of the repro, nothing gets overflowed, and the existing context-manager tests pass.
I haven't tried the TypeScript side, but summarize.ts has the same shape, so it should carry over. If this direction works for the maintainers, I'll open the Python PR.
Thanks for reporting @roshangardi . Instead of tracking this separately, I'll add the Python case to #4685