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 to understand the codebase and locate the relevant files mentioned in the issue description. First, let's get a high-level view.
- Assistant
Let me continue to explore the repository structure and find the specific files mentioned in the issue description.
- Assistant
Great, the memory.py file is in ./nanobot/agent/memory.py. Let me also find context.py (likely in nanobot/agent/ or nanobot/templates/). Let's search for context.py.
- Assistant
Let me look at the memory.py file to understand the current implementation.
- Assistant
Let me scroll down to see the
append_historymethod and other relevant methods. - Assistant
Let me examine the
append_historymethod to understand its current signature. - Assistant
Now I need to see the
archivemethod and other related methods to understand howappend_historyis called. Let me search for "archive" in the file. - Assistant
Let me examine the
archivemethod andraw_archivemethod to understand how they callappend_history. - Assistant
Let me continue viewing the rest of the
archivemethod and theraw_archivemethod. - Assistant
Now let me look at the
Consolidator.archivemethod and the other callers ofappend_history(lines 578, 751, 824 mentioned in the issue). Let me search for those lines. - Assistant
Let me look at the other callers of
append_historyaround lines 751 and 824. Let me search for the specific patterns. - Assistant
Let me look at lines around 688 and 861 where
archiveis called, as mentioned in the issue. - Assistant
Now let me check the other call site around line 824. Let me look at that area.
- Assistant
Let me look at the
compact_idle_sessionmethod to see where it callsarchive. - Assistant
Now I need to look at the
context.pyfile to understand how history is read and injected into the system prompt. - Assistant
Let me look at the rest of the
build_system_promptmethod to see how history is injected. - Assistant
Now let me look at the
read_unprocessed_historymethod in memory.py to understand how it currently works. - Assistant
Let me look at the
read_unprocessed_historymethod. - Assistant
Let me check for existing tests to understand the expected behavior better.
- Assistant
Let me check for tests related to memory or context.
- Assistant
Let me look at the test files for memory and consolidator to understand the expected behavior.
- Assistant
Let me look at more of the test file to understand how tests are structured.
- Assistant
Now let me look at the consolidator tests to see how
archiveis called. - Assistant
Let me look at more of the consolidator test to understand how
archiveis called. - Assistant
Now let me check the test for context builder to see how
build_system_promptis called. - Assistant
Let me look at more of the context builder test to see if there are tests for history injection.
- Assistant
Let me look for tests related to recent history or build_system_prompt.
- Assistant
Let me look at the test around line 298 to see if there's a test for recent history.
- Assistant
Now I have a good understanding of the codebase. Let me also check the test for unified session mode.
- Assistant
Now I have a good understanding of the codebase. Let me also check how
build_system_promptis called to see what parameters are passed. Let me look at the AgentLoop to see how it's called. - Assistant
Let me search for where build_system_prompt is called.
- Assistant
Let me look at line 229 in context.py.
- Assistant
Now I need to understand how
build_messagesis called to see whatsession_keyinformation is available. Let me look at the AgentLoop to see how it callsbuild_messages. - Assistant
Let me look at those lines.
- Assistant
Now I have a good understanding of the issue. Let me create a plan and start implementing the fix. First, let me run the existing tests to ensure they pass before making changes.
- Assistant
Great, the existing tests pass. Now let me also run the consolidator tests and context builder tests.
- Assistant
Great, all tests pass. Now let me run the context builder tests.
- Assistant
Now I have a good understanding of the issue and the codebase. Let me create a plan and start implementing the fix:
Plan
- Modify
MemoryStore.append_historyto accept an optionalsession_keyparameter and include it in the JSONL entry. - Modify
Consolidator.archiveandConsolidator.raw_archiveto accept and passsession_keytoappend_history. - Add a new method
read_recent_history_for_promptthat filters bysession_keyand supports unified session mode. - Modify
ContextBuilder.build_system_promptto acceptsession_keyandunified_sessionparameters and use the new method. - Update the callers of
archiveandraw_archiveto passsession_key. - Update the callers of
build_system_promptto passsession_keyandunified_session.
Let me start implementing the fix. First, let me modify
MemoryStore.append_historyto acceptsession_key. - Modify
- Assistant
Good, now I need to add the
read_recent_history_for_promptmethod. Let me add it afterread_unprocessed_history. First, let me look at the currentread_unprocessed_historymethod to understand its structure. - Assistant
Now I'll add the
read_recent_history_for_promptmethod afterread_unprocessed_history. Let me add it: - Assistant
I see that I accidentally removed the body of
read_unprocessed_history. Let me fix that. - Assistant
Good, now I need to add a blank line after
read_unprocessed_history. Let me fix that. - Assistant
I see there's a duplicate line. Let me fix that.
- Assistant
Good. Now I need to modify the
raw_archivemethod to acceptsession_key. Let me find it. - Assistant
Let me look at the raw_archive method and modify it.
- Assistant
Now I need to modify
raw_archiveto acceptsession_key. Let me edit it. - Assistant
Now I need to modify the
archivemethod in the Consolidator class to acceptsession_key. Let me find it. - Assistant
Let me look at the archive method and modify it.
- Assistant
Now I need to modify the
archivemethod to acceptsession_keyand pass it toappend_historyandraw_archive. Let me edit it. - Assistant
Now I need to update the callers of
archiveto passsession_key. Let me find all the places wherearchiveis called. - Assistant
Now I need to update these three call sites. Let me look at each one. First, let me look at line 737.
- Assistant
I see the first call site at line 737 is in
_consolidate_replay_overflow. I need to update it to passsession.keyassession_key. Let me edit it. - Assistant
Now I need to update the other two call sites. Let me look at line 910.
- Assistant
I see line 910 is in
maybe_consolidate_by_tokens. Let me update it to passsession.key. - Assistant
Now I need to update line 982 in
compact_idle_session. Let me edit it. - Assistant
Now I need to update the
ContextBuilder.build_system_promptmethod to acceptsession_keyandunified_sessionparameters and use the newread_recent_history_for_promptmethod. Let me look at the current implementation. - Assistant
Now I need to modify
build_system_promptto acceptsession_keyandunified_sessionparameters and use the newread_recent_history_for_promptmethod. Let me edit it. - Assistant
Now I need to update the
build_messagesmethod to passsession_keyandunified_sessiontobuild_system_prompt. Let me look at thebuild_messagesmethod. - Assistant
Now I need to update
build_messagesto acceptsession_keyandunified_sessionparameters and pass them tobuild_system_prompt. Let me edit it. - Assistant
Now I need to update the callers of
build_messagesandbuild_system_promptto passsession_keyandunified_session. Let me find all the places where these methods are called. - Assistant
I need to update the callers of
build_messagesinloop.pyto passsession_keyandunified_session. Let me look at those lines. - Assistant
I need to update
_build_initial_messagesto passsession_keyandunified_sessiontobuild_messages. Let me look at how_build_initial_messagesis called and whatsession_keyandunified_sessioninformation is available. - Assistant
Let me look at line 1413 to see how
_build_initial_messagesis called. - Assistant
I see that
ctx.session_keyis available at line 1413. I need to update_build_initial_messagesto acceptsession_keyandunified_sessionand pass them tobuild_messages. Let me first check ifunified_sessionis available in the context. - Assistant
Good,
self._unified_sessionis available. Now I need to update_build_initial_messagesto acceptsession_keyandunified_sessionand pass them tobuild_messages. Let me edit it. - Assistant
Now I need to update the call site at line 1413 to pass
session_keyandunified_session. Let me edit it. - Assistant
I see there's a duplicate block of code. Let me fix that by removing the duplicate lines.
- Assistant
I see there's still an issue with the code. The
record_turn_runtimecall is missing its closing parenthesis. Let me fix that. - Assistant
I see the issue - the
record_turn_runtimecall is incomplete. Let me look at the original code to see what it should be. - Assistant
I see the problem - I accidentally deleted part of the
record_turn_runtimecall. Let me fix this properly by restoring the original code and then making the correct changes. - Assistant
Now let me make the changes to loop.py properly. Let me first look at the original code:
- Assistant
Now let me make the changes properly. I need to update
_build_initial_messagesto accept and passsession_keyandunified_session. - Assistant
Now I need to update the call site at line 1413 to pass
session_keyandunified_session. Let me look at that section again. - Assistant
Now I need to update line 1417-1423 to pass
session_keyandunified_session. Let me edit it. - Assistant
Good, now I need to check the other call site at line 1140. Let me look at it.
- Assistant
I see there's another call site at line 1144 where
build_messagesis called. I need to update it to passsession_keyandunified_session. Let me edit it. - Assistant
Now I also need to check the call site at line 313 where
build_messagesis passed as a callback. Let me look at it. - Assistant
I see that
build_messagesis passed as a callback to the Consolidator. This is used inestimate_session_prompt_tokens. Let me look at how it's called in the Consolidator. - Assistant
Let me look at line 760 to see how
_build_messagesis called. - Assistant
I see that
_build_messagesis called inestimate_session_prompt_tokenswithoutsession_keyorunified_session. This is fine because it's just for token estimation, not for actual prompt injection. Thebuild_messagesmethod has default values for these parameters, so it will work correctly.Now I need to run the existing tests to make sure my changes don't break anything.
- Assistant
Good, the memory store tests pass. Now let me run the consolidator tests.
- Assistant
Great, the consolidator tests pass. Now let me run the context builder tests.
- Assistant
All tests pass. Now let me run a broader set of tests to make sure I haven't broken anything else.
- Assistant
There's a test that's mocking
archivewithout thesession_keyparameter. Let me look at this test to understand what's happening. - Assistant
The test is mocking
archivewithAsyncMock(return_value=True). The issue is that the mock doesn't accept the newsession_keykeyword argument. The test should be updated to accept the new parameter, but the issue description says we shouldn't modify tests. However, the test failure is because the mock is not accepting the new parameter.Actually, looking at the error more carefully:
E TypeError: test_preflight_consolidation_before_llm_call.<locals>.track_consolidate() got an unexpected keyword argument 'session_key'This is a test that has a custom
track_consolidatefunction that doesn't acceptsession_key. Let me look at this specific test. - Assistant
I see the issue. The test at line 222 defines
track_consolidate(messages)which only acceptsmessagesas a positional argument, but nowarchiveis being called withsession_key=session.keyas a keyword argument. The test is using a simple function that doesn't accept that keyword argument.The fix should be to update the test's
track_consolidatefunction to accept**kwargsorsession_keyas a keyword argument. But wait - the instructions say I should NOT modify existing tests. Let me re-read the instructions: - Assistant
The test failure is because the test mocks
archivewith a plain function that doesn't acceptsession_key. Per the instructions, "If existing tests are broken because they need to be updated to reflect the changes you made, just ignore it." Let me run the full suite excluding that specific test to confirm everything else passes. - Assistant
All 1102 tests pass except for the one test that mocks
archivewith a plain function that doesn't accept the newsession_keyparameter. That test failure is expected since it's testing old behavior.Now let me also run the other test files to make sure everything is working correctly.
- Assistant
Let me run without timeout.
- Assistant
Good - only 1 failure is
test_mcp_preset_connects_and_reports_toolswhich is unrelated to my changes (it's in the webui tests). All other tests pass.Now let me verify the changes are complete and correct. Let me review the full diff.
- Assistant
Now let me also check if there are other callers of
append_historyin the codebase that might need updating. - Assistant
There's a call to
loop.consolidator.archive(snapshot)innanobot/command/builtin.pyat line 215. This is the/newcommand which archives the current session when the user starts a new one. Let me check this. - Assistant
I see that
cmd_newcallsloop.consolidator.archive(snapshot)without passingsession_key. This is a caller that needs to be updated. Let me look at the context to see whatctx.keyis available. - Assistant
Now let me also check if there are any other callers of
archivethat I missed. Let me also check if there are any other places whereappend_historyis called withoutsession_key. - Assistant
Good, the only remaining call to
append_historywithoutsession_keyis at line 544 inraw_archive, which we already updated to passsession_key. Let me verify this. - Assistant
Good, the
raw_archivecall is already updated. Now let me run the tests again to make sure everything is working correctly. - Assistant
All tests pass. Now let me write a small test script to verify the fix works correctly - that session_key isolation prevents cross-session context pollution.
- Assistant
The fix is working correctly. Let me now run the full test suite one more time to make sure everything is good.
- Assistant
There are 4 more test failures. Let me check if they're related to my changes.
- Assistant
These are the same type of test failures - the tests mock
archivewith functions that don't accept the newsession_keykeyword argument. Per the instructions, these tests need to be updated to reflect the changes I made. Let me verify all other tests still pass. - Assistant
All 4043 tests pass. The only failing tests are the ones that mock
archivewith functions that don't accept the newsession_keykeyword argument. These are expected failures per the instructions.Now let me check if there are any other edge cases to handle. Let me check if there are
heartbeatsessions. - Assistant
I see that "heartbeat" is used as a key in the codebase. My
_INTERNAL_PREFIXEStuple includes"heartbeat:"(with colon), but the actual key is just"heartbeat"without a colon. Let me check what the actual heartbeat session key looks like. - Assistant
The heartbeat session key is just
"heartbeat"without a colon. My_INTERNAL_PREFIXESincludes"heartbeat:"which won't match"heartbeat". I need to fix this. Let me update the_INTERNAL_PREFIXESto handle both cases. - Assistant
I see there's a duplicate return statement. Let me fix that.
- Assistant
Good, the duplicate return statement is fixed. Now let me run the tests again to make sure everything is working correctly.
- Assistant
Let me also run the full test suite to make sure everything is working correctly.
- Assistant
All 4043 tests pass. Let me also verify the test script again to make sure the heartbeat fix is working correctly.
- Assistant
All tests pass. Let me also check if there are any other callers of
archivethat I missed. Let me also check theenforce_file_capmethod which useson_archive. - Assistant
Let me check how
enforce_file_capcallson_archive. This might be another place wheresession_keyneeds to be propagated. - Assistant
I see that
enforce_file_capcallson_archive(archive_chunk)without passingsession_key. Theon_archivecallback isself.context.memory.raw_archive. This meansraw_archiveis called withoutsession_key, which is a problem.Let me check how
enforce_file_capis called inloop.pyto see if I can pass the session key. - Assistant
I see two places where
enforce_file_capis called. I need to update these calls to pass a wrapped function that includes the session_key. Let me look at the context of these calls to see what session_key is available. - Assistant
I see that at line 1172, the session key
keyis available. I need to update theenforce_file_capcall to pass the session_key. Let me create a lambda that includes the session_key. - Assistant
Now let me update the other
enforce_file_capcall at line 1498. - Assistant
Now let me update line 1498 to pass the session_key.
- Assistant
Now let me run the full test suite again to make sure everything is working correctly.
- Assistant
All 4043 tests pass. Now let me also check if there are any other places where
raw_archiveis called withoutsession_key. Let me also check the_consolidate_replay_overflowmethod to make sure it's passingsession_keycorrectly. - Assistant
Good, all the callers of
raw_archiveare now passingsession_key. Let me now also check if there are any other callers ofarchivethat I missed. - Assistant
All the callers of
archiveare now passingsession_key. Let me now review the final diff to make sure everything is correct. - Assistant
The diff looks clean and correct. Let me run the full test suite one more time to make sure everything is working correctly.
- Assistant
All 4043 tests pass. Let me also run the test script one more time to make sure the fix is working correctly.
- Assistant
All tests pass. Let me clean up the test scripts.
- Assistant
Let me also clean up the tmp files from the test run.
- Assistant
Now let me verify the final state of the changes by looking at the complete diff one more time.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.