ISSUE DESCRIPTION Bug: retainrecentlegalsuffix 在 else 分支下会导致用户消息被重复归档 Bug Description 在…
- User
ISSUE DESCRIPTION
Bug: retain_recent_legal_suffix 在 else 分支下会导致用户消息被重复归档
Bug Description
在
nanobot/session/manager.py的retain_recent_legal_suffix方法中,当 else 分支(最近 N 条消息全是助手/工具消息)被触发时,由于cut值的计算使用len(tail) - len(kept),而没有考虑用户消息的实际位置,导致用户消息被错误地同时归档到 archive 和 kept 中。具体影响:
- 用户消息同时出现在 archive(待压缩)和 kept(保留)中
- 可能导致 LLM 上下文不一致
Steps to Reproduce
- 会话中消息数量超过 _RECENT_SUFFIX_MESSAGES (默认10条)
- 最近 N 条消息中 不包含任何用户消息 (全是 assistant/tool 角色)
- 在完整会话历史中,最后一条用户消息位于倒数第 11-15 条之间
Expected Behavior
当会话历史中最近 N 条消息全是助手/工具消息,而用户消息位于更早位置时:
- 用户消息不应被重复归档 - 用户消息应该只保留在 kept 中,不应该同时出现在 archive 和 kept 中
- 归档边界应该正确 - cut 值应该基于用户消息的实际位置,而不是简单的 len(tail) - len(kept)
- 上下文连贯性应该保持 - 从用户消息开始的完整上下文应该被保留,不应该被错误切割
假设:
tail = messages[0:100](100条)
latest_user = 85(用户消息位置)
max_messages = 10
期望:
cut = latest_user # 应该是 85,不是 90 archive = tail[:85] # [0-84],不包含用户消息 kept = tail[85:] # [85-99],包含用户消息及其后续内容
结果:
archive 和 kept 没有重叠 ✅
用户消息只在 kept 中 ✅
上下文连贯 ✅
总结
期望行为 :无论用户消息位于何处,它都应该:
- 只出现在 kept 中(保留消息)
- 不出现在 archive 中(归档消息)
- 作为保留消息的起始点,确保上下文连贯
Relevant Logs
nanobot Version
0.2.0
Python Version
3.11
Operating System
Windows
Channel / Platform
Weixin (Personal WeChat)
LLM Provider
OpenAI
Configuration (Optional)
Additional Context
No response
Interface
Type: Function Name: retain_recent_legal_suffix Path: nanobot/session/manager.py Input: self, max_messages: int Output: tuple[list[dict], int] Description: Trims the session's message list to at most
max_messageswhile preserving a legal suffix (ending with a user message if possible). Returns the list of dropped messages and a count of how many of those were already in the consolidated prefix, so callers can archive only new, unconsolidated messages.ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use to restore the file to its original state. You can also reset all changes in the repository using command. Additionally, you can use and to temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call ) using or commands. However you don't need to use or before submitting your changes. In fact, only submits currently unstaged changes because it uses to get the changes that need to be submitted.
Assistant
Let me start by exploring the repository structure to understand the codebase and locate the file mentioned in the issue.
Assistant
Now let me look at the file mentioned in the issue -
nanobot/session/manager.py:Assistant
The file is quite long. Let me search specifically for the
retain_recent_legal_suffixmethod to understand the bug:Assistant
Let me open the file to see the
retain_recent_legal_suffixmethod: <tool_call> <function=bash_terminal> <parameter=command> sed -n '272,325p' nanobot/session/manager.py </tool_call>Assistant
Let me view the
retain_recent_legal_suffixmethod by using the bash terminal to print those specific lines.Assistant
Now I understand the issue. Let me analyze the bug:
-
When the tail (recent messages) contains only assistant/tool messages, the code looks for the latest user message in the full session.
-
However, the current code just does:
retained = list(self.messages[latest_user: latest_user + max_messages]) -
Then when archiving is done elsewhere (likely in
enforce_file_capor another caller), it calculatescutvalue aslen(tail) - len(kept), but this doesn't account for the user message position correctly.
Let me look at where
retain_recent_legal_suffixis called and how the archiving is done to understand the full context:<tool_call> <function=bash_terminal> <parameter=command> sed -n '315,400p' nanobot/session/manager.py </tool_call>
-
Assistant
Let me use bash to view the enforce_file_cap method since that's where the archiving logic is likely located.
Assistant
Now I can see how the archiving works. Let me analyze the issue:
In
enforce_file_cap:before = list(self.messages)- captures the original messagesself.retain_recent_legal_suffix(limit)- modifiesself.messagesto keep only the retained onesdropped_count = before_count - len(self.messages)- calculates how many were droppeddropped = before[:dropped_count]- these are the dropped messagesarchive_chunk = dropped[already_consolidated:]- these get archived
The issue is in . Let me trace through what happens:
Assistant
Let me search for where the cut calculation might be happening.
Assistant
Looking at the issue description more carefully, I see the problem is in the
retain_recent_legal_suffixmethod. When the else branch is triggered (no user message in the tail), the code calculatesretainedbut doesn't properly preserve the user message as the starting point when the tail is assistant-only.Let me trace through the scenario more carefully:
Scenario from issue:
tail = messages[0:100](100 messages total in the session)latest_user = 85(user message at position 85)max_messages = 10
What the code currently does:
retained = list(self.messages[-10:])= messages[90:100] (positions 90-99, all assistant/tool)- No user found in retained (all assistant/tool)
latest_user = 85found in the full sessionretained = list(self.messages[85:85+10])= messages[85:95] (positions 85-94)
Assistant
The user message is about a bug in
retain_recent_legal_suffixwhere the user message ends up in both archive and kept when the else branch is triggered. Let me look at the complete method and understand the exact issue.Assistant
Now I understand the issue. Let me look at the tests directory to understand how the tests are organized, then create a reproduction script to confirm the bug and develop a fix.
Assistant
Let me look at the session tests:
Assistant
Let me first create a reproduction script to verify the bug:
Assistant
Assistant
The user mentioned that the environment does NOT support interactive session commands that expect user input. Let me try again without using the interactive command.
I'll run the python script using bash terminal.
Assistant
Assistant
Now let me implement the fix. I'll need to modify
enforce_file_capto correctly identify dropped messages. The fix is to filter out retained messages from the dropped list.Let me view the exact lines of enforce_file_cap again:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '312,345p' nanobot/session/manager.py </tool_call>
Assistant
I'll use bash terminal to view the enforce_file_cap function and then make the fix.
Assistant
Now I can see the issue clearly. The bug is on line 330 where
dropped = before[:dropped_count]incorrectly assumes the firstdropped_countmessages are the dropped ones. When the else branch inretain_recent_legal_suffixis triggered, retained messages might be scattered in the list, causing user messages to be duplicated.The fix is to filter out retained messages from the dropped list:
Assistant
Now I'll apply the fix to the actual file using the edit command.
Assistant
The fix was applied. Let me verify the change was made correctly:
Assistant
Good, the fix is applied. Now let me create a test script to verify that the fix resolves the bug:
Assistant
Let me investigate this more closely to understand why dropped count is 0:
Assistant
Excellent! The debug output shows:
- Before retain: 100 messages (0-99)
- After retain: 10 messages (indices 85-94 from original)
- The fix works correctly:
- Messages in
before[:90]that are INsession.messages: 5 (these are messages 85-89) - Messages in
before[:90]that are NOT insession.messages: 85 (these are messages 0-84) - Final dropped count (after fix): 85
- User in dropped: False
- Messages in
The fix is working correctly! The user message at position 85 is now correctly excluded from the dropped list because it's still in
session.messages.Now let me run the existing tests to make sure I haven't broken anything:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python -m pytest tests/session/ -v 2>&1 | head -100 </tool_call>
Assistant
The command is running but I need to wait for the output. Let me try running the test again.
Assistant
All 25 session tests passed. Let me also run a broader test suite to make sure the fix doesn't break anything else:
Assistant
Assistant
The command didn't get executed properly. Let me try again with a different approach.
Assistant
Assistant
The heredoc seems to have been sent as part of the previous command but didn't execute. Let me check if the file exists and try to run it.
Assistant
It seems the file wasn't created. Let me try a different approach - using echo with a file.
<tool_call> <function=bash_terminal> <parameter=command> echo 'import sys; sys.path.insert(0, "/nanobot"); from nanobot.session.manager import Session; s = Session(key="test"); [s.add_message("user" if i == 85 else "assistant", f"m{i}") for i in range(100)]; b = list(s.messages); s.retain_recent_legal_suffix(10); dc = 100 - len(s.messages); d = [m for m in b[:dc] if m not in s.messages]; print(f"Dropped: {len(d)}, User in dropped: {any(m.get(chr(39)+'role'+chr(39))==chr(39)+'user'+chr(39) for m in d)}" if len(d) > 0 else "No dropped");' > /tmp/simple_test.py && python /tmp/simple_test.py </tool_call>
Assistant
The command is being interpreted but the shell command is very complex and seems to be causing issues. Let me try a simpler approach using Python directly.
Assistant
Great! The test shows the fix is working. Let me run a few more edge case tests to verify:
Assistant
All tests pass. Let me verify the change I made to the file is correct by viewing it:
Assistant
The fix is working correctly. Let me now run the complete session tests again to ensure everything passes:
Assistant
The fix is complete and all tests pass. Let me summarize what I've done:
Summary
Bug Description
The
retain_recent_legal_suffixmethod innanobot/session/manager.pywas causing user messages to be duplicated between archive and kept when the else branch was triggered (i.e., when the recent N messages were all assistant/tool messages).Root Cause
In the
enforce_file_capmethod, the code was calculating dropped messages asbefore[:dropped_count], which assumes that the firstdropped_countmessages from the original list are the ones that were dropped. However, whenretain_recent_legal_suffixis called and the else branch is triggered, the retained messages might not be at the end of the list - they could be scattered throughout. This caused user messages that were retained to also be included in the dropped list.Fix Applied
Changed line 331 in :
Assistant
I've verified the fix is in place. Let me submit it now.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.