[BUG] SummarizingConversationManager's pin_first does not work correctly with FileSessionManager and S3SessionManager
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.54.0
Language Runtime Version
Python 3.13.13
Operating System
macOS 16.6.
Installation Method
other
Steps to Reproduce
How to reproduce
The below 2 unit test cases (test_a_resumed_conversation_is_the_one_the_agent_had and test_a_resumed_conversation_keeps_what_no_summary_replaced) can be used to reproduce the 2 bugs. The test asserts the expected behaviors and they fail in these test cases. The unit test uses FileSessionManager as an example. The same bug also can be reproduced on S3SessionManager by simply replacing FileSessionManager with S3SessionManager
Additional notes
The inline code comment inside each unit test case explain more details the expected behavior and some preliminary analysis why the actual behavior diverges.
Unit test code to reproduce the issue
from __future__ import annotations
from typing import TYPE_CHECKING, Final
import pytest
from strands import Agent
from strands.agent.conversation_manager import SummarizingConversationManager
from strands.models.model import Model
from strands.session.file_session_manager import FileSessionManager
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, AsyncIterable
from pathlib import Path
from strands.types.content import Messages
from strands.types.streaming import StreamEvent
from strands.types.tools import ToolSpec
#: The agent's own system prompt. Doubles as how :class:`StubModel` tells an ordinary turn from a summarisation
#: call: the summariser passes its own prompt instead, so anything that is not this string is the summariser.
AGENT_PROMPT: Final = "Agent System Prompt"
#: The model's context window, in tokens. **Tiny on purpose** — a real one is six orders of magnitude larger, and
#: this is what lets fourteen turns of short conversation cross the compression threshold instead of nine thousand.
#: Read by the SDK through ``Model.context_window_limit``, which reads ``get_config()``.
CONTEXT_WINDOW: Final = 200
#: Compress at half the window rather than the SDK's default 0.7, for the same reason the window is small: it
#: brings the first compaction forward into a conversation short enough to read in a failure message.
COMPRESSION_THRESHOLD: Final = 0.5
#: How many messages at the head are pinned. Any value ≥ 1 reproduces half one; 2 pins the first exchange.
PIN_FIRST: Final = 2
#: A cap on the conversation, so a drive that never compacts **fails** instead of looping.
#:
#: The turn compaction lands on is not asserted anywhere, deliberately. It depends on
#: ``Model.count_tokens``, whose default uses ``tiktoken`` when it is installed and a
#: characters-per-token heuristic when it is not — so a hardcoded turn number would make this file's result depend
#: on whether an optional dependency is present. The drive runs until the SDK actually asks the model to
#: summarise, and 30 turns is far past where that happens (measured: turn 14 at 1.54.0, turn 9 at 1.50.2 --
#: which is the drift this paragraph exists to absorb).
MAX_TURNS: Final = 30
SESSION_ID: Final = "repro"
class StubModel(Model):
"""A model that reports token usage the way a provider does, so proactive compression can trigger.
A stub rather than a real provider because a reproduction needing credentials is one nobody runs. Two details
are load-bearing and neither is arbitrary:
* **it reports usage.** ``_estimate_input_tokens`` prefers the last assistant message's ``metadata.usage`` as
its baseline, and the SDK defaults a missing one to ``inputTokens=0, outputTokens=0`` — so a model that
reports nothing pins the projected count near zero and proactive compression never fires at all. Measured by
deleting the ``metadata`` event below: **30 turns against a 200-token window produced no compaction**, and
both ``xfail``s would have reported ``xfail`` for that reason rather than the defect's, which is what the two
unmarked tests are there to catch. The numbers come from the ABC's own :meth:`Model.count_tokens`, which is
what a provider's own count approximates;
* **it can fail the summarisation call and only that call**, which is the trigger for the second half of the
defect. An ordinary turn still succeeds, so the conversation continues exactly as a user's would.
Args:
fail_summarisation: Raise instead of answering when the summariser calls. Ordinary turns are unaffected.
"""
def __init__(self, *, fail_summarisation: bool = False) -> None:
"""Record the behaviour under test and prepare the call counters."""
self.fail_summarisation = fail_summarisation
#: How many ordinary turns have been answered.
self.answers = 0
#: How many times the SDK asked for a summary — the observable that proves compaction was attempted.
self.summarisation_calls = 0
def update_config(self, **model_config: object) -> None:
"""Not used by this reproduction; the ABC requires it."""
msg = "StubModel has no configuration to update"
raise NotImplementedError(msg)
def get_config(self) -> dict[str, object]:
"""The configuration the SDK reads :data:`CONTEXT_WINDOW` out of.
Returns:
A config carrying ``context_window_limit`` — without it ``Model.context_window_limit`` is ``None`` and
the SDK falls back to its own default window, which no short conversation can fill.
"""
return {"context_window_limit": CONTEXT_WINDOW}
def structured_output(
self, output_model: type[object], prompt: Messages, system_prompt: str | None = None, **kwargs: object
) -> AsyncGenerator[dict[str, object]]:
"""Not used by this reproduction; the ABC requires it.
Args:
output_model: The model a caller wanted; named in the error so a stray call is diagnosable.
prompt: Unused.
system_prompt: Unused.
**kwargs: Unused.
Raises:
NotImplementedError: Always. Nothing in this reproduction asks for structured output.
"""
msg = f"StubModel answers text only; {output_model} was asked for"
raise NotImplementedError(msg)
async def stream(
self,
messages: Messages,
tool_specs: list[ToolSpec] | None = None,
system_prompt: str | None = None,
**kwargs: object,
) -> AsyncIterable[StreamEvent]:
"""Answer one turn, or one summarisation request.
Args:
messages: The conversation so far, counted for the reported ``inputTokens``.
tool_specs: Passed to the token count, as a provider's own count would include them.
system_prompt: The agent's prompt on an ordinary turn, the summariser's on a compaction.
**kwargs: The ABC's extension point. Only ``tool_choice`` is inspected, and only to refuse it.
Yields:
The four events ``process_stream`` needs to build one text message, then the usage metadata that
keeps ``projected_input_tokens`` tracking the real size of the conversation.
Raises:
RuntimeError: When ``fail_summarisation`` is set and this is the summarisation call — a stand-in for
a provider outage at the worst possible moment.
"""
# This stub answers with TEXT only. A forced tool choice would make it answer the wrong shape silently,
# which would look like a defect in the SDK rather than in the stub.
assert not kwargs.get("tool_choice"), f"a tool was forced ({kwargs['tool_choice']!r}); this stub has none"
if system_prompt != AGENT_PROMPT:
self.summarisation_calls += 1
if self.fail_summarisation:
msg = "the provider is unavailable"
raise RuntimeError(msg)
text = "SUMMARY"
else:
self.answers += 1
text = f"answer {self.answers}"
input_tokens = await self.count_tokens(messages, tool_specs, system_prompt)
output_tokens = max(1, len(text) // 4)
yield {"messageStart": {"role": "assistant"}}
yield {"contentBlockDelta": {"delta": {"text": text}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "end_turn"}}
yield {
"metadata": {
"usage": {
"inputTokens": input_tokens,
"outputTokens": output_tokens,
"totalTokens": input_tokens + output_tokens,
},
"metrics": {"latencyMs": 0},
}
}
def build_agent(tmp_path: Path, model: Model) -> Agent:
"""The agent a user would write, on a file-backed session.
A **fresh** ``FileSessionManager`` over the same directory every time, because
``RepositorySessionManager.initialize`` refuses a second agent with the same ``agent_id`` on one instance — so
this is also what resuming a session in a new process does. Constructing it on an existing session is what
**restores**; there is no separate load call.
Args:
tmp_path: The session storage directory.
model: The model to answer with.
Returns:
The agent, initialised — which on an existing session means already restored.
"""
return Agent(
model=model,
system_prompt=AGENT_PROMPT,
conversation_manager=SummarizingConversationManager(
pin_first=PIN_FIRST,
proactive_compression={"compression_threshold": COMPRESSION_THRESHOLD},
),
session_manager=FileSessionManager(session_id=SESSION_ID, storage_dir=str(tmp_path)),
callback_handler=None,
)
def texts(agent: Agent) -> list[str]:
"""The text of each message in the agent's transcript.
Args:
agent: Whose transcript to read.
Returns:
One string per message, in order.
"""
return [message["content"][0].get("text", "") for message in agent.messages]
def converse_until_compaction(agent: Agent, model: StubModel) -> int:
"""Hold an ordinary conversation until the SDK compacts it, and return how many turns that took.
Nothing here reaches into the conversation manager: each turn is one ``agent(...)`` call, and compaction
happens when ``BeforeModelCallEvent`` finds the projected input tokens over
:data:`COMPRESSION_THRESHOLD` of :data:`CONTEXT_WINDOW`.
The loop ends on the **summarisation call**, not on the transcript shrinking, because that is the one
observable both arms share: with ``fail_summarisation`` the model is asked and the transcript does not change.
Args:
agent: The agent to converse with.
model: The same agent's model, whose counters say when compaction was attempted.
Returns:
The number of turns taken.
"""
for turn in range(1, MAX_TURNS + 1):
agent(f"question number {turn}")
if model.summarisation_calls:
return turn
pytest.fail(
f"{MAX_TURNS} turns produced no summarisation call, so the conversation never crossed "
f"{COMPRESSION_THRESHOLD:.0%} of a {CONTEXT_WINDOW}-token window and nothing below is about a compaction"
)
def test_a_resumed_conversation_is_the_one_the_agent_had(tmp_path: Path) -> None:
"""**Half one.** After a compaction, rebuilding the agent on the same session must restore what it had.
The offset is short by exactly ``pin_first``, so ``list_messages(offset=…)`` starts ``pin_first`` messages too
early: the pinned head is skipped, and the last ``pin_first`` messages of the summarised range come back
beside the summary that replaced them.
Asserted as a **whole-transcript equality**, because each half of the symptom hides from a narrower check: the
lengths agree (23 and 23), so a length assertion sees nothing, and a "the head is right" assertion would miss
the re-admitted messages.
``removed_message_count`` is *reported* rather than asserted, deliberately. It is the cause, and the module
docstring names two independent ways to fix it — asserting one of them here would prescribe an implementation
and would leave this test red for a fix that took the other route.
Args:
tmp_path: The session storage directory.
"""
model = StubModel()
agent = build_agent(tmp_path, model)
converse_until_compaction(agent, model)
in_memory = texts(agent)
removed = agent.conversation_manager.removed_message_count
# A NEW AGENT ON THE SAME SESSION -- the next process, or the next request. Nothing else is done to it.
restored = texts(build_agent(tmp_path, StubModel()))
assert restored == in_memory, (
f"a resumed session is not the conversation the agent had.\n"
f" in memory ({len(in_memory)}): {in_memory}\n"
f" restored ({len(restored)}): {restored}\n"
f" removed_message_count = {removed}, the offset list_messages was given; {PIN_FIRST} pinned messages "
f"were removed from the store's point of view but kept in memory, and are not counted in it"
)
def test_a_resumed_conversation_keeps_what_no_summary_replaced(tmp_path: Path) -> None:
"""**Half two**, the worse one, and independent of ``pin_first``: messages go with nothing in their place.
Nothing was summarised, so nothing may be skipped on restore. The SDK moves the counter at step 6 of
``_summarize_oldest`` and generates the summary at step 7, and the proactive path swallows the failure — so
the offset survives a compaction that did not happen, and the next restore reads past messages that are still
the only copy of themselves.
Args:
tmp_path: The session storage directory.
"""
model = StubModel(fail_summarisation=True)
agent = build_agent(tmp_path, model)
converse_until_compaction(agent, model)
in_memory = texts(agent)
removed = agent.conversation_manager.removed_message_count
restored = texts(build_agent(tmp_path, StubModel()))
assert restored == in_memory, (
f"a resumed session is missing messages that no summary replaced.\n"
f" in memory ({len(in_memory)}): {in_memory}\n"
f" restored ({len(restored)}): {restored}\n"
f" removed_message_count = {removed}, over a conversation no compaction changed"
)
Expected Behavior
The above unit test should pass.
Actual Behavior
The above unit test fail.
Additional Context
No response
Possible Solution
No response
Related Issues
No response
I'd like to take this if maintainers agree with the observable persistence contract below.
The two deterministic failures point to coordination between SummarizingConversationManager and repository-backed restore, where removed_message_count is used as the restore offset. I would avoid assuming the counter update alone is the correct fix until the pinned-range behavior is covered.
The regression invariant I would implement against is:
- after successful compaction, rebuilding from the same session reproduces the exact in-memory transcript without duplicates or loss; and
- if summary generation fails, rebuilding skips nothing.
I would reuse the reporter's two tests, cover pin_first=0 and pin_first>0, and run the same shared contract through FileSessionManager and the existing S3 fixture/mock. Assertions would cover restored message order and the relevant persistence accounting, while keeping backend-specific changes out unless a test proves they are needed.
I do not expect a public API change. If this invariant and test boundary are correct, please confirm the scope.
Hi! Our Conversation Managers are not integrated with Session Management, however we are about to deprecate Conversation Manager in favor of Context Manager, which does support context-level session management.
Will close this out when the feature is launched out of experimental in the upcoming days: https://github.com/strands-agents/harness-sdk/blob/main/team/designs/0015-context-manager.md https://github.com/strands-agents/harness-sdk/tree/main/strands-ts/src/context-manager
Same root cause, two more triggers, folded in from #6358 (closed as a duplicate of this issue). FileSessionManager and S3SessionManager store a message once, when MessageAddedEvent fires, so anything that changes it afterwards restores differently. Besides pin_first:
- (a)
ContextInjectoradds itsinjectedblock to the latest user message at model-call time, after the message was stored. The restored message has no block. - (b) A background-task result that arrives after the final answer is merged into that assistant message, which is stored as a second record. The restored history has two assistant messages in a row.
Main at 0943408, fake model; SnapshotSessionManager restores both identically:
(a) ContextInjector, FileSessionManager
live: ['user:text+injected', 'assistant:text']
restored: ['user:text', 'assistant:text']
same: False
(b) background task result after the final answer, FileSessionManager
live: ['user:text', 'assistant:toolUse', 'user:toolResult', 'assistant:text+toolUse', 'user:toolResult', 'assistant:text']
restored: ['user:text', 'assistant:toolUse', 'user:toolResult', 'assistant:text', 'assistant:text+toolUse', 'user:toolResult', 'assistant:text']
same: False
Effect on the next request: (b) changes the history from that assistant message on. (a) changes request bytes only on models that take temporary messages; elsewhere only the latest message's injected text is sent. Neither was measured against a live prompt cache.
Repro script (python repro.py, no network)
"""FileSessionManager stores each message once, when it is appended. History edited afterwards restores differently.
Fake model, sessions in a temp dir, no network."""
import tempfile
import time
from strands import Agent, tool
from strands.models import Model
from strands.session import FileSessionManager, SnapshotSessionManager
from strands.storage import LocalFileStorage
from strands.vended_plugins.context_injector import ContextInjector
class FakeModel(Model):
"""Replays scripted assistant blocks, one per call."""
def __init__(self, *replies): self.replies = list(replies)
def update_config(self, **model_config): ...
def get_config(self): return {}
def structured_output(self, output_model, prompt, system_prompt=None, **kwargs): ...
async def stream(self, messages, tool_specs=None, system_prompt=None, **kwargs):
reply = self.replies.pop(0)
yield {"messageStart": {"role": "assistant"}}
if isinstance(reply, dict):
yield {"contentBlockStart": {"start": {"toolUse": reply}}}
yield {"contentBlockDelta": {"delta": {"toolUse": {"input": "{}"}}}}
else:
yield {"contentBlockDelta": {"delta": {"text": reply}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "tool_use" if isinstance(reply, dict) else "end_turn"}}
@tool
def slow_job() -> str:
"""Run a slow job."""
time.sleep(0.3)
return "job finished"
def shape(agent):
return [f"{message['role']}:{'+'.join(next(iter(block)) for block in message['content'])}" for message in agent.messages]
def check(label, make_session_manager, replies, **agent_kwargs):
live = Agent(model=FakeModel(*replies), session_manager=make_session_manager(), agent_id="a", callback_handler=None, **agent_kwargs)
live("user turn 1")
restored = Agent(model=FakeModel(), session_manager=make_session_manager(), agent_id="a", callback_handler=None, **agent_kwargs)
print(f"{label}\n live: {shape(live)}\n restored: {shape(restored)}\n same: {shape(live) == shape(restored)}")
for name, make in [("FileSessionManager", lambda d: FileSessionManager(session_id="s", storage_dir=d)),
("SnapshotSessionManager (control)", lambda d: SnapshotSessionManager(session_id="s", storage=LocalFileStorage(d)))]:
with tempfile.TemporaryDirectory() as a, tempfile.TemporaryDirectory() as b:
check(f"(a) ContextInjector, {name}", lambda: make(a), ["answer 1"],
plugins=[ContextInjector(lambda context: "Reminder: answer in French.")])
check(f"(b) background task result after the final answer, {name}", lambda: make(b),
[{"toolUseId": "t1", "name": "slow_job"}, "The job is running.", "The job finished."],
tools=[slow_job], background_tasks={"always": [slow_job]})