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
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /nanobot, current file: none) bash-$
Assistant
Let me understand the issue first. The bug is in
nanobot/session/manager.pyin theretain_recent_legal_suffixmethod. When the else branch is triggered (recent N messages are all assistant/tool messages), thecutvalue calculation useslen(tail) - len(kept)without considering the actual position of the user message. This causes user messages to be incorrectly archived to botharchiveandkept.Let me start by exploring the repository structure and finding the relevant file.
Assistant
Let me find the specific file mentioned in the issue.
Assistant
I need to use the correct syntax for the open command. Let me check the documentation again.
Looking at the usage:
Usage: open [OPTIONS] [FILE] [LINE_NUMBER]It seems like the arguments should be positional, not named. Let me try a different approach.
Assistant
Let me search for the
retain_recent_legal_suffixmethod specifically:Assistant
Now I see the method. But the issue description mentions a function that returns
tuple[list[dict], int]. Let me search more broadly - the issue mentions the function signature should bedef retain_recent_legal_suffix(self, max_messages: int)that returnstuple[list[dict], int]. Let me check if there's a different version:Assistant
Now I understand the issue better. Let me re-read the issue description carefully. The bug description talks about
retain_recent_legal_suffixand how it's supposed to return a tuple(list[dict], int)- dropped messages and a count. But the current implementation doesn't return anything.Wait, let me re-read the interface section more carefully:
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.So the issue is describing what the function should do vs what it currently does. But the actual bug description is about the else branch causing user messages to be duplicated.
Let me re-read the bug more carefully. The issue says:
- When the else branch is triggered (recent N messages are all assistant/tool messages)
- The
cutvalue calculation useslen(tail) - len(kept)without considering user message position - User messages are incorrectly archived to both
archiveandkept
But wait, the current code doesn't have
cut,archive,tail, orkeptvariables in the method I see. Let me look at where this method is called from:Assistant
Now I see the issue! The bug is in
memory.py, not inmanager.py. Let me look at more context around this code:Assistant
Now I see the bug clearly. The issue is in
memory.pyincompact_idle_session. Let me trace through the logic:tail = list(session.messages[session.last_consolidated:])- gets unconsolidated messages- A
probeSession is created withtail.copy() probe.retain_recent_legal_suffix(max_suffix)is called - this trimsprobe.messagesin-placekept = probe.messages- the retained messagescut = len(tail) - len(kept)- calculates the cut pointarchive_msgs = tail[:cut]- archives the firstcutmessages fromtail
The problem is: when
retain_recent_legal_suffixtriggers the else branch (no user message in the recent tail), it may extend backwards to include user messages from earlier intail. Butcutis calculated based on lengths only, not on the actual indices of messages.Let me trace through an example from the issue:
tail= 100 messages (indices 0-99 in tail)max_suffix= 10retainedstarts astail[-10:]= messages 90-99- No user message in
retained(all assistant/tool) latest_user= 85 (inself.messages, which is the probe's messages, i.e., tail)retained = self.messages[85: 85 + 10]= messages 85-94- So
probe.messages(kept) = 10 messages (indices 85-94) cut = len(tail) - len(kept) = 100 - 10 = 90archive_msgs = tail[:90]= messages 0-89
Bug: Message at index 85 (the user message) is in BOTH
archive_msgs(0-89) andkept(85-94)!The fix should be: instead of
cut = len(tail) - len(kept), we need to find the actual starting index ofkeptwithintail. Sinceretain_recent_legal_suffixmodifiesprobe.messagesin-place, we need to know wherekeptstarts.The simplest fix would be to modify
retain_recent_legal_suffixto also return the starting index of the kept messages. Or we could modify the approach incompact_idle_session.Actually, looking at the interface description again:
Output: tuple[list[dict], int] Description: Trims the session's message list to at most
max_messageswhile preserving a legal suffix ... 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.The intended design is that
retain_recent_legal_suffixshould return the dropped messages, so the caller doesn't need to calculate the cut. Let me check the tests to understand expected behavior:Assistant
Now let me look at the
compact_idle_sessionmethod more carefully and understand the exact bug. The issue is inmemory.py. Let me create a test script to reproduce the bug:Assistant
I've confirmed the bug. Now let me understand the fix needed. The problem is in the
compact_idle_sessionmethod inmemory.py. Whenretain_recent_legal_suffixoperates in the else branch, it doesn't just take the last N messages - it goes back to find the latest user message and takes a window from there. Butcompact_idle_sessioncalculatescutbased on lengths, not on the actual starting position.The fix should be in
compact_idle_sessionto correctly determine the archive boundary. There are a few approaches:- Modify
retain_recent_legal_suffixto return the dropped messages - This matches the interface description in the issue - Track the starting index in
compact_idle_session- Compare kept messages with tail to find the actual start index
Looking at the interface description, option 1 seems to be the intended approach: "Returns the list of dropped messages and a count of how many of those were already in the consolidated prefix."
Let me look at how the method is used in all callers to understand the impact:
- Modify
Assistant
Now I see there are multiple places with the same pattern. The approach described in the interface section is:
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.
So the fix should modify
retain_recent_legal_suffixto return(dropped_messages, consolidated_count)and update all callers.But wait, let me re-read the issue description more carefully. The issue says "Bug: retain_recent_legal_suffix 在 else 分支下会导致用户消息被重复归档". This translates to "Bug: retain_recent_legal_suffix causes user messages to be duplicated in the archive under the else branch."
Looking at the expected behavior:
cut = latest_user # Should be 85, not 90 archive = tail[:85] # [0-84], does not include user message kept = tail[85:] # [85-99], includes user messageThe issue is that when
retain_recent_legal_suffixreturns (via modifyingself.messages), the caller incompact_idle_sessioncalculatescutbased on lengths, but it should use the actual position wherekeptstarts intail.The simplest fix would be to change
retain_recent_legal_suffixto return the dropped messages directly, so the caller doesn't need to guess the cut position.Let me implement the fix:
Assistant
Now I understand the full picture. The current implementation modifies
self.messagesin-place. The fix should make the method return the dropped messages so the caller can use them directly instead of calculatingcut.According to the interface description:
Output: tuple[list[dict], int] Returns the list of dropped messages and a count of how many of those were already in the consolidated prefix
Let me implement this:
Assistant
The edit command arguments are not being parsed correctly. Let me try a different approach - using bash to make the edit:
Assistant
Let me verify the changes look correct:
Assistant
Good. Now I need to update the callers to use the returned value instead of calculating
cut. Let me updatememory.py:Assistant
Now I need to update this. The key change is to use the returned
dropped_messagesdirectly instead of calculating the cut:Assistant
The sed with newlines didn't work. Let me try a different approach - using Python to make the edit:
Assistant
Now let me also update the
cli/commands.pycaller. This one just callsretain_recent_legal_suffixwithout using the return value, so it should be fine to just ignore the return value:Assistant
This caller ignores the return value, which is fine - the return value can be safely ignored. The method still modifies
self.messagesin place, so the behavior is the same. No changes needed here.Now let me update the test file to handle the new return type:
Assistant
I should not modify the tests. The test file will need the same fix in
memory.py. But wait, I should NOT modify tests. The test is essentially a mock that simulates the same pattern. Let me check if this is a test helper that gets imported or if it's actual test code:Assistant
This is a test file that tests auto compact. The test has its own copy of the same buggy pattern. Since I can't modify tests, I need to make sure the method is backward compatible.
Actually, the issue says I should NOT modify tests. But the tests will break because they call
retain_recent_legal_suffixwithout capturing the return value. Let me check if the existing tests will still work:The test does:
probe.retain_recent_legal_suffix(max_suffix) kept = probe.messages cut = len(tail) - len(kept) archive_msgs = tail[:cut]Since the method now returns a tuple but the test doesn't capture it, this should still work - Python doesn't error if you don't capture a return value. The test will have the same bug, but that's the test's internal logic, not the method itself.
Let me also check the tests in
test_session_manager_history.py:Assistant
These tests ignore the return value, which is fine - they just check
session.messagesandsession.last_consolidatedafter calling the method. The method still modifiesself.messagesin-place, so these tests should still pass.Now let me run the tests to verify:
Assistant
All tests pass. Now let me also run the auto_compact tests:
Assistant
All 50 tests pass. Now let me verify that my bug fix script confirms the bug is fixed:
Assistant
The bug still exists! Let me debug why. The issue is that my fix returns
dropped_messagesfromself.messages, but when theelsebranch is triggered,retainedis set toself.messages[latest_user: latest_user + max_messages], which starts fromlatest_user. Sodropped_messagesshould beself.messages[:latest_user](before the retained window), not just based on lengths.Let me trace through:
self.messages= 100 messagesretained = self.messages[-10:]= messages 90-99 (10 messages)- No user message in
retained(all assistant) latest_user = 85retained = self.messages[85: 95]= messages 85-94 (10 messages)dropped_messages = self.messages[:-10]= messages 0-89 (90 messages)
But the problem is: messages 85-89 are in BOTH
dropped_messagesandretained! That's becauseretainedstarts at index 85 butdropped_messagesis calculated as all messages except the last 10.Wait, I see the issue now. When the
elsebranch takesself.messages[latest_user: latest_user + max_messages], the retained messages start atlatest_user, not atlen(self.messages) - max_messages. So the dropped messages should beself.messages[:latest_user], notself.messages[:-len(retained)].Let me fix this by tracking the actual start index of
retained:Assistant
I see the issue clearly now. I need to track the actual start index of the retained window in the original message list. Let me rewrite the method properly:
Assistant
Continuing with the fix. I need to track the actual start index of the retained window so that dropped_messages is calculated correctly.
Assistant
Let me verify the new code:
Assistant
I see there's a problem - the
enforce_file_capmethod definition got merged with the previous method. Let me check the full file to see what happened:Assistant
The
enforce_file_capmethod is missing itsdefline. Let me fix this:Assistant
Let me fix the triple-quote issue:
Assistant
Good, the file is now properly formatted. Let me verify the complete method one more time:
Assistant
Now let me run my test script again:
Assistant
The bug is fixed. Now let me run the existing tests to make sure everything still works:
Assistant
All 79 tests pass. Let me also run a broader test to check for any other affected tests:
Assistant
All session-related tests pass. Now let me also run any tests related to memory and compact:
Assistant
All tests pass. Let me clean up the temporary test files:
Assistant
Now let me review my changes one final time to make sure everything is correct:
Assistant
The changes look correct. Let me verify my understanding of the fix and verify edge cases once more:
Assistant
The assertion is wrong - let me check what the actual result is:
Assistant
The bug is fixed correctly. The issue was my test assertion - when
latest_user = 85andmax_messages = 10,retained = messages[85:95]which is 10 messages, not 15. My test assertion was wrong.Let me fix the test and run it again:
Assistant
All edge case tests pass. Let me clean up and run the full test suite one more time:
Assistant
Assistant
Let me run the final tests to make sure everything passes.
Assistant
All 79 tests pass. Let me verify my final changes and submit.
Assistant
Let me review the checklist from the issue:
-
If an error was reported in the issue description, I have successfully reproduced it. ✅ - I created a test script that confirmed the bug: when the recent N messages are all assistant/tool messages and the user message is at an earlier position, the user message appeared in BOTH archive and kept.
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error. ✅ - After the fix, the user message only appears in kept, not in archive. I verified this with the test script.
-
I have thought about edge cases and made sure my fix handles them as well. ✅ - I tested:
- Normal case (user message in the tail)
- Zero max_messages
- No trim needed
- All assistant messages (no user)
- Hard cap excess scenario
- last_consolidated tracking
-
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. ✅ - All 79 tests in test_session_manager_history.py and test_auto_compact.py pass.
Let me submit now. </tool_call>
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →