ISSUE DESCRIPTION history.jsonl 跨会话注入导致上下文污染 Bug Description history.jsonl 跨会话注入导致上下文污染…
- User
ISSUE DESCRIPTION
history.jsonl跨会话注入导致上下文污染Bug Description
history.jsonl跨会话注入导致上下文污染问题描述
history.jsonl中的每条 entry 来源于 单个会话 的消息摘要(通过Consolidator.archive()生成),但ContextBuilder.build_system_prompt()在注入# Recent History时,未做会话隔离,会将所有会话尚未被 Dream 处理的 entry 全部混入当前会话的 system prompt。数据流分析
写入路径(
Consolidator)Consolidator.archive()被三个调用方触发,均传入 per-session 的消息块:# memory.py:578, 751, 824 chunk = session.messages[session.last_consolidated:end_idx] # 单会话切片 summary = await self.archive(chunk) self.store.append_history(summary, max_chars=_ARCHIVE_SUMMARY_MAX_CHARS)每条写入的 JSONL entry 格式为:
{"cursor": N, "timestamp": "2026-06-09 12:00", "content": "用户偏好深色主题..."}注意:entry 中没有
session_key或chat_id字段,无法追溯来源会话。注入路径(
ContextBuilder)# context.py:64-71 entries = self.memory.read_unprocessed_history(since_cursor=self.memory.get_last_dream_cursor()) if entries: capped = entries[-self._MAX_RECENT_HISTORY:] history_text = "\n".join( f"- [{e['timestamp']}] {e['content']}" for e in capped ) history_text = truncate_text(history_text, self._MAX_HISTORY_CHARS) parts.append("# Recent History\n\n" + history_text)read_unprocessed_history(since_cursor)读取的是 cursor > dream_cursor 的全部条目,不区分来源会话,无任何 session 隔离。问题场景
时序 事件 dream_cursorT1 微信会话 A 触发 Consolidator,写入 2 条摘要 entry 0 T2 Telegram 会话 B 触发 Consolidator,写入 1 条摘要 entry 0 T3 用户打开 Telegram 会话 B,调用 build_system_prompt读取 cursor>0 的 全部 3 条,混入会话 B 的 system prompt 此时会话 B 的
# Recent History中包含了微信会话 A 的摘要,而该摘要是从微信会话提炼的,可能包含:- 微信特定的事实或上下文
- 与 Telegram 会话完全无关的用户偏好
- 尚未被 Dream 消化/验证的原始摘要
影响评估
- 会话上下文污染 — 当前会话的 system prompt 被注入无关会话的事实,可能干扰 LLM 判断
Assistant
Let me start by exploring the repository structure to understand the codebase.
Assistant
Now let me look at the rest of memory.py (specifically the MemoryStore.append_history, raw_archive, and Consolidator sections).
Assistant
Now let me look at the autocompact.py which has
_archive:Assistant
Now let me check the existing test file for memory:
Assistant
Let me also look at the test files for context_builder and consolidator:
Assistant
Now let me check the context tests to understand how the current
build_system_promptis exercised:Assistant
Now let me understand the loop.py to see how session_key works:
Assistant
Now let me look at the loop.py around session_key usage in
_run_agent_loopand how the relevant calls work:Assistant
Let me look at the build_messages function to see if it includes session_key:
Assistant
Now let me look at session.py and session manager to understand session.key handling:
Assistant
Now let me look at how Consolidator.archive() is called - check the callers:
Assistant
Now let me look at loop.py for clear() and understand the session clearing logic:
Assistant
Now I have a great understanding. Let me look at the loop.py around line 1160-1170 and 1490 where
enforce_file_capandraw_archiveare referenced:Assistant
Now I understand. Let me also check the dream-related logic to understand what session_key dream uses:
Assistant
Now I understand the full picture. Let me also look at
_INTERNAL_SESSION_PREFIXES:Assistant
Now let me check all the tests:
Assistant
Now I have a comprehensive understanding. Let me draft a plan:
Plan:
MemoryStore.append_history- Addsession_key: str | None = Noneparameter. Persist it into the JSONL record.MemoryStore.raw_archive- Addsession_keyparameter, propagate toappend_history.Consolidator.archive- Addsession_keyparameter, propagate toappend_historyandraw_archive.
Assistant
Now let me look at the cron session keys and heartbeat session keys:
Assistant
Good. Now let me check the cron service for session_key generation:
Assistant
Now I have all the context I need. Let me also explore the cron execution:
Assistant
Now let me check the cron session_key usage in execution:
Assistant
Let me look at how cron runs an agent turn:
Assistant
Now I understand the full picture. Let me make a detailed plan:
MemoryStore.append_history- Addsession_key: str | None = Noneparameter. Persist it into the JSONL record.MemoryStore.raw_archive- Addsession_keyparameter, propagate toappend_history.Consolidator.archive- Addsession_keyparameter, propagate toappend_historyandraw_archive.- Add
MemoryStore.read_recent_history_for_prompt- The new function: reads unprocessed entries filtered by session_key, supportsunified_sessionmode. - Update
ContextBuilder.build_system_prompt- Take asession_key: str | None = Noneandunified_session: bool = Falseand useread_recent_history_for_prompt. - Update
ContextBuilder.build_messages- Propagate the new parameters.
Assistant
OK so
cmd_newalready uses_schedule_background. That part is fine. The contract specifies: "Session clearing must not wait for archival success". This already works since archive is scheduled in background. So that's already correct. Let me check if there are any places where archive is awaited during clear.Actually, the only place archive is called from the
cmd_newflow is vialoop._schedule_background(loop.consolidator.archive(snapshot))- that is non-blocking. So this is already correct.Now for "MCP background tasks must be drained on close" - that's about
close_mcp. Let me see the current state:Assistant
So MCP background tasks drain in
close_mcp. The contract says "MCP background tasks must be drained on close". The currentclose_mcpdrains_background_taskswhich includes any background tasks. Let me check what tests useclose_mcp:Assistant
OK, now let me look at the current
build_messagesto understand theunified_sessionhandling:Assistant
So context.py doesn't currently take
unified_session. We need to add that.Now let me also look at how the agent uses session_key in the build_messages:
Assistant
OK. Now I have enough information. Let me start implementing.
First, let me reproduce the issue (create a script):
Assistant
Good. The bug is reproduced - the API doesn't even accept
session_key. Let me now start implementing the fix.Assistant
Now let me look at how
_consolidate_replay_overflowis called:Assistant
Now let me start implementing the fix. First, let's modify
append_history:Assistant
Now let me edit memory.py to make the changes. First, let's look at the broader context:
Assistant
Now I'll edit memory.py to implement the fix. Let me modify the
append_historymethod first:Assistant
I notice the edit removed a blank line. Let me fix that:
Assistant
Good. Now I need to add the
read_recent_history_for_promptmethod and updateraw_archive. Let me first check the rest of the file:Assistant
Now let me update
raw_archive:Assistant
Let me use a more targeted replacement approach:
Assistant
Let me try using sed instead since the replace tool isn't working:
Assistant
Now let me look at the
read_unprocessed_historyto add the newread_recent_history_for_prompt:Assistant
Now I need to add
read_recent_history_for_prompt. Let me also add a helper for filtering by session_key. The contract says:- Recent-history prompt injection is scoped to the current session and excludes legacy entries without a session key.
- In unified_session mode, include user-channel history across sessions but exclude internal
cron:,dream:, andheartbeathistories, except that the currently matching internal session may read its own entries.
So the helper should be:
- Default: include only entries with
session_key == session_key. Exclude entries withoutsession_key(legacy entries are filtered out from per-session injection). - Unified mode: include entries from non-internal sessions (not starting with
cron:,dream:,heartbeat). If the current session is internal, also include its own entries.
Assistant
Now let me verify the change:
Assistant
Now let me update the
Consolidator.archivemethod:Assistant
Now let me update the callers of
archive()inside memory.py to propagate session_key:Assistant
Now let me update the three callers:
Assistant
Now let's update the
ContextBuilder.build_system_promptandbuild_messages:Assistant
Now let me update the call sites of
build_messagesandarchive/raw_archive. Let me first update the call sites inloop.py:Assistant
Now let me also update the
cmd_newincommand/builtin.pyto pass session_key:Assistant
Now let me verify the changes by running my reproduce script:
Assistant
All my test cases pass. Now let me run the existing tests to make sure I haven't broken anything:
Assistant
The test failure is expected — the test creates entries without
session_keyand the contract explicitly states legacy entries without a session key are excluded. Let me run all the context tests to see the full picture:Assistant
The 4 failures in
test_context_prompt_cache.pyare expected — they pre-date this change and assert that all entries (including legacy ones without session_key) appear in the prompt. The contract explicitly states that legacy entries without a session key must be excluded. The instruction says to ignore these.Let me continue checking all the tests:
Assistant
Let me check these other test failures to understand what they're expecting:
Assistant
These tests use
loop.consolidator.archive = _failing_summarize- they replace thearchivemethod with a mock that has signature_failing_summarize(messages) -> bool(no session_key). So when my code callsloop.consolidator.archive(snapshot, session_key=ctx.key), the mock is called with a keyword argument it doesn't accept, causing a TypeError.Let me check the actual error:
Assistant
Per the contract, I'll ignore tests broken by the API signature change. Let me look at the remaining failure:
Assistant
Same issue — the test mocks
archive()with a function that doesn't acceptsession_key. Per the contract, this is expected.Let me also check that I haven't broken the auto_compact tests:
Assistant
Let me also run all tests to make sure the rest of the codebase is unaffected:
Assistant
There's 1 additional failure. Let me check it:
Assistant
Good — that test was pre-existing and unrelated. Let me also verify the new feature works for the dream prompt flow:
Assistant
Dream still processes all entries regardless of session_key. Now let me also test edge cases:
Assistant
All edge cases pass. Let me also verify the consolidated offset tests work properly (the ones that are now failing due to mock signatures). Let me look at what they expect:
Assistant
Let me now do a broader check on all callers and also look at the
prepare_sessionintegration in autocompact to ensure I haven't broken anything:Assistant
Let me also check for any tests that we may have missed and ensure my tests in memory_store still pass:
Assistant
All 197 tests pass. Now let me look at the consolidated offset tests carefully. They're failing because of test mock signatures — let me verify by inspecting them more carefully:
Assistant
Yes, these tests mock
archivewith functions that don't acceptsession_key. These are failures caused by the API signature change and should be ignored per the contract.Let me now also check if my code handles a specific edge case - what about
_iter_valid_entrieslegacy entries that lackcursorfield entirely?Assistant
The empty session_key test failed. Let me check the actual output:
Assistant
That's because empty string is treated as "no session_key" (falsy). That's fine and acceptable. Let me remove that edge test:
Assistant
Excellent! All edge cases pass. Let me now also do a final check by inspecting the full context.py file to make sure everything looks right:
Assistant
Now let me check the full memory.py changes:
Assistant
All the changes are in place. Let me also verify the loop.py changes:
Assistant
All changes look good. Let me now look at the full new memory.py file structure:
Assistant
Let me also check whether all the right tests pass with our changes (besides the expected failures):
Assistant
Excellent! 3995 tests pass, only the expected failures remain. Let me also look at the agents test file to be sure:
Assistant
Let me run a final summary check by inspecting the diff:
Assistant
All my diffs look good. Let me also run the broader tests one more time to verify nothing else broke:
Assistant
1031 tests pass. Now let me ensure I'm cleaning up temporary test files:
Assistant
Clean. Now let me also look at the issue contract once more to make sure I cover all the requirements:
Contract checklist:
- ✅
append_history(self, entry: str, *, max_chars: int | None = None, session_key: str | None = None)→ added session_key - ✅
archive(self, messages: list[dict], *, session_key: str | None = None)→ added session_key - ✅
raw_archive(self, messages: list[dict], *, max_chars: int | None = None, session_key: str | None = None)→ added session_key - ✅
read_recent_history_for_prompt(self, since_cursor: int, *, session_key: str | None, unified_session: bool = False)→ added new method
Behavior requirements:
- ✅ Every archive path propagates session_key (summary, raw fallback, idle compaction, /new archival)
- ✅ Recent-history prompt injection is scoped to the current session and excludes legacy entries without a session key
- ✅ In unified-session mode, include user-channel history across sessions but exclude internal cron:, dream:, and heartbeat histories, except that the currently matching internal session may read its own entries
- ✅
Assistant
The bug is fixed. Let me now also verify the complete intended API contract works:
Assistant
The annotation comparison fails due to how string-form annotations work. Let me look at my verification more carefully:
Assistant
All API contracts are met. Now let me create a quick checklist:
Checklist:
- [✅] If an error was reported in the issue description, I have successfully reproduced it. — Yes, my reproduce script originally failed because
append_historydid not acceptsession_key. - [✅] If an error was reported in the issue description, I have confirmed that my fix resolves the error. — Yes, after the fix, the reproduce script passes.
- [✅] I have thought about edge cases and made sure my fix handles them as well. — Yes, tested: legacy unkeyed entries, unified_session mode, internal session scope (cron/dream/heartbeat), self-matching internal sessions, raw_archive fallback, idle compaction, /new archival.
- [✅] I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. — All 3995 tests pass except for 9 that expected the old behavior (which are documented as expected to break per the issue contract).
Let me do one final sanity check by listing the final modified files:
- [✅] If an error was reported in the issue description, I have successfully reproduced it. — Yes, my reproduce script originally failed because
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.