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 and understanding the relevant files.
Assistant
Now let me look at the
archiveandraw_archivemethods, and the Consolidator class:Assistant
Now let me look at the
context.pyfile to understand the injection path:Assistant
Now let me understand the call sites of
build_system_promptand the callers ofarchiveandraw_archive:Assistant
Now let me look at the dream-related code and the builtin.py call site:
Assistant
Now let me look at the dream logic and the loop to understand
unified_session:Assistant
Now let me look at the autocompact.py to understand internal session prefixes and how archive is called there:
Assistant
Now let me look at the loop.py to understand how session keys and channels work:
Assistant
Let me look at how
build_messagesis called in the main message processing path, and find where session_key is available for build_system_prompt:Assistant
Let me look at the internal session prefixes and the cron/heartbeat sessions:
Assistant
So internal session keys include
dream:,cron:, andheartbeat. Let me look at howcron:andheartbeatsessions archive. Let me look at the cli/commands.py around the cron and heartbeat code.Assistant
Let me look at
enforce_file_capand howraw_archiveis used as a callback:Assistant
Let me look at the close method in loop.py:
Assistant
The
close_mcpalready drains_background_tasksbefore closing MCP stacks. The contract says "MCP background tasks must be drained on close." Let me check whetherclose_mcpis actually called on shutdown, and whether there are MCP-specific background tasks. Let me check the shutdown path. Actually, the issue contract point 5 seems already satisfied. But let me search for any MCP background tasks that might not be drained.Let me check if
close_mcpis called. Let me search.Assistant
Let me check if MCP creates background tasks that need draining:
Assistant
Now let me look at existing tests for memory and context to understand the expected interface:
Assistant
Let me check the consolidator and dream tests:
Assistant
Now I have enough understanding. Let me also check the
_consolidate_replay_overflowmethod to see the other archive call at line 688.Assistant
Let me check the main close path and the unified session test:
Assistant
Now I have a thorough understanding. Let me check the dream test to ensure
build_dream_promptkeeps using unscoped reads:Assistant
Let me look at the Consolidator
__init__to see how_build_messagesis set:Assistant
Let me see how the Consolidator is constructed in loop.py:
Assistant
Now I have a complete plan. Let me start implementing. First, let me check all
build_messagesandbuild_system_promptcall sites:Assistant
Now let me implement the changes. Starting with
memory.py— adding the internal session helper and updatingappend_history:Assistant
Now let me add the internal session helper after the imports:
Assistant
Now let me update
append_historyto add thesession_keyparameter:Assistant
Now let me add
read_recent_history_for_promptafterread_unprocessed_history:Assistant
Now let me update
raw_archiveto acceptsession_key:Assistant
Now let me update the
Consolidator.__init__to addunified_sessionparam, andarchiveto acceptsession_key:Assistant
Now update
_consolidate_replay_overflow,estimate_session_prompt_tokens, andarchive:Assistant
Now update
estimate_session_prompt_tokensto pass session_key and unified_session:Assistant
Now update
archiveto accept and propagatesession_key:Assistant
Now update the
archive(chunk)call inmaybe_consolidate_by_tokensandcompact_idle_session:Assistant
Now let me update
autocompact.pyto use the shared internal session helper (expand prefixes to include cron and heartbeat):Assistant
Now let me update
context.py—build_system_promptandbuild_messages:Assistant
Now update
build_messagesin context.py to accept and forwardsession_keyandunified_session:Assistant
Now update
loop.py—_build_initial_messages,_state_build,_process_system_message, and the Consolidator construction:Assistant
Now update
_build_initial_messages:Assistant
There's a stray
)at line 618. Let me fix it:Assistant
Let me check the area around the
_build_initial_messagesdefinition for proper spacing:Assistant
Need a blank line between line 589 and 590:
Assistant
Now update
_state_buildto pass session_key and unified_session:Assistant
Now update
_process_system_message'sbuild_messagescall:Assistant
Now update
session/manager.pyenforce_file_capto passsession_key=self.key:Assistant
Let me check tests that use
enforce_file_capwith anon_archivemock:Assistant
Let me check the test callbacks to understand whether they'd break (I shouldn't modify tests, but want to ensure correctness):
Assistant
The tests use
MagicMock()asarchive_fn, which accepts any args includingsession_key=.... Soon_archive(archive_chunk, session_key=self.key)works fine with MagicMock. Good.The test_session_manager_history.py tests — let me check their archive_fn. They likely also use MagicMock or a function. Let me check.
Assistant
Now update
builtin.pycmd_newto passsession_key:Assistant
Let me verify all
_build_initial_messagescallers and run a syntax check:Assistant
Now let me write a reproduction/verification script to test the cross-session isolation behavior:
Assistant
The mock returns "summary" for all. Let me fix the test to use distinct summary content:
Assistant
All isolation checks pass. Now let me run the existing relevant tests to make sure I haven't broken anything:
Assistant
These failures are due to the test mocks for
archivenot accepting the newsession_keykwarg — these are signature-update-needed failures. Let me look at thetest_close_mcp_drains_background_taskstest to verify the drain-on-close behavior is preserved:Assistant
These 4 failures are purely due to the test mocks for
archiveusing a positional-only signature that doesn't accept the newsession_keykwarg — exactly the "tests need updating to reflect signature change" case described in the instructions. The drain-on-close behavior itself is untouched. Let me run the broader agent/command test suites to check for other regressions:Assistant
Same signature-mock issue. Let me confirm it's a mock signature issue:
Assistant
Confirmed —
track_consolidate(messages)doesn't acceptsession_key, a signature-update issue (the other tests in the file useAsyncMockwhich accepts kwargs and pass). Let me run the full agent test directory to get the overall picture:Assistant
Let me investigate the
test_context_prompt_cache.pyfailures and the dream_session one:Assistant
The
test_context_prompt_cache.pyfailures are testing the old unscoped injection behavior — they callappend_history/build_system_promptwithoutsession_key, which under the new contract correctly yields no history (per-session scoping, legacy excluded). These tests reflect outdated behavior and need updating. Now let me check thetest_dream_session.pyfailure, which may be unrelated:Assistant
The
test_dream_session.pyfailure is pre-existing (fails on original code too, with my changes stashed) — it's a flaky mtime-based test, unrelated to my changes.All the failures my change introduced fall into the "tests need updating to reflect the signature/behavior change" category described in the instructions. Let me run a few more suites to ensure no other regressions:
Assistant
Let me run the command tests and the nanobot facade tests:
Assistant
Let me verify there are no other direct
append_historycallers that should now passsession_key:Assistant
Let me double-check no other
consolidator.archive(or.raw_archive(callers exist outside tests:Assistant
All archive paths propagate
session_key. Now let me clean up the temp test file and run the memory/context/consolidator/dream tests one final time to confirm the core tests pass:Assistant
Let me verify no consolidator test asserts on
build_messagescall args that would now differ due to the new kwargs:Assistant
The
build_messages(**kwargs)test accepts the new kwargs and passes (confirmed in the run). Let me do a final import check and run the providers tests to ensure nothing else broke:Assistant
Now let me review the full diff to ensure everything is clean and correct:
Assistant
The diff is clean and complete. Let me do a final broad test run on the full agent suite plus command tests to confirm the only failures are the known signature/behavior-update ones (and the pre-existing flaky dream_session test):
Assistant
The 9 failures are exactly the ones identified as needing test updates to reflect the new interface/behavior (signature mocks for
archivethat don't acceptsession_key, and old unscoped-injection behavior tests). The pre-existing flakytest_dream_sessionmtime test passed this run. All other 1094 tests pass.Let me verify the contract interface signatures one final time programmatically:
Assistant
All interface signatures match the contract exactly. Let me clean up the temp test file (already removed) and submit.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.