Skip to content
TheChatArchiveThe Chat Archive
gpt-5.6-sol· openaiHugging Face ibragim-bad/swe_rebench_07_2026_trajectories

history.jsonl 跨会话注入导致上下文污染 Bug Description history.jsonl 跨会话注入导致上下文污染 问题描述 history.jsonl…

  1. 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_cursor
    T1微信会话 A 触发 Consolidator,写入 2 条摘要 entry0
    T2Telegram 会话 B 触发 Consolidator,写入 1 条摘要 entry0
    T3用户打开 Telegram 会话 B,调用 build_system_prompt读取 cursor>0 的 全部 3 条,混入会话 B 的 system prompt

    此时会话 B 的 # Recent History 中包含了微信会话 A 的摘要,而该摘要是从微信会话提炼的,可能包含:

    • 微信特定的事实或上下文
    • 与 Telegram 会话完全无关的用户偏好
    • 尚未被 Dream 消化/验证的原始摘要

    影响评估

    • 会话上下文污染 — 当前会话的 system prompt 被注入无关会话的事实,可能干扰 LLM 判断

    修复方向建议

    在 entry 中记录 session_key

    在 append_history() 的 entry 中增加 session_key 字段:

    {"cursor": N, "timestamp": "2026-06-09 12:00", "session_key": "telegram:12345", "content": "用户偏好深色主题..."}
    

    然后在 read_unprocessed_history() 或 ContextBuilder 注入时支持按 session_key 过滤。

    Steps to Reproduce

    无

    Expected Behavior

    无

    Relevant Logs

    nanobot Version

    0.2.0

    Python Version

    3.11

    Operating System

    macOS

    Channel / Platform

    Weixin (Personal WeChat)

    LLM Provider

    OpenAI

    Configuration (Optional)

    Additional Context

    No response

    Evaluation contract

    Every archive path—including summary, raw fallback, idle compaction, and /new archival—must propagate the originating session_key into history entries. 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. Session clearing must not wait for archival success, and MCP background tasks must be drained on close.

    Interface

    Type: Function Name: append_history Path: nanobot/agent/memory.py Input: self, entry: str, *, max_chars: int | None = None, session_key: str | None = None Output: int Description: Appends an entry to history.jsonl with an auto-incrementing cursor and optional session_key for cross-session isolation. Use this when writing new history entries that should be scoped to a specific conversation.

    Type: Function Name: archive Path: nanobot/agent/memory.py Input: self, messages: list[dict], *, session_key: str | None = None Output: str | None Description: Summarizes a list of messages via LLM and appends the result to history.jsonl with the given session_key. Falls back to raw_archive on LLM failure to preserve message breadcrumbs.

    Type: Function Name: raw_archive Path: nanobot/agent/memory.py Input: self, messages: list[dict], *, max_chars: int | None = None, session_key: str | None = None Output: None Description: Dumps raw messages directly to history.jsonl without LLM summarization, tagged with an optional session_key. Used as a fallback when the LLM call in archive() fails.

    Type: Function Name: read_recent_history_for_prompt Path: nanobot/agent/memory.py Input: self, since_cursor: int, *, session_key: str | None, unified_session: bool = False Output: list[dict[str, Any]] Description: Returns unprocessed history entries filtered by session_key for prompt injection, supporting per-session isolation. In unified_session mode, it includes entries from non-internal sessions plus any matching the given session_key.

  2. Assistant

    我会沿着归档、提示词注入、会话清理和 MCP 关闭四条路径逐一核对并修复,然后运行针对性测试与相关回归测试。先读取仓库约束和现有实现。

  3. Assistant

    仓库没有安装 rg,我改用 grep 定位。当前约束中特别强调 history.jsonl 的原子写入,修复会保留现有持久化方式。

  4. Assistant

    已确认污染点之外还有两类漏传:会话文件上限触发的 raw fallback,以及 /new 的后台归档。接下来会统一给它们绑定 session.key,并让 prompt 构建显式接收当前会话及 unified-session 策略;旧的无 key 记录只保留给 Dream 消化,不再注入聊天上下文。

  5. Assistant

    核心改动已落地。现在先跑 memory/context/consolidator/unified-session 与 /new 相关测试;预计旧的“无 session_key 也注入”断言需要按新隔离语义调整,但我会先区分真实回归和预期行为变化。

  6. Assistant

    测试暴露了两处兼容性问题:直接调用 ContextBuilder 时没有“当前会话”参数,以及部分现有扩展/测试替换了旧版单参数 archive。我会保留无会话调用的旧读取行为(运行时始终显式传 key),并给归档调用加一个签名兼容层;正式实现仍始终传递 key。

  7. Assistant

    新增回归用例已覆盖按会话过滤、legacy 排除、unified 模式的内部会话规则,以及摘要/失败 fallback 的 key 保留。另发现关闭时若某个后台归档又派生出任务,原先一次 gather 后直接清空可能漏等;我会把关闭逻辑改为持续排空任务列表。

  8. Assistant

    针对性回归目前 126 项全部通过,lint 也通过。最后我会运行完整 Python 测试套件,并检查最终 diff,确认没有遗漏调用点或意外改动。

  9. Assistant

    完整套件已跑到约 30%,此前部分全部通过;当前进入耗时较长的一组测试,进程仍在运行,我会继续等待到完成。

  10. Assistant

    完整套件结果为 4090 通过、1 失败;失败位于 WebUI MCP preset 测试,与本次代码路径无关,且看起来受全套件共享状态影响。我会单独复跑该用例确认是否为既有顺序依赖,再做最终检查。

  11. Assistant

    复跑确认唯一失败是环境中缺少 npx,该用例在真正调用已 monkeypatch 的连接函数前就被依赖预检拦截,与本次改动无关。最终审阅时我收紧了一点:即使调用方未提供 session key,也不应回退注入 legacy 历史;我会同步更新旧测试为显式会话调用,完全遵守隔离契约。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.