history.jsonl 跨会话注入导致上下文污染 Bug Description history.jsonl 跨会话注入导致上下文污染 问题描述 history.jsonl…
- User
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
Investigating the memory and context code to implement session-scoped history injection.
- Assistant
Implementing session-scoped history: updating memory store, consolidator, context builder, and call sites.
- Assistant
Updating tests and adding coverage for session-scoped history.
- Assistant
已修复
history.jsonl跨会话污染问题。核心改动如下:问题根因
Consolidator.archive()写入的摘要没有session_key,而ContextBuilder.build_system_prompt()通过read_unprocessed_history()读取所有未处理条目,导致其他会话的摘要混入当前会话的# Recent History。修复方案
1. 写入时打上
session_key标签append_history()新增可选参数session_keyarchive()/raw_archive()透传session_key- 所有归档路径均已覆盖:
- Token 压缩(
maybe_consolidate_by_tokens) - Replay 窗口溢出(
_consolidate_replay_overflow) - 空闲会话压缩(
compact_idle_session) /new命令(cmd_new)- 文件上限 raw 归档(
enforce_file_cap)
- Token 压缩(
2. 注入时按会话过滤
新增
read_recent_history_for_prompt():- 普通模式:只返回匹配当前
session_key的条目 - unified_session 模式:包含所有用户频道历史,排除
cron:、dream:、heartbeat内部会话(当前内部会话可读自己的条目)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.