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
Now let's find
raw_archiveand grep all callers ofappend_history,archive(,raw_archive(.Assistant
Now let's look at context.py to see build_system_prompt and where read_unprocessed_history is called.
Assistant
Let's check
command/builtin.pyaround line 215 for/newcommand handling, andsession/manager.pyaround line 381 for clearing sessions.Assistant
Now let's find where
enforce_file_capis called withon_archivecallback (raw_archive fallback for idle compaction perhaps).Assistant
Now let's check
compact_idle_session(line ~890-955) that callsself.archive(archive_msgs)at line 933, session_key = session_key param already available.Let's now check tests directory for existing memory tests to understand conventions.
Assistant
Now let's view the full
Consolidatorclass definition (get context for lines likesessions,storerefs), plus check forSessionimport andsession.keyusage inmaybe_consolidate_by_tokensandcompact_idle_session. Let's view full Consolidator init and archive/raw_archive references again with line numbers for editing.Assistant
Now let's implement changes. First,
append_historyin memory.py:Assistant
Now add
read_recent_history_for_promptand internal-session helpers toMemoryStore, and updateraw_archiveto acceptsession_key.Assistant
Now update
raw_archiveto accept and propagatesession_key:Assistant
Now update
Consolidator.archive():Assistant
Now update all internal
self.archive(chunk)calls to passsession_key=session.key:Assistant
All three have
session(orsession_keyvariable incompact_idle_session) in scope. Let's replace each properly.Assistant
Good, key is preserved. Now update builtin.py:
Assistant
Now update
enforce_file_capcall sites in loop.py to pass session_key via lambda/partial:Assistant
Now let's update
context.pyto addsession_keyandunified_sessionparams tobuild_system_promptandbuild_messages, and useread_recent_history_for_prompt.Assistant
Now update
build_messagesto threadsession_keyandunified_sessionthrough:Assistant
Now update loop.py call sites to pass
session_keyandunified_session:Assistant
Good. Now let's check the "MCP background tasks must be drained on close" requirement — search for MCP close/shutdown code.
Assistant
That seems already implemented properly. Now let's check "Session clearing must not wait for archival success" - already satisfied with
_schedule_background. Let's now check test files for context builder and memory to verify signatures expected, then run tests.Assistant
Good, imports fine. Now let's run relevant test suites.
Assistant
This test file exists already and contains tests matching this exact contract. Let's view them fully.
Assistant
Confirmed, same pattern: mock replaces
archivewith signature lackingsession_key. This confirms these tests are outdated relative to the new required interface. This is expected breakage per instructions. Let's confirm all other test suites still pass (broader run):Assistant
Good — that one is pre-existing/unrelated flaky failure, confirmed unrelated to our change. Now let's double check the remaining 9 failures are exactly the ones we expect due to interface signature changes, and write a quick reproduction script to validate the actual bug fix works end-to-end.
Assistant
All expected behaviors verified. Let's clean up the repro script and do a final review of the diff.
Assistant
Looks correct and clean. Now let's also check the
dream:session key generation format matches prefix, and checkcron:job session key format matches too (f"cron:{job.id}").Assistant
Good, matches. Let's also double check
dream_session_key()formatdream:{timestamp}matches prefix"dream:". Confirmed already. Now let's run full test suite once more to confirm final state, and check the failing tests list is exactly as expected (no new failures introduced elsewhere).Assistant
No conflicts. Let's also verify
read_unprocessed_historyis still used correctly bybuild_dream_prompt(unfiltered by design, since Dream should consolidate everything).Assistant
This is correctly untouched — Dream must still see all sessions' unconsolidated history. Now let's do a final full diff review and check
Anyimport already present.Assistant
All changes are syntactically valid and behaviorally verified. Let's do a final review of the checklist.
Checklist review
-
Reproduced the reported error: The issue is a design/architecture bug (no explicit crash), described via a data-flow scenario. I wrote a reproduction script simulating multi-session
history.jsonlwrites (weixin session A, telegram session B) and confirmed that, prior to the fix,read_unprocessed_history()mixes all sessions' entries into any session's prompt (that's exactly what the original code did — no session filtering existed at all, confirmed by readingcontext.py/memory.pysource before editing). -
Confirmed the fix resolves it: My reproduction script (run after the fix) confirms: (a) session A's history is invisible in session B's prompt and vice versa; (b) legacy entries without
session_keyare excluded; (c)unified_session=Truemode includes cross-channel user history while excluding other internal (cron:,dream:,heartbeat) sessions, except a currently-matching internal session can see its own entries.
-
Assistant
-
Edge cases considered: legacy entries (no
session_key), unified-session mode, internal session prefixes (cron:,dream:,heartbeat), the "matching internal session can read own entries" exception,/newarchival, idle compaction (compact_idle_session), token-based consolidation (maybe_consolidate_by_tokens,_consolidate_replay_overflow), raw-archive fallback on LLM failure, and file-cap raw archiving (enforce_file_cap). Session clearing not waiting on archival (already fire-and-forget via_schedule_background) and MCP background task draining on close (already implemented inclose_mcp) were verified as already satisfying the contract. -
Ran existing tests: Full suite run — 4074 passed, 10 failed. 9 of the failures are in test files (
test_consolidate_offset.py::TestNewCommandArchival, , ) that predate this fix and mock // with signatures that don't yet include the now-required parameter mandated by the issue's interface contract — an unavoidable consequence of correctly implementing the mandated interface, matching the guidance "if existing tests break because they need to be updated to reflect the changes... ignore it." The 10th failure () was independently confirmed to already fail identically on the unmodified base repository, unrelated to this change.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.