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
I'll start by exploring the repository structure to understand the codebase and locate relevant files. Let's first check the current directory.
- Assistant
Good. Let's look at the main files mentioned in the issue: memory.py and context.py.
- Assistant
Let's first examine the memory.py file to understand the current structure.
- Assistant
Let's start by exploring the repository structure and understanding the codebase.
- Assistant
Let me read the memory.py file to understand the current implementation.
- Assistant
Let me read the full memory.py file in sections.
- Assistant
Let me continue reading the memory.py file to see the key methods.
- Assistant
Let me continue reading the memory.py file to see the
raw_archivemethod and other relevant parts. - Assistant
Let me continue reading the memory.py file to see the rest of the Consolidator class.
- Assistant
Let me continue reading the rest of memory.py and also look at context.py.
- Assistant
Now let me look at the context.py file to see the
build_system_promptmethod. - Assistant
Now let me find all callers of
archive()andappend_history()to understand the current call patterns: - Assistant
Now let me check the
append_historyandraw_archivecallers as well. - Assistant
Now let me check the loop.py file to understand how
archive()is called from there, and what session_key info is available: - Assistant
Let me look at the
builtin.pyreference. - Assistant
Let me check how
archive()is called in loop.py more broadly and the callers from the session object. - Assistant
Now let me look at the
enforce_file_capmethod on the Session class. - Assistant
Now let me check how
build_system_promptis called: - Assistant
Let me look at the loop.py code around the
build_messagescalls to understand what session_key info is available there: - Assistant
Let me understand the session key format:
- Assistant
Let me check what internal session keys look like (cron, dream, heartbeat):
- Assistant
Let me also check the
_unified_sessionflag: - Assistant
Let me check the existing test structure:
- Assistant
Now let me run the existing tests to understand the current state:
- Assistant
Good. Now let me also check the context builder tests.
- Assistant
Good. Now let me run the context builder tests.
- Assistant
Let me also run the dream and auto_compact tests:
- Assistant
Let me look at how
build_messagesis called inloop.pymore carefully: - Assistant
Now I need to see the other call site in loop.py. Let me check around line 1140.
- Assistant
Let me also look at the Session's
enforce_file_capmethod: - Assistant
Let me also check the
_effective_session_keymethod and how it relates to unified session: - Assistant
Let me check what
UNIFIED_SESSION_KEYis: - Assistant
Now I have a comprehensive understanding of the codebase. Let me plan the implementation:
Summary of changes needed:
MemoryStore.append_history()- addsession_keyparam, include in JSONL recordMemoryStore.raw_archive()- addsession_keyparam, pass throughMemoryStore.read_recent_history_for_prompt()- new method for filtered historyConsolidator.archive()- addsession_keyparam, pass throughSession.enforce_file_cap()- passsession_keyto on_archive callbackContextBuilder.build_system_prompt()- addsession_key+unified_sessionContextBuilder.build_messages()- addsession_key+unified_session, pass through- Update all callers in loop.py and builtin.py
Let me start implementing:
- Assistant
Now let me implement the changes step by step. First, modify
append_history: - Assistant
Now let me implement the changes step by step. First, modify
append_history: - Assistant
Now let me update the Consolidator.archive() method:
- Assistant
Now let me update Session.enforce_file_cap to pass session_key through:
- Assistant
Now let me update the ContextBuilder to pass session_key:
- Assistant
Good, now let me update the callers in loop.py. First, let me look at the full loop.py to find all call sites:
- Assistant
Let me look at the call sites in loop.py more carefully:
- Assistant
Let me see how
_build_initial_messagesis called to understand what session_key to pass: - Assistant
Let me see how
_build_initial_messagesis called at line 1413. - Assistant
Let me see what session_key is available at line 1140:
- Assistant
Good. Now let me look at how
_build_initial_messagesis called to see what session key is available: - Assistant
Now let me update loop.py. First, update
_build_initial_messages: - Assistant
Now let me update builtin.py to pass session_key to the archive call:
- Assistant
Now I need to update builtin.py to pass session_key to archive. The
session.keyis available in the context. - Assistant
Let me also check the Consolidator's
estimate_session_prompt_tokenswhich uses_build_messages: - Assistant
Let me look at the estimate_session_prompt_tokens method to see if it calls build_messages:
- Assistant
I need to also update
estimate_session_prompt_tokensin the Consolidator to passsession_keyto_build_messages: - Assistant
Now let me run the existing tests to make sure nothing is broken:
- Assistant
Good, memory store tests pass. Let me run the consolidator tests:
- Assistant
Let me run the context builder tests and other related tests:
- Assistant
There's a failing test. Let me look at it:
- Assistant
I see. The test is calling
append_historywithoutsession_keyandbuild_system_promptwithoutsession_key. In my newread_recent_history_for_prompt, whensession_key=Nonein per-session mode, it returns empty.The evaluation contract says "excludes legacy entries without a session key", which is the correct behavior. But for backward compatibility, when
session_keyis not provided (None), I should fall back to the oldread_unprocessed_historybehavior. This way, the existing tests pass, and the real code path (which now passessession_key) gets proper filtering.Let me update
read_recent_history_for_prompt:I see the issue. When
session_keyis None (backward compatibility), I should fall back to old behavior. Let me fix this: - Assistant
I need to fix the fallback behavior. When
session_keyis None andunified_sessionis False, I should fall back to old behavior for backward compatibility: - Assistant
Good, now let me run the tests again:
- Assistant
All 218 tests pass. Let me run a broader test suite to make sure nothing else is broken:
- Assistant
There's a test failure. Let me look at this test:
- Assistant
I see. The test mocks
consolidator.archivewith a function that doesn't acceptsession_key. The instructions say:- If existing tests break because they need to be updated to reflect the changes you made, just ignore it. Evaluation system will not take it into account.
This test needs to be updated to accept the new
session_keyparameter. My fix is correct. Let me continue running other tests to check for more failures. - Assistant
Same type of test failure - mocks that don't accept
session_key. Let me continue checking: - Assistant
Let me check if that last failure is related to my changes:
- Assistant
Let me check if this failure is pre-existing by reverting my changes temporarily:
- Assistant
Good - the MCP presets test failure is pre-existing. Now let me verify the other two failures are purely about mock compatibility:
- Assistant
Both test failures are mock compatibility issues. My fix is correct - the tests need to accept the new
session_keykeyword argument.Let me now run all the tests related to the files I changed to make sure I haven't broken anything else:
- Assistant
All 293 related tests pass. Now let me verify my implementation by reviewing the final state of my changes:
- Assistant
Let me verify the full diff:
- Assistant
The diff looks good. Now let me create a temporary script to verify the cross-session isolation works correctly:
- Assistant
Let me fix the syntax error:
- Assistant
All my isolation tests pass. Let me also test the scenario from the issue (cross-session pollution) to confirm the fix works end-to-end:
- Assistant
The fix is working correctly. Let me run the full test suite one more time to get a complete picture:
- Assistant
Let me verify each failure type:
- Assistant
All failures are the same mock compatibility issue. Let me clean up the temporary test files:
- Assistant
Let me do a final review of all the changes:
- Assistant
Let me do a final verification of the key parts of my implementation:
- Assistant
Let me also verify the
read_recent_history_for_promptmethod and the context builder changes. - Assistant
Let me also verify the context builder changes.
- Assistant
Everything looks correct. Let me run the full test suite one more time to confirm my final results:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.