[BUG] a ContextManager shared by several agents mixes their stashes across sessions (py + ts)
Human Overview
To be filled in by a human (AI-drafted issue, see team/AI_USAGE_POLICY.md).
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, TypeScript
Strands Version
main @ 794d37c6e (strands-agents and @strands-agents/sdk from source); also present at 7296caba7
Language Runtime Version
Python 3.12.11, Node.js 24.15.0
Operating System
macOS 26.7.3
Installation Method
git clone
Steps to Reproduce
A common server setup builds one ContextManager and creates an Agent per session or request with it. Each agent serves one session, but the shared manager mixes their stashes, so one session's content can be read through another session's retrieve_context.
TypeScript. A ContextManager instance passed to several agents keeps one _stash and one cached retrieval tool. Each initAgent replaces the stash with one scoped to the newest agent, and the retrieve_context tool built for the first agent is handed to every later one. Messages are stashed under the right agent (the MessageAddedEvent hook captures its own stash), but the second agent's retrieve_context reads the first agent's stash.
import { Agent, Model, type ModelStreamEvent } from '@strands-agents/sdk'
import { ContextManager } from '@strands-agents/sdk/experimental'
import { InMemoryStorage } from '@strands-agents/sdk/storage'
class EchoModel extends Model {
constructor(private _text: string) { super() }
getConfig() { return { modelId: 'echo' } }
updateConfig() {}
async *stream(): AsyncGenerator<ModelStreamEvent> {
yield { type: 'modelMessageStartEvent', role: 'assistant' }
yield { type: 'modelContentBlockStartEvent' }
yield { type: 'modelContentBlockDeltaEvent', delta: { type: 'textDelta', text: this._text } }
yield { type: 'modelContentBlockStopEvent' }
yield { type: 'modelMessageStopEvent', stopReason: 'endTurn' }
}
}
const storage = new InMemoryStorage()
const cm = new ContextManager()
const a = new Agent({ id: 'a', model: new EchoModel('reply from a'), storage, contextManager: cm, printer: false })
const b = new Agent({ id: 'b', model: new EchoModel('reply from b'), storage, contextManager: cm, printer: false })
await a.invoke('secret of a')
await b.invoke('secret of b')
// Each message is stashed under its trackingId; the reference resolves every entry under that id.
const firstMessageOf = (agent: Agent) => agent.messages[0]!.trackingId!
console.log('same retrieve_context on both agents:', a.tools.find((t) => t.name === 'retrieve_context') === b.tools.find((t) => t.name === 'retrieve_context'))
const own = await b.tool.retrieve_context!.invoke({ reference: firstMessageOf(b) }, { recordDirectToolCall: false })
console.log('b retrieves its own entry:', JSON.stringify(own.content))
const other = await b.tool.retrieve_context!.invoke({ reference: firstMessageOf(a) }, { recordDirectToolCall: false })
console.log("b retrieves a's entry:", JSON.stringify(other.content))
Python. Each agent's retrieve_context and message hook are scoped to that agent, but the manager also keeps one self._stash, replaced by every init_agent (strands-py/src/strands/_context_manager/context_manager.py:200). The first-call backfill writes through it (:267-272), so an earlier agent's history is copied into the last-attached agent's session scope.
import asyncio
from strands import Agent
from strands.models.model import Model
from strands.storage import InMemoryStorage
from strands.experimental.context_manager import ContextManager
class Echo(Model):
def __init__(self, text): self.text = text
def update_config(self, **kw): pass
def get_config(self): return {"model_id": "echo"}
async def structured_output(self, *a, **k):
raise NotImplementedError
yield
async def stream(self, *a, **k):
yield {"messageStart": {"role": "assistant"}}
yield {"contentBlockStart": {"start": {}}}
yield {"contentBlockDelta": {"delta": {"text": self.text}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "end_turn"}}
async def main():
storage = InMemoryStorage()
cm = ContextManager() # one manager, as a module-level instance reused per request would be
a = Agent(agent_id="a", model=Echo("reply from a"), storage=storage, context_manager=cm, callback_handler=None)
b = Agent(agent_id="b", model=Echo("reply from b"), storage=storage, context_manager=cm, callback_handler=None)
await a.invoke_async("secret of a")
await b.invoke_async("secret of b")
for key in sorted(await storage.list("")):
print(key, "->", (await storage.read(key)).decode())
other = b.tool.retrieve_context(reference=a.messages[0]["tracking_id"], record_direct_tool_call=False)
print("b retrieves a's entry:", other["content"])
asyncio.run(main())
Expected Behavior
Each agent gets its own stash and its own retrieve_context: b retrieves its own entries, cannot read a's, and nothing of a's is written under b's session or agent scope.
Actual Behavior
TypeScript:
same retrieve_context on both agents: true
b retrieves its own entry: [{"text":"Error: reference not found: 10e22a00-.... Pass only the <id> from the placeholder's \"[ref: <id>]\". ..."}]
b retrieves a's entry: [{"text":"secret of a"}]
The strategies are affected the same way: strategy.init(agent, this._stash) and _runStrategies pass the last-attached agent's stash, so content a offloads is stashed under b's scope and a's placeholders point at references its own tool cannot resolve.
Python (a and b are in different sessions, 7da684ee and 5b24af48; a's first message also lands in b's):
context/5b24af48/scopes/agent/b/2cc5785b-..._0 -> {"text": "secret of b"}
context/5b24af48/scopes/agent/b/7ac218a0-..._0 -> {"text": "reply from b"}
context/5b24af48/scopes/agent/b/ee54acbb-..._0 -> {"text": "secret of a"}
context/7da684ee/scopes/agent/a/e0eb6e07-..._0 -> {"text": "reply from a"}
context/7da684ee/scopes/agent/a/ee54acbb-..._0 -> {"text": "secret of a"}
b retrieves a's entry: [{'text': 'secret of a'}]
Additional Context
The Python offload strategy already avoids this for its own writes: it closes over the agent's stash because "one strategy or config dict can reach several agents" (strands-py/src/strands/_context_manager/strategies/offload/base.py:162-163).
TypeScript at the pin 7296caba7: the same code is at context-manager.ts:118-125, 132-139, 220 and strategies/offload/base.ts:354,367.