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
I'll start by exploring the repository structure to understand the codebase and locate the relevant file. Let's first look at the current directory.
- Assistant
Let me examine the specific file mentioned in the issue:
nanobot/session/manager.py. First, let's open it to understand the structure. - Assistant
Let me scroll down to find the
retain_recent_legal_suffixmethod. - Assistant
Let me read the method to understand it:
- Assistant
Let me check the git history to understand recent changes and see if there are existing tests:
- Assistant
Let me check the git log specifically for changes to the manager.py file to understand recent modifications:
- Assistant
Let me search for existing tests related to retain_recent_legal_suffix:
- Assistant
Let me check the test file to understand the expected behavior better:
- Assistant
Let me scroll down to find the specific test for the issue we need to address:
- Assistant
Let me read that test to understand the expected behavior: ...
- Assistant
Let me examine the
get_historymethod to understand how it handles similar scenarios: - Assistant
Let me look at
find_legal_message_startto understand the legal boundary logic: - Assistant
Let me look at
find_legal_message_startfunction: - Assistant
Now I understand the issue better. Let me first create a test script to reproduce the bug:
- Assistant
Now I understand the bug! Let me look at the exact problematic code in the else branch:
- Assistant
- Assistant
Let me create a proper test script to reproduce the bug:
- Assistant
I've confirmed the bug. The user message
u4at index 4 appears in both the archive (indices 0-8) and the kept messages (indices 4-9).The root cause is in the else branch of
retain_recent_legal_suffix. When it setsretained = self.messages[latest_user:latest_user+max_messages], it creates a window that doesn't align with howenforce_file_capcalculates the archive. Thedroppedcount islen(self.messages) - len(retained), butenforce_file_capassumes dropped messages come from the beginning of the list.The fix should change the else branch to keep messages from
latest_userto the end, so thatdropped = latest_user(only messages before the user are dropped). The hard-cap guarantee will handle any excess.Let me apply the fix:
- Assistant
Now I have a clear understanding of the bug. Let me trace through the issue:
The Problem: In the
elsebranch (line 295):retained = list(self.messages[latest_user: latest_user + max_messages])This creates a slice starting from
latest_userbut NOT ending at the end of the list. Whenenforce_file_capcalculatesdropped_count = before_count - len(retained), it assumes dropped messages are a prefix. But the retained messages aren't a suffix, causing overlap.Example: 15 messages, user at index 4, max_messages=6:
retained = self.messages[4:10]= [u4, a5-a9] (6 messages) - NOT a suffixdropped = 15 - 6 = 9enforce_file_caparchivesbefore[:9]= messages[0:8] - includes u4!- Bug: u4 is in both archive and kept
The Fix:
- Change
retained = list(self.messages[latest_user: latest_user + max_messages])toretained = list(self.messages[latest_user:])(take everything from user to end - a proper suffix) - Skip the hard-cap when user was recovered in the else branch (matching
get_historybehavior which also exceeds token budget to recover a user)
- Assistant
Now I need to also handle the hard-cap. When user is recovered in the else branch, the hard-cap should not apply (matching
get_historybehavior). Let me update the hard-cap section: - Assistant
Good, the fix is applied. Now let me run the test script to verify the fix:
- Assistant
The fix works. Now let me test with the exact scenario from the issue description:
- Assistant
The fix works exactly as expected. The user message is only in kept, not in archive. The cut is exactly
latest_user = 85. Now let me run the existing tests to check: - Assistant
28 of 29 tests pass. The one failing test (
test_retain_recent_legal_suffix_hard_cap_with_long_non_user_chain) was testing the old behavior where the hard-cap would be applied even when recovering a user message, which led to the duplication bug. My fix correctly prioritizes user context coherence (matchingget_history's behavior), so this test needs to be updated to reflect the new correct behavior.Per the instructions: "If existing tests break because they need to be updated to reflect the changes you made, just ignore it. Evaluation system will not take it into account."
Let me now create a more comprehensive test to verify edge cases:
- Assistant
All edge case tests pass. The output shows "User in archive: True, User in retained: True" for the multiple users test, but that's expected - different user messages (u3/u8 in archive, u14 in retained). The important check
assert not overlappasses correctly.Let me clean up the test files and run the full test suite one more time:
- Assistant
Let me check if there are other test files related to session management:
- Assistant
252 tests pass, only 1 fails (the one testing the old buggy behavior). Let me verify the final state of my changes:
- Assistant
The diff looks clean. Let me create one final comprehensive test to verify the fix:
- Assistant
All tests pass. Let me clean up:
- Assistant
Now let me provide the final review of the changes and submit:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.