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
Let me start by exploring the repository structure to understand the codebase.
Assistant
Let me see the full memory.py file since it was truncated:
Assistant
Now let me look at the context.py file:
Assistant
Now let me look at where
append_historyandarchiveare being called:Assistant
Now let me check the tests directory:
Assistant
Let me also look at the existing tests for context and recent history:
Assistant
Let me check how the loop sets up the build_messages:
Assistant
Now let me look at the cron and dream sessions to understand internal session keys:
Assistant
Now let me understand where the cron and dream and heartbeat sessions look like. Let me check the cron service for what session key it uses:
Assistant
Let me now look at how the cron service creates a session key when it processes a job:
Assistant
Let me check the broader scope - look for "cron:" or "heartbeat" patterns:
Assistant
Now let me check what the existing tests for the consolidator look like, especially what arguments archive is called with:
Assistant
Now let me look at the conftest.py for these tests:
Assistant
Now let's also look at how recent history is used. Let me check test_context_prompt_cache.py:
Assistant
Now I have a good understanding of the issue. Let me check the cron service, especially the cmd_new and the _schedule_background:
Assistant
Let me look at what
enforce_file_capdoes, since it's used in conjunction withraw_archive:Assistant
Now let me understand the full structure. Let me look at the eval contract from the issue more carefully:
The contract requires:
append_history- signature:self, entry: str, *, max_chars: int | None = None, session_key: str | None = Nonearchive- signature:self, messages: list[dict], *, session_key: str | None = Noneraw_archive- signature:self, messages: list[dict], *, max_chars: int | None = None, session_key: str | None = Noneread_recent_history_for_prompt- new method:self, since_cursor: int, *, session_key: str | None, unified_session: bool = False
And:
- Every archive path must propagate the originating
session_key - Recent-history prompt injection is scoped to the current session
- Excludes legacy entries without a session key
- In unified-session mode, include user-channel history across sessions but exclude internal
cron:, , and histories
Assistant
Good. Now let me look at how MCP background tasks are handled on close:
Assistant
Now I understand the codebase. Let me plan the solution:
Plan:
-
append_history- Addsession_keyparameter. When provided, store the session_key in the entry's JSON record. -
raw_archive- Addsession_keyparameter. Pass it toappend_history. -
archive(Consolidator) - Addsession_keyparameter. Pass it toappend_historyandraw_archive. -
read_recent_history_for_prompt- New method on MemoryStore. Returns entries filtered by session_key. In unified_session mode, includes entries from non-internal sessions (those that don't start with , , or are exactly ) plus any matching the given session_key. Excludes legacy entries (no session_key field).
-
Assistant
Now let me check where the session_key flows to enforce_file_cap. The session object has a key attribute, so we can use
session.key. Let me check howenforce_file_capshould be updated:Assistant
Now let me look at what session keys are used. Let me check the
cmd_newarchive call:Assistant
Now I have enough context. Let me look at the loop.py to understand session keys for archive:
Assistant
Now let me trace through the call chain. The
enforce_file_capis called in_save_turnand_process_system_message. The session has akeyattribute. So we need to passsession_keytoenforce_file_capto forward toraw_archive. But that's a Session method, not a context thing. Let me see how enforce_file_cap is called and understand the chain:Assistant
Now I see. The
enforce_file_capcallson_archive(archive_chunk)but doesn't pass the session_key. We need to bind it properly. There are a few options:- Change
enforce_file_capto callon_archive(archive_chunk, session_key=self.key)(but this changes the call signature) - Use a lambda that closes over session_key:
session.enforce_file_cap(on_archive=lambda msgs: self.context.memory.raw_archive(msgs, session_key=session.key))
Looking at the test cases for
enforce_file_cap, let's see:- Change
Assistant
The
on_archiveis called with positional argsarchive_chunk. Let me see all test calls to confirm:Assistant
OK, so the tests use
archive_fn.call_args.args[0]. The cleanest approach is to add an optionalsession_keykwarg toenforce_file_capand have it pass it toon_archive. But this requires changing the call signature ofon_archive.Let me look at how to handle this most elegantly. The cleanest is to allow the session's own key to be passed by
enforce_file_cap, sinceself.keyis available. So the change toenforce_file_capwould be:def enforce_file_cap(self, on_archive=None, limit=FILE_MAX_MESSAGES, *, on_archive_kwargs=None) -> None: ... if archive_chunk and on_archive: on_archive(archive_chunk, **on_archive_kwargs or {})Assistant
Now I have enough context. Let me start making changes. First, let me plan the full set of changes:
Assistant
Now let me start implementing. First, let me look at the existing memory.py more carefully:
Assistant
Now let me check internal session key handling:
Assistant
Good. Now let me start with the implementation. First, let me reproduce the issue to confirm my understanding:
Assistant
Confirmed the issue. Now let me also test the
_MAX_RECENT_HISTORYetc. constants:Assistant
Now let me start making the changes. First, the memory.py:
Assistant
Now let me apply the changes. First,
append_history:Assistant
Let me now make the change. I'll modify memory.py first:
Assistant
Now let me verify the changes:
Assistant
Let me also look at the existing raw_archive and archive:
Assistant
Now let me update the callers. First, let me update the consolidator's
archivecalls within the same file:Assistant
Now let me update these archive calls to pass session_key:
Assistant
Now let me update the cmd_new in builtin.py:
Assistant
Now let me update
enforce_file_capto pass session_key. Let me examine the current code and modify it:Assistant
Now let me check that the existing tests for
enforce_file_capstill pass (the on_archive gets called with kwargs now):Assistant
Good, the existing tests use
archive_fn.call_args.args[0]which still works (they take only positional args and ignore session_key kwarg). Let me also check the auto_compact tests:Assistant
Good. Now let me also look at the test_session_manager_history.py test to make sure I understand the full chain:
Assistant
Good. Now let me update the ContextBuilder to use
read_recent_history_for_promptand pass session_key:Assistant
The build_messages block wasn't found. Let me see what's there:
Assistant
OK the issue is that I wrote
"""Build the complete message list for an LLM call."\"\"\"in the script with double quote escape. Let me try again:Assistant
Now let me update the loop.py callers to pass session_key:
Assistant
Now I need to update the two callers to add session_key and unified_session:
Assistant
Now let me check there's also a build_messages call in agents that I missed. Let me look again:
Assistant
Let me look at the Consolidator's
_build_messagesusage to see if it needs to pass session_key:Assistant
This is a token-count probe using
_build_messagescallback. It's used byConsolidator.estimate_session_prompt_tokens. Since the messages list is reconstructed, this is just for token estimation. We don't necessarily need to pass session_key here but to be safe, let me pass it. Let me pass session.key:Assistant
Now let me check the CronService and others for places that call archive directly:
Assistant
Now let me also check the
append_historyusers:Assistant
Good - only the internal
append_historycalls (raw_archive path and archive path). Both have been updated.Now let me check the runner.py file to see if it uses any memory/archive APIs:
Assistant
Good. Now let me also handle the cron and heartbeat paths. The heartbeat session key is just a string "heartbeat". The cron jobs have keys like
cron:<jobid>. Let me check if there's anywhere these get archived:Assistant
Good. The only callers are in command/builtin.py (cmd_new), which we've already updated. Both
archiveandraw_archivecalls in memory.py are now passing session_key.Let me also look at the heartbeat and how it's invoking context:
Assistant
Let me check
process_direct:Assistant
Good, this uses _process_message which goes through effective_session_key and dispatches. The unified_session logic is already in
_effective_session_key.Now let me look at how
_process_messageuses session_key:Assistant
OK now let me write the reproduction script and verify my fix:
Assistant
My fix works. Now let me make sure all existing tests still pass:
Assistant
These tests are testing the OLD behavior - they don't pass
session_key, so they treat legacy entries as recent history. The new contract requires that legacy entries be excluded. The tests need updating, but I'm not supposed to modify them. Let me check the rest:Assistant
These tests need updating because they were testing the OLD behavior. The contract specifies the new behavior excludes legacy entries. Per instructions, I should not modify these tests, just confirm they break due to the contract change.
Let me run other test files:
Assistant
This test fails because the mock signature doesn't match the new contract signature. Per the contract, it's expected that archive takes session_key. Per instructions, I should ignore tests that break due to contract changes.
Assistant
Now let me also examine and test the MCP background task draining. The test in question verifies the contract requirement: "MCP background tasks must be drained on close"
Assistant
Let me check how unified_session is used in tests and ensure the implementation is consistent:
Assistant
Good. Now let me also check whether there are any specific tests for the new functionality I need to verify:
Assistant
Same issue with this test - the mock function
track_consolidate(messages)doesn't acceptsession_key. Per instructions, ignore these tests.Let me now also check what tests test the close_mcp draining and other functionality:
Assistant
Let me check if this test was already failing before my changes:
Assistant
Good - this test was already failing before my changes. Let me restore my changes:
Assistant
Good. Now let me run my comprehensive verification script:
Assistant
Now let me verify the original reproduction:
Assistant
Let me also write a more comprehensive end-to-end test that mimics the actual cmd_new → archive flow:
Assistant
Excellent! Now let me also verify the ContextBuilder integration. Let me write a test to ensure the system prompt injection respects session_key:
Assistant
All my verification tests pass. Now let me also check the entire test suite, ignoring the tests that need updating per the contract:
Assistant
All directly relevant tests pass. Let me now examine if I need to handle a few more edge cases. Looking at the contract more carefully:
"Session clearing must not wait for archival success"
Let me look at the cmd_new flow:
Assistant
Good - the cmd_new correctly uses
_schedule_backgroundso session clearing is not waiting.Let me look at close_mcp for the MCP background task draining:
Assistant
close_mcpcorrectly drainsself._background_tasksbefore closing MCP servers. This ensures any pending consolidation/archive tasks (which all use_schedule_background) complete before MCP cleanup.Let me now think about edge cases:
-
What if
append_historyis called without session_key by an old/external code path? → Entries are saved without session_key, treated as legacy by readers, and won't be injected across sessions. -
What if a session that has entries from before the fix still reads history? → They get no recent history (because all entries are legacy), which is correct behavior to prevent pollution.
-
What if
append_historyis called withsession_key=""(empty string)? → Currently,if session_key:only adds to record if truthy. Empty string is falsy, so it's not added. This treats it the same as legacy.
Wait, that's a potential issue. Let me check this edge case:
-
Assistant
Now let me also verify the
Nonebehavior:Assistant
Good. Now let me also think about the case where
append_historyis called with session_key but a legacy file has entries without session_key:Assistant
All edge cases pass. Let me also verify the test for one more edge case - making sure the legacy migration code still works:
Assistant
All existing memory_store tests still pass. Now let me also check the autopact_path which checks token consolidation and may interact with my changes:
Assistant
Let me verify one more thing - the enforce_file_cap path now properly tags entries:
Assistant
Let me also check that the relevant tests for the loop pass with my changes:
Assistant
All 9 failed tests are due to the contract change (per instructions, I should ignore them). Let me do final verification on all the related and unrelated test files:
Assistant
4053 tests pass, 9 fail (all due to contract change). Let me see the failure summary:
Assistant
All 9 failing tests are due to contract change. The pre-existing mcp_presets test was already failing before my changes.
Let me also clean up temp scripts:
Assistant
Now let me also verify the consistency of my implementation by reading through the final state of all modified files:
Assistant
All changes are clean. Now let me run the relevant tests one more time:
Assistant
All 321 relevant tests pass.
Now let me write one final comprehensive verification:
Assistant
All 9 verification tests pass. Let me clean up:
Assistant
Now let me check the final list of changes:
Assistant
Let me do one last check on tests that should be passing:
Assistant
All 321 relevant tests pass. Let me also do a final review of the contract requirements:
-
Interface contract:
- ✅
append_history(self, entry: str, *, max_chars: int | None = None, session_key: str | None = None) -> int - ✅
archive(self, messages: list[dict], *, session_key: str | None = None) -> str | None(in Consolidator) - ✅
raw_archive(self, messages: list[dict], *, max_chars: int | None = None, session_key: str | None = None) -> None - ✅
read_recent_history_for_prompt(self, since_cursor: int, *, session_key: str | None, unified_session: bool = False) -> list[dict[str, Any]]
- ✅
-
Functional contract:
- ✅ "Every archive path—including summary, raw fallback, idle compaction, and archival—must propagate the originating into history entries."
-
Assistant
Let me also check that there are no leftover temp files:
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.