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 and understanding the issue better. The issue is about a bug in
nanobot/session/manager.pyin theretain_recent_legal_suffixmethod.First, I should:
- Find and examine the relevant file
- Understand the current implementation
- Reproduce the bug if possible
- Fix the bug
- Test the fix
Let me start by looking at the file structure and the relevant code.
Assistant
Let me look for the session manager file specifically.
Assistant
Found it. Let me open and examine the file.
Assistant
Good, the file is open. Let me see the
retain_recent_legal_suffixmethod which is likely towards the end of the file given the context. Let me scroll to see the method:Assistant
Let me view the
retain_recent_legal_suffixmethod around line 272:Assistant
Let me go directly to line 272 to see the method:
Assistant
<arg_key>bash_terminal</arg_key> <arg_value>goto 272</arg_value>
<arg_key>bash_terminal</arg_key> <arg_value>goto 272</arg_value>
Assistant
Let me try going to line 272 to see the method:
Assistant
Now I understand the issue. Looking at the code:
- When
first_useris not None (user message found in the tail), it takesretained = retained[first_user:]- this is correct - When
first_useris None (all assistant/tool messages in the tail), it does:- Finds
latest_userin the full session - Takes
retained = list(self.messages[latest_user: latest_user + max_messages])
- Finds
The problem is that this code doesn't exist in the current version. Looking at the issue description again:
The bug is about
retain_recent_legal_suffixwhere in the else branch, when all recent messages are assistant/tool, the user message is being incorrectly duplicated between archive and kept.But looking at the current code at line 272-316, I see a different implementation. The method at line 272 doesn't have the exact issue described - it uses
retained = list(self.messages[latest_user: latest_user + max_messages])which seems reasonable.- When
Assistant
Let me use the sed command correctly to view the enforce_file_cap method:
Assistant
Looking at the issue description again, it seems like the problem might have been fixed or the description is outdated. Let me check the git history to see if there have been recent changes:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && git log --oneline -10 -- nanobot/session/manager.py </tool_call>
Assistant
The bash_terminal command is not working with "cd" syntax. Let me just use the command properly:
Assistant
The issue description mentions that there's a bug where
cutis calculated usinglen(tail) - len(kept)in the else branch. Looking at the current code, I don't see this issue - the current code usesretained = list(self.messages[latest_user: latest_user + max_messages])which seems correct.Wait, let me re-read the issue description more carefully. The expected behavior shows:
# 期望: cut = latest_user # 应该是 85,不是 90 archive = tail[:85] # [0-84],不包含用户消息 kept = tail[85:] # [85-99],包含用户消息及其后续内容This suggests that there's code that calculates
cutusing something likelen(tail) - len(kept)instead of usinglatest_userdirectly.But looking at the current code, it seems the bug has already been fixed or the code is different. Let me check if there's another implementation or if this is a different method.
Actually, wait - the issue description mentions a
drop_messagesmethod that returns a tuple. Let me search for that:<tool_call> <function=bash_terminal> <parameter=command> grep -n "drop_messages|drop_message|drop =" /nanobot/nanobot/session/manager.py </tool_call>
Assistant
Let me search properly for drop-related functions. The grep command seems to have failed, so let me try a different approach.
Assistant
Assistant
Let me properly call the bash_terminal tool to view the enforce_file_cap method.
Assistant
Assistant
I need to properly call grep to search for retain_recent_legal_suffix usages.
Assistant
Assistant
Let me re-run the grep command properly to find the line number of the method definition.
Assistant
Let me first create a test script to reproduce the bug, then implement the fix.
Assistant
Assistant
I need to use the proper format for the bash_terminal tool. Let me re-run the command correctly.
Assistant
I've successfully reproduced the bug. The issue is clear:
- Retained messages are at indices 85-94
- Dropped messages are incorrectly computed as
before[:90], which includes indices 0-89 - Messages at indices 85-89 are in BOTH retained and dropped (duplicated!)
Now I need to implement a fix. The cleanest approach is to modify
retain_recent_legal_suffixto return the dropped messages, then update all callers.Let me implement the fix:
Assistant
Now I need to fix the bug. The issue is in
enforce_file_capwhere it computesdropped = before[:dropped_count]. Instead, we need to track which messages were actually retained so we can compute the correct dropped messages.The cleanest fix is to modify
retain_recent_legal_suffixto return the dropped messages. Let me implement this:Assistant
Assistant
I need to use the bash_terminal tool properly. Let me create and run the Python script to fix the issue.
Assistant
Now let me verify the fix was applied correctly and test it:
Assistant
The bug still exists. The issue is that the test script is still using the old method of computing
dropped = before[:dropped_count]. But the test script doesn't useenforce_file_cap, it just callsretain_recent_legal_suffixdirectly.The real bug is that the test script is computing
dropped = before[:dropped_count]manually. Let me update the test script to properly test the fix by using the returned value fromretain_recent_legal_suffix.Actually, looking at the test output more carefully, I see that the test is calling
session.retain_recent_legal_suffix(10)without capturing the return value. My fix should have changed the method to return(dropped_messages, dropped_count), but the test is not using the returned value.Let me verify that the fix was applied correctly to the source file:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '272,340p' /nanobot/nanobot/session/manager.py </tool_call>
Assistant
Let me properly call the bash_terminal tool to view the fixed code.
Assistant
The fix was applied to
retain_recent_legal_suffix. Now let me check theenforce_file_capmethod:<tool_call> <function=bash_terminal> <parameter=command> sed -n '340,370p' /nanobot/nanobot/session/manager.py </tool_call>
Assistant
Let me view the enforce_file_cap method to verify the fix was applied there as well.
Assistant
Assistant
Let me run the test properly using the bash_terminal tool.
Assistant
Assistant
The bash_terminal command is not working properly with the heredoc syntax. Let me try a different approach - I'll use a simpler test script.
Assistant
The fix is working. Now let me test the
enforce_file_capmethod and update the other callers:Assistant
Assistant
Let me run the command properly to test the enforce_file_cap method with proper accumulation.
Assistant
The fix is working. Now I need to update the other callers of
retain_recent_legal_suffixto handle the new return type. Let me check and update each caller:Assistant
Let me view more context around this call in the agent/memory.py file.
Assistant
Let me view the context around line 810 in the agent/memory.py file. I should use sed to get a wider view to understand what the code is doing.
Assistant
I see. In the agent/memory.py file, the code is using
retain_recent_legal_suffixand then computingcut = len(tail) - len(kept)to determine which messages to archive. This is exactly the same bug pattern! The code is computingarchive_msgs = tail[:cut]which would be incorrect whenkeptstarts from the middle oftail.Wait, but this is using a different pattern. Let me analyze:
probeis a new Session withmessages=tail.copy()(a copy of the tail)probe.retain_recent_legal_suffix(max_suffix)is called
Assistant
I need to view the context in the agent/memory.py file to understand how to fix it. Let me use sed properly.
Assistant
Now I need to fix the agent/memory.py file. Let me create a Python script to patch it:
Assistant
Now let me verify the fix was applied:
Assistant
Assistant
The command is not being executed. Let me try with a different approach to run the test.
Assistant
Now I need to check and update the other callers of
retain_recent_legal_suffix. Let me check the CLI commands file:Assistant
I need to view more context around this call in the CLI commands file to see if it needs to be updated.
Assistant
Let me view the context around line 1032 in the CLI commands file:
Assistant
The CLI commands call just discards the return value (using
session.retain_recent_legal_suffix(...)without capturing the result), which is fine. The function still returns a value, but the caller doesn't use it. This should be fine.Now let me check the test files to see if they need to be updated:
Assistant
The tests are calling
session.retain_recent_legal_suffix(...)without capturing the return value. Since the tests only check the state ofsession.messagesafter the call, they should still work. However, to be safe, I should update the tests to ignore the return value.Actually, looking at the tests more carefully, they don't use the return value, so they should still work. But I should also check if the tests in
test_auto_compact.pyneed to be updated.Let me check that file:
<tool_call> <function=bash_terminal> <parameter=command> grep -B3 -A5 "retain_recent_legal_suffix" /nanobot/tests/agent/test_auto_compact.py </tool_call>
Assistant
Let me try to run the grep command to check the test_auto_compact.py file.
Assistant
I need to update the test file
test_auto_compact.pyas well since it has the same buggy pattern. Let me find and fix it:Assistant
Let me view the context around line 79 in the test_auto_compact.py file.
Assistant
This is in a test file, but it's actually testing the same buggy pattern. I should fix it to use the correct pattern:
<tool_call> <function=bash_terminal> <parameter=command> python3 << 'PYEOF'
Read the file
with open('/nanobot/tests/agent/test_auto_compact.py', 'r') as f: content = f.read()
Fix: Update the call to retain_recent_legal_suffix to use returned values
old_code = ''' probe.retain_recent_legal_suffix(max_suffix) kept = probe.messages cut = len(tail) - len(kept) archive_msgs = tail[:cut]'''
new_code = ''' archive_msgs, _ = probe.retain_recent_legal_suffix(max_suffix) kept = probe.messages'''
content = content.replace(old_code, new_code)
Write the file
with open('/nanobot/tests/agent/test_auto_compact.py', 'w') as f: f.write(content)
print("Fixed tests/agent/test_auto_compact.py") PYEOF </tool_call>
Assistant
Let me try running the python command to fix the test file.
Assistant
Now I need to update the test files to capture the return value instead of ignoring it. Let me check all the tests in test_session_manager_history.py and update them:
<tool_call> <function=bash_terminal> <parameter=command> python3 -c " with open('/nanobot/tests/agent/test_session_manager_history.py', 'r') as f: content = f.read()
The tests don't need to change because they don't use the return value
Just need to make sure they work with the new signature
print('Test file doesn\'t need changes (return value not used)') " </tool_call>
Assistant
Let me run the command to check if the test file needs changes.
The tests in test_session_manager_history.py don't use the return value, so they should still work. However, I should run the tests to make sure my changes don't break anything.
Let me run the existing tests to see if they pass.
Assistant
Good, all tests in test_session_manager_history.py pass! Let me also run the test_auto_compact.py tests:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python -m pytest tests/agent/test_auto_compact.py -v 2>&1 | head -80 </tool_call>
Assistant
I need to run the test_auto_compact.py tests to ensure my changes don't break them. Let me execute the pytest command.
Assistant
All tests pass! Now let me verify the bug fix once more by running the original test case:
<tool_call> <function=bash_terminal> <parameter=command> python3 -c " import sys sys.path.insert(0, '/nanobot') from nanobot.session.manager import Session
Test case: user message at index 85, 100 messages, max_messages=10
session = Session(key='test:key') messages = [] for i in range(100): if i == 85: messages.append({'role': 'user', 'content': f'User message {i}'}) elif i < 85: if i % 3 == 0: messages.append({'role': 'user', 'content': f'User message {i}'}) else: messages.append({'role': 'assistant', 'content': f'Assistant message {i}'}) else: messages.append({'role': 'assistant', 'content': f'Assistant message {i}'})
Assistant
I need to run a verification test to confirm the bug fix is working. Let me use a simpler approach to execute the test.
Assistant
The bug is fixed. Let me run all related tests to make sure everything still works:
Assistant
All tests pass. Let me run a broader set of tests to make sure the fix doesn't break anything else:
Assistant
The tests are passing. Let me now verify the changes I've made and summarize the fix:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && git diff --stat </tool_call>
Assistant
Let me run the git diff command to see the changes made.
Assistant
Let me view the full diff to see the changes I made:
Assistant
Now let me view the changes to agent/memory.py and test_auto_compact.py:
Assistant
Assistant
Let me run a simpler test to verify the edge cases.
Assistant
Assistant
Let me fix the minor issue with the
max_messages = 0case and then submit the fix. First, let me check the current behavior:Assistant
Let me fix the minor issue with the
max_messages <= 0case:Assistant
Wait, that's not right. After
self.clear(), the session is empty, solist(self.messages)would be empty. Let me fix this properly:Assistant
Now let me verify the fix:
Assistant
Now let me run the tests again to make sure everything still works:
Assistant
Let me run a final verification to confirm the fix:
Assistant
Wait, the output says "User in dropped=True", which is unexpected. Let me check this more carefully - the issue is that there's a user message in dropped, which is not the one at index 85.
The test setup has user messages at indices 0, 3, 6, 9, ..., 84 (every 3rd index from 0 to 84). The retained messages are at indices 85-94. So the user message at index 85 is in retained, and user messages at indices 0, 3, 6, ..., 84 are in dropped.
Assistant
The bug fix verification shows that the fix is working correctly:
- Duplicate check passed:
Duplicate indices in retained: []- No messages appear in both dropped and retained - Retained messages are correct: Indices 85-94 (user message at 85 and subsequent assistant messages)
- Dropped messages are correct: Indices 0-84 (messages before the retained slice)
- User message handling: The user message at index 85 is correctly in retained, while earlier user messages (0, 3, 6, ..., 84) are correctly in dropped
The fix addresses the original issue:
- Before:
dropped = before[:dropped_count]incorrectly included messages 85-89 (which should be retained) - After:
dropped = dropped_messagescorrectly computes only messages that were actually dropped
- Duplicate check passed:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.