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
shellnanobot Version
0.2.0
Python Version
3.11
Operating System
Windows
Channel / Platform
Weixin (Personal WeChat)
LLM Provider
OpenAI
Configuration (Optional)
yamlAdditional 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 then locate the file mentioned in the issue -
nanobot/session/manager.py.Assistant
Found it! Let me read the
retain_recent_legal_suffixmethod innanobot/session/manager.py.Assistant
The output was truncated. Let me search for the
retain_recent_legal_suffixmethod specifically.Assistant
Let me view the
retain_recent_legal_suffixmethod in detail by reading from line 272 onwards.<tool_call> <function=bash_terminal> <parameter=command> sed -n '272,330p' /nanobot/nanobot/session/manager.py </tool_call>
Assistant
Let me use bash_terminal properly to view the method.
Assistant
Now I can see the issue clearly. Let me analyze the method:
-
The
retain_recent_legal_suffixmethod (lines 272-313) is designed to keep a legal recent suffix constrained by a hard message cap. -
The issue is in the
elsebranch (lines 290-298) where if the tail is assistant/tool-only, it anchors to the latest user in the full session.
Let me look at the
enforce_file_capmethod to understand the context better and see how the return values are used.<tool_call> <function=bash_terminal> <parameter=command> grep -n "def retain_recent_legal_suffix" /nanobot/nanobot/session/manager.py -A 100 | head -120 </tool_call>
-
Assistant
The method is called but the return type is
None. Let me check what method callsretain_recent_legal_suffixand returns a tuple to understand the flow better.Assistant
Now I understand the issue. Let me analyze the bug:
Current behavior:
- When the
elsebranch runs,retained = messages[latest_user:latest_user+max_messages] - Then
dropped_count = before_count - len(self.messages)calculates incorrectly - This causes the first
dropped_countmessages (before[:dropped_count]) to include messages that are also inretained
Example scenario:
- 100 messages (0-99), last_consolidated = 10, max_messages = 10
- Latest 10 messages (90-99) are all assistant/tool
- Latest user message is at position 85
Current buggy calculation:
retained = messages[85:95](10 messages)dropped_count = 100 - 10 = 90dropped = before[:90] = messages[0:90]archive_chunk = messages[10:90]← includes message 85 (user)
- When the
Assistant
Now let me check if there are any existing tests for the session manager.
Assistant
Let me create a script to reproduce the bug first, and then fix it.
Assistant
The bug is confirmed! Now let me fix the issue. The problem is that when the else branch runs, the
dropped_countcalculation is incorrect. The fix needs to track what was actually dropped from the front.Looking at the code flow:
enforce_file_capcallsretain_recent_legal_suffix(limit)- Then calculates
dropped_count = before_count - len(self.messages) - Then takes
archive_chunk = dropped[already_consolidated:]
The issue is that when the else branch runs, messages are removed from the END of the session, not from the front. So
dropped_countincorrectly includes messages that are still in the retained list.The fix needs to:
- Have
retain_recent_legal_suffixreturn information about which messages were dropped from the front
Assistant
Let me open the file directly to see the exact content that needs to be modified.
Assistant
Assistant
Let me use bash_terminal instead to run the python script.
Assistant
The file wasn't created. Let me try a different approach - using sed or direct editing.
Actually, I realize my heredoc approach may have issues. Let me use a simpler approach with bash_terminal to write the fix.
Assistant
Now let me update the
enforce_file_capmethod:Assistant
Now let me test the fix with the reproduction script:
Assistant
The bug is fixed! The user message 85 now only appears in retained, not in archive. The archive size went from 80 to 75, which is correct (10 to 85 = 75 messages).
Now let me run the existing tests to make sure the fix doesn't break anything:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python -m pytest tests/ -v --tb=short 2>&1 | head -100 </tool_call>
Assistant
Let me run the tests again using bash_terminal properly.
Assistant
Tests are passing so far. Let me run more tests to check if there are any failures:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python -m pytest tests/ -v --tb=short 2>&1 | tail -100 </tool_call>
Assistant
The tests seem to be running. Let me wait for them to complete and check the final result.
Assistant
Two tests failed. Let me check the failing test for
retain_recent_legal_suffix:<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python -m pytest tests/agent/test_session_manager_history.py::test_retain_recent_legal_suffix_adjusts_last_consolidated -v --tb=long </tool_call>
Assistant
The bash_terminal command needs to be invoked properly. Let me try again.
Assistant
The test failure is related to my modification. The issue is that my fix changed how
last_consolidatedis calculated, but I didn't update it correctly. Let me look at the test and my fix to understand what went wrong.The test expects:
- 10 messages, last_consolidated = 7
- After retain_recent_legal_suffix(4), retained = 4 messages (messages 6-9)
- last_consolidated should be adjusted to 1 (7 - 6 = 1, since 6 messages were dropped from the front)
Assistant
Let me use bash_terminal to view the current state of the file.
Assistant
The problem is that I need to also update last_consolidated correctly. The cut_point is the index in the ORIGINAL messages list where the retained suffix starts. So last_consolidated should become max(0, last_consolidated - cut_point).
Let me fix this:
<tool_call> <function=bash_terminal> <parameter=command> cat > /nanobot/fix_last_consolidated.py << 'ENDOFFILE'
Read the original file
with open('/nanobot/nanobot/session/manager.py', 'r') as f: content = f.read()
Fix: Update last_consolidated in retain_recent_legal_suffix
old_line = ''' self.messages = retained self.updated_at = datetime.now() return cut_point, len(self.messages)'''
new_line = ''' self.messages = retained self.last_consolidated = max(0, self.last_consolidated - cut_point) self.updated_at = datetime.now() return cut_point, len(self.messages)'''
Apply the fix
if old_line in content: content = content.replace(old_line, new_line) with open('/nanobot/nanobot/session/manager.py', 'w') as f: f.write(content) print("Fix applied successfully!") else: print("ERROR: Could not find the line to fix") ENDOFFILE python /nanobot/fix_last_consolidated.py </tool_call>
Assistant
The bash_terminal command should be run to execute the script. Let me do that.
Assistant
The heredoc isn't creating the file properly. Let me try a different approach using sed to make the change directly.
<tool_call> <function=bash_terminal> <parameter=command> sed -i 's/self.messages = retained$/self.messages = retained\n self.last_consolidated = max(0, self.last_consolidated - cut_point)/' /nanobot/nanobot/session/manager.py </tool_call>
Assistant
Let me try a different approach - I'll use Python directly with the -c flag to make the change.
Assistant
Now let me run the failing test again to see if this fixes the issue:
Assistant
Now let me verify the bug fix is still in place:
Assistant
Now let me run all the tests again to make sure everything passes:
Assistant
Let me check if the failing test is related to my changes:
Assistant
Let me check if this test was already failing before my changes by restoring the original file temporarily:
Assistant
Let me check if the MCP test was already failing before my changes by testing it against the original code:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && git stash </tool_call>
Assistant
The stash command should be run to save my changes.
Assistant
The test was already failing before my changes, so this is a pre-existing issue unrelated to my fix. Let me restore my changes and verify all session-related tests pass:
Assistant
Good, my changes are back. Now let me run all the session-related tests to make sure my fix works correctly:
Assistant
All 29 tests in the session manager history test file pass. Let me also run tests related to the auto_compact feature since that's where
enforce_file_capis used:<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python -m pytest tests/agent/test_auto_compact.py -v </tool_call>
Assistant
The command was not invoked. Let me retry it with bash_terminal.
Assistant
Assistant
The heredoc approach for Python is not working properly in the bash terminal. Let me write the script to a file first and then run it.
Assistant
I see the test expectation was incorrect. Let me verify my understanding and update the test:
Assistant
All edge case tests pass. Now let me view the final state of the fixed file to summarize the changes:
Assistant
The changes are now complete. Let me clean up the temporary test files I created and run a final verification:
<tool_call> <function=bash_terminal> <parameter=command> rm -f /nanobot/reproduce_bug.py /nanobot/fix_manager.py /nanobot/fix_manager2.py /nanobot/fix_last_consolidated.py /nanobot/fix.py /nanobot/test_edge_cases.py </tool_call>
Assistant
Let me clean up the temporary files using the bash_terminal.
Assistant
Now let me run the final test suite to make sure everything passes:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python -m pytest tests/agent/test_session_manager_history.py tests/agent/test_auto_compact.py -v --tb=short 2>&1 | tail -30 </tool_call>
Assistant
The command was not executed because I need to use bash_terminal to run the test command. Let me try again.
Assistant
All 79 tests pass. Let me now view the final modified file to ensure the fix is complete:
Assistant
The fix looks correct. Let me also verify that I haven't introduced any issues with the return type changes. Let me check if there are any other callers of
retain_recent_legal_suffix:Assistant
Now I see there are other callers of
retain_recent_legal_suffixthat don't expect a return value. I need to update those callers to handle the new return type, or I need to make sure the return value is simply ignored.Looking at the callers:
nanobot/nanobot/agent/memory.py- calls but doesn't use return valuenanobot/nanobot/cli/commands.py- calls but doesn't use return valuenanobot/tests/agent/test_auto_compact.py- calls but doesn't use return valuenanobot/tests/agent/test_session_manager_history.py- multiple tests that don't use return value
Since Python allows calling functions that return values without using the return value, these should work fine. But let me verify by running the full test suite again:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python -m pytest tests/ --tb=short 2>&1 | grep -E "(PASSED|FAILED|ERROR)" | head -20 </tool_call>
Assistant
I need to run the test command using bash_terminal. Let me do that.
Assistant
Let me run the full test summary:
<tool_call> <function=bash_terminal> <parameter=command> cd /nanobot && python -m pytest tests/ --tb=short 2>&1 | tail -10 </tool_call>
Assistant
I need to use bash_terminal to run the test command. Let me do that properly.
Assistant
All tests pass (3775 passed). The only failing test (
test_test_mcp_preset_connects_and_reports_tools) is a pre-existing issue unrelated to my fix, as I verified earlier by running it against the original code.Let me provide a summary of the changes made:
Summary of Fix
Issue
The
retain_recent_legal_suffixmethod innanobot/session/manager.pyhad a bug where when the else branch was triggered (all recent N messages were assistant/tool messages), thecutvalue calculation usedlen(tail) - len(kept)without considering the actual position of the user message. This caused user messages to be incorrectly included in both the archive (pending compression) and kept (retention) lists.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.